mirror of
https://github.com/Xevion/contest.git
synced 2025-12-15 10:11:27 -06:00
properly rename october 2013 mispell
This commit is contained in:
246
uil/aplus-october-2013/3/input-generator/main.py
Normal file
246
uil/aplus-october-2013/3/input-generator/main.py
Normal file
@@ -0,0 +1,246 @@
|
||||
import os, sys, math, time, random
|
||||
|
||||
class Node(object):
|
||||
def __init__(self, parent=None, position=None):
|
||||
self.parent, self.position = parent, position
|
||||
self.g, self.h, self.f = 0, 0, 0
|
||||
|
||||
def __eq__(self, other):
|
||||
assert type(other) == Node, "Node cannot compared against type \"{}\"".format(str(type(other)))
|
||||
return self.position == other.position
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Node ({self.position[0]}, {self.position[1]})>'
|
||||
|
||||
@classmethod
|
||||
def positionify(self, nodes):
|
||||
return [node.position for node in nodes]
|
||||
|
||||
# Generate a grid and return it to the user
|
||||
class SnakeGrid(object):
|
||||
def __init__(self, x, y, length=3):
|
||||
self.x, self.y, self.length, self.sleepTime = x, y, length, 0.0
|
||||
# Right, Down, Up, Left
|
||||
self.offsets = [[0, 1], [1, 0], [-1, 0], [0, -1]]
|
||||
self.offsetLetters = list("RDUL")
|
||||
self.generate()
|
||||
|
||||
def sleep(self, seconds):
|
||||
self.sleepTime += (seconds, time.sleep(seconds))[0]
|
||||
|
||||
def generate(self):
|
||||
assert self.x > 2 + self.length and self.y > 3, "Dimensions must be able to at least fit the snake"
|
||||
|
||||
# Grid is a matrix of single space strings
|
||||
self.matrix = [[' ' for xx in range(self.x + 1)] for yy in range(self.y + 1)]
|
||||
|
||||
# Choose a initial position
|
||||
self.positions = [self.getPos(-1, -1)]
|
||||
self.mark(self.positions[0])
|
||||
curlength = self.length - 1
|
||||
|
||||
# Start drawing up the snake
|
||||
while curlength > 0:
|
||||
left, right = [self.positions[0][0], self.positions[0][1] - 1], [self.positions[-1][0], self.positions[-1][1] + 1]
|
||||
canLeft, canRight = self.available(left), self.available(right)
|
||||
curlength -= 1
|
||||
|
||||
# If both options are available, just choose one and act like the other is unavailable
|
||||
if canLeft and canRight:
|
||||
if random.choice([True, False]): canLeft = False
|
||||
else: canRight = False
|
||||
|
||||
if canLeft != canRight:
|
||||
if canLeft:
|
||||
self.mark(left)
|
||||
self.positions.insert(0, left)
|
||||
if canRight:
|
||||
self.mark(right)
|
||||
self.positions.append(right)
|
||||
elif not (canLeft or canRight):
|
||||
print(positions, left, right)
|
||||
print("Could not resolve any position to use...?")
|
||||
|
||||
# Populate with 3-7 pellets
|
||||
for _ in range(random.randint(2, 5)):
|
||||
while True:
|
||||
pos = self.getPos()
|
||||
if self.available(pos):
|
||||
self.mark(pos, 'F')
|
||||
break
|
||||
|
||||
# Pythagorean distance calculation
|
||||
def distance(self, pos1, pos2):
|
||||
return math.sqrt(((pos1[0] - pos2[0]) ** 2) + ((pos1[1] - pos2[1]) ** 2))
|
||||
|
||||
# Returns all positions with the specified character (by default, 'F', for pellets)
|
||||
def pellets(self, char='F'):
|
||||
pelletss = []
|
||||
for yy in range(self.y):
|
||||
for xx in range(self.x):
|
||||
if self.available([xx, yy], look=char):
|
||||
pelletss.append([xx, yy])
|
||||
return pelletss
|
||||
|
||||
# Returns the best pellet to path to based on distance and a specified blacklist of positions
|
||||
def bestPellet(self, curpos, blacklist=[]):
|
||||
potential = self.pellets()
|
||||
if blacklist:
|
||||
potential = list(filter(lambda item : item not in blacklist, potential))
|
||||
# Returns None if no potential pellets are in due to blacklist
|
||||
if not potential:
|
||||
return None
|
||||
return min(potential, key=lambda pos : self.distance(curpos, pos))
|
||||
|
||||
# Quick code for calcul
|
||||
def merge(self, pos1, pos2):
|
||||
return [pos1[0] + pos2[0], pos1[1] + pos2[1]]
|
||||
|
||||
def solution(self, maxdist=20, startpos=None):
|
||||
pelletCount, path = self.generateSolutions(maxdist=maxdist, startpos=startpos)
|
||||
for i, pos in enumerate(path):
|
||||
if self.available(pos):
|
||||
self.mark(pos, str(i))
|
||||
return pelletCount, self.mapPositions(path)
|
||||
|
||||
def mapPositions(self, positions):
|
||||
letters = []
|
||||
curpos = positions.pop(0)
|
||||
while len(positions) > 0:
|
||||
nextpos = positions.pop(0)
|
||||
offset = [nextpos[0] - curpos[0], nextpos[1] - curpos[1]]
|
||||
letters.append(offset)
|
||||
curpos = nextpos
|
||||
letters = list(map(lambda item : self.offsetLetters[self.offsets.index(item)], letters))
|
||||
return ''.join(letters)
|
||||
|
||||
# Generater a solution for the maz
|
||||
def generateSolutions(self, maxdist=20, startpos=None):
|
||||
def build_path(current_node):
|
||||
path = []
|
||||
current = current_node
|
||||
while current is not None:
|
||||
path.append(current.position)
|
||||
current = current.parent
|
||||
return (pelletCount, path[::-1])
|
||||
|
||||
# Pathfinding initial constants
|
||||
start_node = Node(None, self.positions[-1])
|
||||
end_node = Node(None, startpos or self.bestPellet(start_node.position))
|
||||
open_list = [start_node]
|
||||
closed_list = [Node(position=pos) for pos in self.pellets(char='X')]
|
||||
finished_end_nodes = []
|
||||
pathdist = 0
|
||||
pelletCount = 1
|
||||
output = ""
|
||||
|
||||
while len(open_list) > 0:
|
||||
# self.sleep(0.125)
|
||||
pathdist += 1
|
||||
# Choose the best node to work on
|
||||
current_index, current_node = min(enumerate(open_list), key=lambda item : item[1].f)
|
||||
open_list.pop(current_index)
|
||||
closed_list.append(current_node)
|
||||
|
||||
|
||||
# Check if we've hit the maximum distance
|
||||
if pathdist >= maxdist:
|
||||
return build_path(current_node)
|
||||
|
||||
# If we've hit the "end node", but still distance to travel, setup a new one
|
||||
if current_node == end_node:
|
||||
finished_end_nodes.append(end_node)
|
||||
start_node = end_node
|
||||
open_list = [start_node]
|
||||
closed_list.append(end_node)
|
||||
end_node = position=self.bestPellet(current_node.position, blacklist=Node.positionify(finished_end_nodes))
|
||||
pelletCount += 1
|
||||
# if we've acquired all pellets by chance
|
||||
if end_node is None:
|
||||
return build_path(current_node)
|
||||
else:
|
||||
end_node = Node(parent=None, position=end_node)
|
||||
|
||||
# Basically iterates upon all positions next to the current node dependent on the cardinal directions
|
||||
for offset in self.offsets:
|
||||
child = self.merge(current_node.position, offset)
|
||||
# Ensure in bounds
|
||||
if self.inBounds(child):
|
||||
child = Node(parent=current_node, position=child)
|
||||
|
||||
if child in closed_list:
|
||||
continue
|
||||
|
||||
# Ensure not already a closed position
|
||||
child.g = current_node.g + 1
|
||||
child.h = self.distance(child.position, end_node.position)
|
||||
child.f = child.g + child.h
|
||||
|
||||
# Ensure that child node is
|
||||
if child not in open_list:
|
||||
open_list.append(child)
|
||||
|
||||
# Quick method for getting a position with the offsets provided
|
||||
def getPos(self, xoffset=0, yoffset=0):
|
||||
return [random.randint(1, self.x + xoffset), random.randint(1, self.y + yoffset)]
|
||||
|
||||
# Quick method for marking a postiion
|
||||
def mark(self, pos, marker='X'):
|
||||
if self.matrix[pos[0]][pos[1]] != ' ':
|
||||
print(f'Overwritten {self.matrix[pos[0][pos[1]]]} with \'{marker}\'')
|
||||
self.matrix[pos[0]][pos[1]] = marker
|
||||
|
||||
# Mechansim for determining whether a position is in the boundaries of the matrix
|
||||
def inBounds(self, pos):
|
||||
return all([pos[0] >= 0, pos[1] >= 0, pos[1] < self.y, pos[0] < self.x])
|
||||
|
||||
# Determine whether a position is available for use
|
||||
def available(self, pos, look=' '):
|
||||
return (self.matrix[pos[0]][pos[1]] == look) if self.inBounds(pos) else False
|
||||
|
||||
def toRawString(self):
|
||||
return '\n'.join(''.join(line) for line in self.matrix)
|
||||
|
||||
def __repr__(self):
|
||||
length = max([max(len(item) for item in sub) for sub in self.matrix])
|
||||
return '\n'.join(' - '.join(map(lambda item : item.ljust(length) if item != ' ' else (' ' * length), line)) for line in self.matrix)
|
||||
|
||||
# Driver Code
|
||||
if __name__ == "__main__":
|
||||
# User Adjustable Constants
|
||||
timing = 0.050
|
||||
iterations = 1
|
||||
size = (15, 15)
|
||||
|
||||
# Build Constants
|
||||
roundTime = lambda seconds : str(round((seconds) * 1000, 2)) + 'ms'
|
||||
centerSize = (2 + len(str(iterations)))
|
||||
dividerTotal = (4 * size[0]) - centerSize
|
||||
dividerCustom = ('-' * (dividerTotal // 2)) + ' {} ' + ('-' * (dividerTotal // 2))
|
||||
dividerTotal = '-' * (dividerTotal + 4)
|
||||
path = os.path.join(sys.path[0], 'output', 'output.dat')
|
||||
file = open(path, 'w+')
|
||||
t1 = time.time()
|
||||
|
||||
# Build and prints matrixes
|
||||
for x in range(iterations):
|
||||
snakegrid = SnakeGrid(size[0], size[1], 3)
|
||||
print(dividerCustom.format(str(x+1).zfill(len(str(iterations)))))
|
||||
file.write(snakegrid.toRawString() + '\n')
|
||||
for position in snakegrid.pellets():
|
||||
pelletCount, solution = snakegrid.solution(startpos=position)
|
||||
if len(solution) >= 5 and pelletCount > 0:
|
||||
file.write(solution + '\n')
|
||||
print(f'{solution} - {pelletCount}')
|
||||
print(dividerTotal)
|
||||
print(snakegrid)
|
||||
# snakegrid.sleep(timing)
|
||||
print(dividerTotal)
|
||||
|
||||
# Finish and print timing statistics
|
||||
file.close()
|
||||
t2 = time.time()
|
||||
print(f'Processing Time : {roundTime(t2 - t1 - snakegrid.sleepTime)}')
|
||||
print(f'Artificial Time : {roundTime(snakegrid.sleepTime)}')
|
||||
print(f'Total Time : {roundTime(t2 - t1)}')
|
||||
print(dividerTotal)
|
||||
20
uil/aplus-october-2013/3/input-generator/output/output.dat
Normal file
20
uil/aplus-october-2013/3/input-generator/output/output.dat
Normal file
@@ -0,0 +1,20 @@
|
||||
|
||||
F
|
||||
F
|
||||
|
||||
F
|
||||
|
||||
|
||||
|
||||
|
||||
XXX
|
||||
|
||||
|
||||
|
||||
F
|
||||
F
|
||||
|
||||
UUUUULL
|
||||
UULULUL
|
||||
UUUUUURUULL
|
||||
DRDRDD
|
||||
6
uil/aplus-october-2013/3/java/.idea/misc.xml
generated
Normal file
6
uil/aplus-october-2013/3/java/.idea/misc.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8 (1)" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
8
uil/aplus-october-2013/3/java/.idea/modules.xml
generated
Normal file
8
uil/aplus-october-2013/3/java/.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/3.iml" filepath="$PROJECT_DIR$/3.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
uil/aplus-october-2013/3/java/.idea/vcs.xml
generated
Normal file
6
uil/aplus-october-2013/3/java/.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../../../.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
291
uil/aplus-october-2013/3/java/.idea/workspace.xml
generated
Normal file
291
uil/aplus-october-2013/3/java/.idea/workspace.xml
generated
Normal file
@@ -0,0 +1,291 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="250f6713-4389-436f-88a0-d6dffc72af7e" name="Default Changelist" comment="">
|
||||
<change beforePath="$PROJECT_DIR$/input.dat" beforeDir="false" afterPath="$PROJECT_DIR$/input.dat" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/src/problem3.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/problem3.java" afterDir="false" />
|
||||
</list>
|
||||
<ignored path="$PROJECT_DIR$/out/" />
|
||||
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||
</component>
|
||||
<component name="FUSProjectUsageTrigger">
|
||||
<session id="-261025025">
|
||||
<usages-collector id="statistics.lifecycle.project">
|
||||
<counts>
|
||||
<entry key="project.open.time.2" value="1" />
|
||||
<entry key="project.opened" value="1" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
<usages-collector id="statistics.file.extensions.open">
|
||||
<counts>
|
||||
<entry key="java" value="1" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
<usages-collector id="statistics.file.types.open">
|
||||
<counts>
|
||||
<entry key="JAVA" value="1" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
<usages-collector id="statistics.file.extensions.edit">
|
||||
<counts>
|
||||
<entry key="java" value="44" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
<usages-collector id="statistics.file.types.edit">
|
||||
<counts>
|
||||
<entry key="JAVA" value="44" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
</session>
|
||||
<session id="-1963689904">
|
||||
<usages-collector id="statistics.lifecycle.project">
|
||||
<counts>
|
||||
<entry key="project.closed" value="1" />
|
||||
<entry key="project.open.time.0" value="1" />
|
||||
<entry key="project.opened" value="1" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
<usages-collector id="statistics.file.extensions.edit">
|
||||
<counts>
|
||||
<entry key="dat" value="105" />
|
||||
<entry key="java" value="5234" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
<usages-collector id="statistics.file.types.edit">
|
||||
<counts>
|
||||
<entry key="JAVA" value="5234" />
|
||||
<entry key="PLAIN_TEXT" value="105" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
<usages-collector id="statistics.file.extensions.open">
|
||||
<counts>
|
||||
<entry key="dat" value="8" />
|
||||
<entry key="java" value="2" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
<usages-collector id="statistics.file.types.open">
|
||||
<counts>
|
||||
<entry key="JAVA" value="2" />
|
||||
<entry key="PLAIN_TEXT" value="8" />
|
||||
</counts>
|
||||
</usages-collector>
|
||||
</session>
|
||||
</component>
|
||||
<component name="FileEditorManager">
|
||||
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300" />
|
||||
</component>
|
||||
<component name="FileTemplateManagerImpl">
|
||||
<option name="RECENT_TEMPLATES">
|
||||
<list>
|
||||
<option value="Class" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="FindInProjectRecents">
|
||||
<findStrings>
|
||||
<find>out.println</find>
|
||||
<find>out.prin</find>
|
||||
<find>listContains</find>
|
||||
<find>listContai</find>
|
||||
</findStrings>
|
||||
</component>
|
||||
<component name="Git.Settings">
|
||||
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/../../../.." />
|
||||
</component>
|
||||
<component name="GradleLocalSettings">
|
||||
<option name="projectSyncType">
|
||||
<map>
|
||||
<entry key="A:/Programming/Modding/Minecraft/EnderStorage" value="PREVIEW" />
|
||||
<entry key="A:/Programming/Modding/Minecraft/Fabric/fabric-example-mod" value="PREVIEW" />
|
||||
<entry key="A:/Programming/Modding/Minecraft/HelloWorldMod" value="PREVIEW" />
|
||||
</map>
|
||||
</option>
|
||||
</component>
|
||||
<component name="IdeDocumentHistory">
|
||||
<option name="CHANGED_PATHS">
|
||||
<list>
|
||||
<option value="$PROJECT_DIR$/src/problem3.java" />
|
||||
<option value="$PROJECT_DIR$/input.dat" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectFrameBounds" extendedState="6">
|
||||
<option name="x" value="351" />
|
||||
<option name="y" value="-16" />
|
||||
<option name="width" value="974" />
|
||||
<option name="height" value="1057" />
|
||||
</component>
|
||||
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
|
||||
<component name="ProjectView">
|
||||
<navigator proportions="" version="1">
|
||||
<foldersAlwaysOnTop value="true" />
|
||||
</navigator>
|
||||
<panes>
|
||||
<pane id="ProjectPane">
|
||||
<subPane>
|
||||
<expand>
|
||||
<path>
|
||||
<item name="java" type="b2602c69:ProjectViewProjectNode" />
|
||||
<item name="java" type="462c0819:PsiDirectoryNode" />
|
||||
</path>
|
||||
</expand>
|
||||
<select />
|
||||
</subPane>
|
||||
</pane>
|
||||
<pane id="Scope" />
|
||||
<pane id="PackagesPane" />
|
||||
</panes>
|
||||
</component>
|
||||
<component name="PropertiesComponent">
|
||||
<property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1568926048325" />
|
||||
<property name="last_opened_file_path" value="$PROJECT_DIR$/../../12" />
|
||||
<property name="settings.editor.selected.configurable" value="preferences.pluginManager" />
|
||||
</component>
|
||||
<component name="RunDashboard">
|
||||
<option name="ruleStates">
|
||||
<list>
|
||||
<RuleState>
|
||||
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
|
||||
</RuleState>
|
||||
<RuleState>
|
||||
<option name="name" value="StatusDashboardGroupingRule" />
|
||||
</RuleState>
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="RunManager">
|
||||
<configuration name="problem3" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
|
||||
<option name="MAIN_CLASS_NAME" value="problem3" />
|
||||
<module name="3" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<recent_temporary>
|
||||
<list>
|
||||
<item itemvalue="Application.problem3" />
|
||||
</list>
|
||||
</recent_temporary>
|
||||
</component>
|
||||
<component name="SvnConfiguration">
|
||||
<configuration />
|
||||
</component>
|
||||
<component name="TaskManager">
|
||||
<task active="true" id="Default" summary="Default task">
|
||||
<changelist id="250f6713-4389-436f-88a0-d6dffc72af7e" name="Default Changelist" comment="" />
|
||||
<created>1568523737759</created>
|
||||
<option name="number" value="Default" />
|
||||
<option name="presentableId" value="Default" />
|
||||
<updated>1568523737759</updated>
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
<component name="TodoView">
|
||||
<todo-panel id="selected-file">
|
||||
<is-autoscroll-to-source value="true" />
|
||||
</todo-panel>
|
||||
<todo-panel id="all">
|
||||
<are-packages-shown value="true" />
|
||||
<is-autoscroll-to-source value="true" />
|
||||
</todo-panel>
|
||||
</component>
|
||||
<component name="ToolWindowManager">
|
||||
<frame x="-8" y="-8" width="1936" height="1066" extended-state="6" />
|
||||
<layout>
|
||||
<window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.25266525" />
|
||||
<window_info id="Structure" order="1" side_tool="true" weight="0.25" />
|
||||
<window_info id="Image Layers" order="2" />
|
||||
<window_info id="Designer" order="3" />
|
||||
<window_info id="UI Designer" order="4" />
|
||||
<window_info id="Capture Tool" order="5" />
|
||||
<window_info id="Favorites" order="6" side_tool="true" />
|
||||
<window_info anchor="bottom" id="Messages" weight="0.32939914" />
|
||||
<window_info anchor="bottom" id="Message" order="0" />
|
||||
<window_info anchor="bottom" id="Find" order="1" />
|
||||
<window_info anchor="bottom" id="Run" order="2" weight="0.29077253" />
|
||||
<window_info anchor="bottom" id="Debug" order="3" weight="0.39914164" />
|
||||
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
|
||||
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
|
||||
<window_info anchor="bottom" id="TODO" order="6" weight="0.32939914" />
|
||||
<window_info anchor="bottom" id="Terminal" order="7" weight="0.32939914" />
|
||||
<window_info anchor="bottom" id="Event Log" order="8" side_tool="true" />
|
||||
<window_info anchor="bottom" id="Version Control" order="9" show_stripe_button="false" />
|
||||
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
|
||||
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
|
||||
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
|
||||
<window_info anchor="right" id="Palette" order="3" />
|
||||
<window_info anchor="right" id="Capture Analysis" order="4" />
|
||||
<window_info anchor="right" id="Theme Preview" order="5" />
|
||||
<window_info anchor="right" id="Palette	" order="6" />
|
||||
<window_info anchor="right" id="Maven Projects" order="7" />
|
||||
</layout>
|
||||
</component>
|
||||
<component name="VcsContentAnnotationSettings">
|
||||
<option name="myLimit" value="2678400000" />
|
||||
</component>
|
||||
<component name="editorHistoryManager">
|
||||
<entry file="jar://C:/Program Files/AdoptOpenJDK/jdk-8.0.212.04-hotspot/src.zip!/java/lang/Object.java">
|
||||
<provider selected="true" editor-type-id="text-editor">
|
||||
<state relative-caret-position="436">
|
||||
<caret line="234" column="18" selection-start-line="234" selection-start-column="18" selection-end-line="234" selection-end-column="18" />
|
||||
<folding>
|
||||
<element signature="e#11062#11063#0" expanded="true" />
|
||||
<element signature="e#11145#11146#0" expanded="true" />
|
||||
</folding>
|
||||
</state>
|
||||
</provider>
|
||||
</entry>
|
||||
<entry file="jar://C:/Program Files/AdoptOpenJDK/jdk-8.0.212.04-hotspot/src.zip!/java/lang/String.java">
|
||||
<provider selected="true" editor-type-id="text-editor">
|
||||
<state relative-caret-position="232">
|
||||
<caret line="657" selection-start-line="657" selection-end-line="657" />
|
||||
</state>
|
||||
</provider>
|
||||
</entry>
|
||||
<entry file="file://$PROJECT_DIR$/input.dat">
|
||||
<provider selected="true" editor-type-id="text-editor">
|
||||
<state relative-caret-position="238">
|
||||
<caret line="14" column="17" lean-forward="true" selection-start-line="14" selection-start-column="17" selection-end-line="14" selection-end-column="17" />
|
||||
</state>
|
||||
</provider>
|
||||
</entry>
|
||||
<entry file="file://$PROJECT_DIR$/src/problem3.java">
|
||||
<provider selected="true" editor-type-id="text-editor">
|
||||
<state relative-caret-position="289">
|
||||
<caret line="88" column="21" lean-forward="true" selection-start-line="88" selection-start-column="21" selection-end-line="88" selection-end-column="21" />
|
||||
<folding>
|
||||
<element signature="imports" expanded="true" />
|
||||
<element signature="e#242#243#0" expanded="true" />
|
||||
<element signature="e#261#262#0" expanded="true" />
|
||||
<element signature="e#456#457#0" expanded="true" />
|
||||
<element signature="e#517#518#0" expanded="true" />
|
||||
<element signature="e#597#598#0" expanded="true" />
|
||||
<element signature="e#658#659#0" expanded="true" />
|
||||
<element signature="e#641#648#0" expanded="true" />
|
||||
<element signature="e#692#699#0" expanded="true" />
|
||||
</folding>
|
||||
</state>
|
||||
</provider>
|
||||
</entry>
|
||||
</component>
|
||||
<component name="masterDetails">
|
||||
<states>
|
||||
<state key="ProjectJDKs.UI">
|
||||
<settings>
|
||||
<last-edited>11</last-edited>
|
||||
<splitter-proportions>
|
||||
<option name="proportions">
|
||||
<list>
|
||||
<option value="0.2" />
|
||||
</list>
|
||||
</option>
|
||||
</splitter-proportions>
|
||||
</settings>
|
||||
</state>
|
||||
</states>
|
||||
</component>
|
||||
</project>
|
||||
10
uil/aplus-october-2013/3/java/.vscode/launch.json
vendored
Normal file
10
uil/aplus-october-2013/3/java/.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"type": "java",
|
||||
"name": "CodeLens (Launch) - problem3",
|
||||
"request": "launch",
|
||||
"mainClass": "problem3"
|
||||
}
|
||||
]
|
||||
}
|
||||
11
uil/aplus-october-2013/3/java/3.iml
Normal file
11
uil/aplus-october-2013/3/java/3.iml
Normal file
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
20
uil/aplus-october-2013/3/java/input.dat
Normal file
20
uil/aplus-october-2013/3/java/input.dat
Normal file
@@ -0,0 +1,20 @@
|
||||
|
||||
F
|
||||
F
|
||||
|
||||
F
|
||||
|
||||
|
||||
|
||||
|
||||
XXX
|
||||
|
||||
|
||||
|
||||
F
|
||||
F |
|
||||
4
|
||||
UOOOULOOLUOORD
|
||||
UULULULUL
|
||||
UOOOUORUOLOOOODOLDR
|
||||
ODDRDDROD
|
||||
BIN
uil/aplus-october-2013/3/java/out/production/3/Maze.class
Normal file
BIN
uil/aplus-october-2013/3/java/out/production/3/Maze.class
Normal file
Binary file not shown.
BIN
uil/aplus-october-2013/3/java/out/production/3/Point.class
Normal file
BIN
uil/aplus-october-2013/3/java/out/production/3/Point.class
Normal file
Binary file not shown.
BIN
uil/aplus-october-2013/3/java/out/production/3/problem3.class
Normal file
BIN
uil/aplus-october-2013/3/java/out/production/3/problem3.class
Normal file
Binary file not shown.
164
uil/aplus-october-2013/3/java/src/problem3.java
Normal file
164
uil/aplus-october-2013/3/java/src/problem3.java
Normal file
@@ -0,0 +1,164 @@
|
||||
import static java.lang.System.*;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.*;
|
||||
|
||||
// Point representing and (X, Y) coordinate
|
||||
class Point {
|
||||
int x, y;
|
||||
|
||||
Point(int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
// Returns a point which is the translated end-point based on the other point (offset).
|
||||
Point merge(Point other) {
|
||||
return new Point(this.x + other.x, this.y + other.y);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return String.format("Point(%d, %d)", this.x, this.y);
|
||||
}
|
||||
|
||||
public boolean equals(Point other) {
|
||||
return this.x == other.x && this.y == other.y;
|
||||
}
|
||||
|
||||
public static boolean collectionContains(Collection<Point> collection, Point point) {
|
||||
for(Point other : collection) {
|
||||
if(point.x == other.x && point.y == other.y) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Class method that searches a List
|
||||
public static int listContains(List<Point> c, Point p) {
|
||||
for(Point o : c) {
|
||||
if(p.x == o.x && p.y == o.y)
|
||||
return c.indexOf(o);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
class Maze {
|
||||
// Offset Constants
|
||||
public List<Point> positionOffsets = Arrays.asList(new Point(1, 0), new Point(0, 1), new Point(-1, 0), new Point(0, -1));
|
||||
private List<String> nameOffsets = Arrays.asList("D R U L".split(" "));
|
||||
// Maze Data
|
||||
List<Point> snake = new ArrayList<Point>();;
|
||||
private List<Point> pellets = new ArrayList<Point>();
|
||||
private char[][] rawMatrix;
|
||||
|
||||
Maze(char[][] rawMatrix) {
|
||||
this.rawMatrix = rawMatrix;
|
||||
|
||||
for(int x = 0; x < 15; x++) {
|
||||
for(int y = 0; y < 15; y++) {
|
||||
switch(rawMatrix[x][y]) {
|
||||
// Empty Space
|
||||
case ' ':
|
||||
break;
|
||||
// Point Found
|
||||
case 'X':
|
||||
this.snake.add(new Point(x, y));
|
||||
break;
|
||||
// Pellet Found
|
||||
case 'F':
|
||||
this.pellets.add(new Point(x, y));
|
||||
break;
|
||||
// Should not be found based on input data. Something has gone wrong/input data is invalid.
|
||||
default:
|
||||
out.println("Possibly faulty Maze Input with item \"" + rawMatrix[x][y] + "\" found.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Simulate the snake game using instructions
|
||||
String simulate(String input) {
|
||||
String curDirection = "R";
|
||||
int score = 0;
|
||||
for(int i = 0; i < input.length(); i++) {
|
||||
// Calculate the offset based on the current instruction
|
||||
Point offset;
|
||||
String curOffset = input.substring(i, i + 1);
|
||||
if(!curDirection.equals(curOffset) && !curOffset.equals("O"))
|
||||
curDirection = curOffset;
|
||||
if(curOffset.equals("O"))
|
||||
offset = positionOffsets.get(nameOffsets.indexOf(curDirection));
|
||||
else
|
||||
offset = positionOffsets.get(nameOffsets.indexOf(curOffset));
|
||||
// Calculate the new point, ensure it's real
|
||||
Point newPoint = snake.get(snake.size() - 1);
|
||||
newPoint = newPoint.merge(offset);
|
||||
// New Point was out of bounds, cannot continue
|
||||
if(!this.inBounds(newPoint))
|
||||
return "GAME OVER";
|
||||
// Add new point, discard end of snake to simulate it's movement
|
||||
snake.remove(0);
|
||||
snake.add(newPoint);
|
||||
// Check if we're at a pellet, add score.
|
||||
int pelletIndex = Point.listContains(pellets, newPoint);
|
||||
if(pelletIndex != -1) {
|
||||
score += 1;
|
||||
this.pellets.remove(pelletIndex);
|
||||
}
|
||||
}
|
||||
return Integer.toString(score);
|
||||
}
|
||||
|
||||
// Methods for testing whether a position is in the maze's boundaries
|
||||
public boolean inBounds(Point point) {return this.inBounds(point.x, point.y);}
|
||||
private boolean inBounds(int x, int y) {return x >= 0 && y >= 0 && x < 15 && y < 15;}
|
||||
|
||||
// Prints a string representation of the Maze
|
||||
public String toString() {
|
||||
String[] lines = new String[15];
|
||||
for(int x = 0; x < 15; x++) {
|
||||
String[] temp = new String[15];
|
||||
for(int y = 0; y < 15; y++) {
|
||||
Point point = new Point(x, y);
|
||||
// Priority: Empty Space < Pellet < Snake
|
||||
temp[y] = Point.collectionContains(this.snake, point) ? "X" : (Point.collectionContains(this.pellets, point) ? "F" : " ");
|
||||
}
|
||||
lines[x] = String.join(" - ", temp);
|
||||
}
|
||||
return String.join("\n", lines);
|
||||
}
|
||||
}
|
||||
|
||||
public class problem3 {
|
||||
public static void main(String[] args ) throws FileNotFoundException {
|
||||
// Constants
|
||||
File fileInput = new File("input.dat");
|
||||
Scanner read = new Scanner(fileInput);
|
||||
|
||||
// Read the maze into a String matrix
|
||||
char[][] rawMatrix = new char[15][15];
|
||||
for(int x = 0; x < 15; x++) {
|
||||
String line = read.nextLine();
|
||||
for(int y = 0; y < 15; y++) {
|
||||
rawMatrix[x][y] = line.charAt(y);
|
||||
}
|
||||
}
|
||||
|
||||
// Read each of the inputs
|
||||
int lines = Integer.parseInt(read.nextLine());
|
||||
String[] inputs = new String[lines];
|
||||
for(int i = 0; i < lines; i++)
|
||||
inputs[i] = read.nextLine();
|
||||
|
||||
// Simulate inputs
|
||||
for(String input : inputs) {
|
||||
Maze maze = new Maze(rawMatrix);
|
||||
String pellets = maze.simulate(input);
|
||||
// Uncomment to display the final position of the maze
|
||||
// out.println(maze);
|
||||
out.println(pellets); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user