first commit
3
README.md
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# University lab projects
|
||||
|
||||
This repo contains a few projects that I completed back when I was learning to code in university around 2018.
|
||||
165
clab/client-server-system/.gitignore
vendored
Executable file
|
|
@ -0,0 +1,165 @@
|
|||
|
||||
# Created by https://www.gitignore.io/api/c,python
|
||||
# Edit at https://www.gitignore.io/?templates=c,python
|
||||
|
||||
### C ###
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Object files
|
||||
*.o
|
||||
*.ko
|
||||
*.obj
|
||||
*.elf
|
||||
|
||||
# Linker output
|
||||
*.ilk
|
||||
*.map
|
||||
*.exp
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Libraries
|
||||
*.lib
|
||||
*.a
|
||||
*.la
|
||||
*.lo
|
||||
|
||||
# Shared objects (inc. Windows DLLs)
|
||||
*.dll
|
||||
*.so
|
||||
*.so.*
|
||||
*.dylib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
*.i*86
|
||||
*.x86_64
|
||||
*.hex
|
||||
|
||||
# Debug files
|
||||
*.dSYM/
|
||||
*.su
|
||||
*.idb
|
||||
*.pdb
|
||||
|
||||
# Kernel Module Compile Results
|
||||
*.mod*
|
||||
*.cmd
|
||||
.tmp_versions/
|
||||
modules.order
|
||||
Module.symvers
|
||||
Mkfile.old
|
||||
dkms.conf
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# celery beat schedule file
|
||||
celerybeat-schedule
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# Mr Developer
|
||||
.mr.developer.cfg
|
||||
.project
|
||||
.pydevproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# End of https://www.gitignore.io/api/c,python
|
||||
|
||||
.data
|
||||
2
clab/client-server-system/README.md
Executable file
|
|
@ -0,0 +1,2 @@
|
|||
|
||||
# Client-Server-System
|
||||
5
clab/client-server-system/client/client.cfg
Executable file
|
|
@ -0,0 +1,5 @@
|
|||
Id = KZ87MKAGB43N
|
||||
Params = LUM-0-O;LUM-0-I;PRE-0-O;TEM-0-O
|
||||
Local-TCP = 5057
|
||||
Server = localhost
|
||||
Server-UDP = 9002
|
||||
391
clab/client-server-system/client/client.py
Executable file
|
|
@ -0,0 +1,391 @@
|
|||
#!/usr/bin/env python3
|
||||
from utils import *
|
||||
|
||||
signal.signal(signal.SIGINT, handler)
|
||||
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# --------------------- FASE DE REGISTRE -----------------------
|
||||
# --------------------------------------------------------------
|
||||
|
||||
def register(sock, server_address):
|
||||
global client
|
||||
client.register_attemps += 1
|
||||
logger.debug_print(f"Registrant el client al servidor. (Intent {client.register_attemps})")
|
||||
if client.register_attemps > o:
|
||||
logger.debug_print("S'ha superat el nombre d'intents permesos")
|
||||
print("No s'ha pogut contactar amb el servidor")
|
||||
client.current_state = DISCONNECTED
|
||||
else:
|
||||
send_reg_req(sock, server_address, 0, t)
|
||||
|
||||
|
||||
def send_reg_req(sock, server_address, num_sends, timeout):
|
||||
global client
|
||||
if num_sends >= n:
|
||||
|
||||
time.sleep(u)
|
||||
register(sock, server_address)
|
||||
elif not client.has_state(REGISTERED):
|
||||
if num_sends >= p and timeout < q * t:
|
||||
timeout += t
|
||||
sendto(sock, server_address, REG_REQ,
|
||||
client.id, "00000000\0", "")
|
||||
client.current_state = WAIT_ACK_REG
|
||||
(inputs, _, _) = select.select([sock], [], [], timeout)
|
||||
if len(inputs) > 0:
|
||||
response, addr = recvfrom(sock)
|
||||
if client.has_state(WAIT_ACK_REG) and addr[0] == server_address[0]:
|
||||
pck = response[0]
|
||||
if pck == REG_ACK:
|
||||
client.set_udp_communication_port(int(response[3]))
|
||||
client.set_server_credentials(
|
||||
response[1], response[2], addr[0])
|
||||
send_info(sock, server_address, num_sends, timeout)
|
||||
elif pck == REG_NACK:
|
||||
client.current_state = NOT_REGISTERED
|
||||
send_reg_req(sock, server_address, num_sends + 1, timeout)
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
register(sock, server_address)
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
register(sock, server_address)
|
||||
else:
|
||||
send_reg_req(sock, server_address, num_sends + 1, timeout)
|
||||
|
||||
|
||||
def send_info(sock, server_address, num_reg_sends, reg_timeout):
|
||||
global client
|
||||
info_timeout = t * 2
|
||||
address = (client.server_ip, client.udp_port)
|
||||
data = f"{str(client.local_tcp)},{';'.join(list(client.elems))}"
|
||||
sendto(sock, address, REG_INFO, client.id, client.rand_num, data)
|
||||
client.current_state = WAIT_ACK_INFO
|
||||
(inputs, _, _) = select.select([sock], [], [], info_timeout)
|
||||
if len(inputs) > 0:
|
||||
response, addr = recvfrom(sock)
|
||||
pck = response[0]
|
||||
if client.has_state(WAIT_ACK_INFO) and client.check_server_credentials(server_id=response[1],
|
||||
rand_num=response[2],
|
||||
server_ip=addr[0]):
|
||||
if pck == INFO_ACK:
|
||||
client.set_tcp_communication_port(int(response[3]))
|
||||
client.current_state = REGISTERED
|
||||
elif pck == INFO_NACK:
|
||||
client.current_state = NOT_REGISTERED
|
||||
send_reg_req(sock, server_address,
|
||||
num_reg_sends + 1, reg_timeout)
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
register(sock, server_address)
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
register(sock, server_address)
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
register(sock, server_address)
|
||||
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# --------------------- FASE DE COMUNICACIÓ --------------------
|
||||
# ---------------------------PERIÒDICA--------------------------
|
||||
# --------------------------------------------------------------
|
||||
|
||||
|
||||
def recv_first_alive(sock):
|
||||
global client
|
||||
timeout = r * v
|
||||
(inputs, _, _) = select.select([sock], [], [], timeout)
|
||||
if len(inputs) > 0:
|
||||
response, server_addr = recvfrom(sock)
|
||||
pck, client_id = response[0], response[-1]
|
||||
if client.check_server_credentials(server_id=response[1], rand_num=response[2],
|
||||
server_ip=server_addr[0]) and client_id == client.id:
|
||||
if pck == ALIVE:
|
||||
client.current_state = SEND_ALIVE
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
|
||||
|
||||
def recv_alive(sock):
|
||||
global client
|
||||
alives_not_received = 0
|
||||
max_lost_alive = s
|
||||
timeout = r * v
|
||||
while client.has_state(SEND_ALIVE):
|
||||
(inputs, _, _) = select.select([sock], [], [], timeout)
|
||||
if len(inputs) > 0:
|
||||
response, server_addr = recvfrom(sock)
|
||||
pck, client_id = response[0], response[-1]
|
||||
if client.check_server_credentials(server_id=response[1], rand_num=response[2],
|
||||
server_ip=server_addr[0]) and client_id == client.id:
|
||||
if pck == ALIVE:
|
||||
alives_not_received = 0
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
else:
|
||||
client.current_state = NOT_REGISTERED
|
||||
else:
|
||||
alives_not_received += 1
|
||||
if alives_not_received >= max_lost_alive:
|
||||
logger.debug_print(
|
||||
f"No s'han rebut {max_lost_alive} paquets ALIVE consecutius, estat actual: NOT_REGISTERED")
|
||||
client.current_state = NOT_REGISTERED
|
||||
|
||||
|
||||
def send_alive(sock, server_udp_address):
|
||||
global client
|
||||
timeout = v
|
||||
while client.has_state(REGISTERED, SEND_ALIVE):
|
||||
sendto(sock, server_udp_address, ALIVE, client.id, client.rand_num, "")
|
||||
time.sleep(timeout)
|
||||
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# --------------------- REBUDA DE COMANDES ---------------------
|
||||
# --------------------------------------------------------------
|
||||
def start_cli():
|
||||
global client
|
||||
print("\nBenvingut, introdueix 'help' per veure les comandes acceptades.")
|
||||
while client.has_state(SEND_ALIVE):
|
||||
try:
|
||||
cmd = input().strip().split()
|
||||
if len(cmd) == 0:
|
||||
pass
|
||||
elif cmd[0] == 'help':
|
||||
help()
|
||||
elif cmd[0] == 'stat':
|
||||
run_stat()
|
||||
elif cmd[0] == 'set':
|
||||
run_set(cmd)
|
||||
elif cmd[0] == 'send':
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.connect((client.server_ip, client.tcp_port))
|
||||
run_send(sock, cmd)
|
||||
sock.close()
|
||||
except ConnectionError as err:
|
||||
print(
|
||||
f"Connexió rebutjada, pot ser que el servidor estigui desconnectat.")
|
||||
pass
|
||||
elif cmd[0] == 'quit':
|
||||
client.current_state = DISCONNECTED
|
||||
else:
|
||||
print("\tComanda no acceptada.")
|
||||
except EOFError:
|
||||
os.kill(os.getpid(), signal.SIGINT)
|
||||
|
||||
|
||||
def help():
|
||||
print("\tstat")
|
||||
print("\tset <identificador_element> <nou_valor>")
|
||||
print("\tsend <identificador_element>")
|
||||
print("\tquit")
|
||||
|
||||
|
||||
def run_stat():
|
||||
global client
|
||||
print(" ---ELEMS---|--VALUE---------")
|
||||
for key, value in client.elems.items():
|
||||
print(f"\t{key} : {value}")
|
||||
|
||||
|
||||
def run_set(cmd):
|
||||
if len(cmd) != 3:
|
||||
print("\tset <identificador_element> <nou_valor>")
|
||||
elif cmd[1] not in client.elems:
|
||||
print("\tL'element no existeix")
|
||||
else:
|
||||
elem_id = cmd[1]
|
||||
new_value = cmd[2]
|
||||
client.elems[elem_id] = new_value
|
||||
|
||||
|
||||
def run_send(sock, cmd):
|
||||
if len(cmd) != 2:
|
||||
print("\tsend <identificador_element>")
|
||||
elif cmd[1] not in client.elems:
|
||||
print("\tL'element no existeix")
|
||||
else:
|
||||
timeout = m
|
||||
elem = cmd[1]
|
||||
value = client.elems[elem]
|
||||
info = get_actual_date()
|
||||
send(sock, SEND_DATA, client.id, client.rand_num, elem, value, info)
|
||||
(inputs, _, _) = select.select([sock], [], [], timeout)
|
||||
if len(inputs) > 0:
|
||||
response = recv(sock)
|
||||
if response is not None:
|
||||
pck = response[0]
|
||||
if client.check_server_credentials(server_id=response[1], rand_num=response[2]):
|
||||
if pck == DATA_ACK:
|
||||
client_id = response[-1]
|
||||
if client_id == client.id:
|
||||
logger.debug_print("\tDades acceptades!")
|
||||
else:
|
||||
logger.debug_print("\tDades d'identificació del client rebudes erronees, client passa a l'estat NOT_REGISTERED")
|
||||
client.current_state = NOT_REGISTERED
|
||||
elif pck == DATA_NACK:
|
||||
logger.debug_print(
|
||||
f"\tDades no acceptades, motiu: {response[-1]}")
|
||||
else:
|
||||
logger.debug_print(
|
||||
f"\tDades rebutjades per part del servidor")
|
||||
client.current_state = NOT_REGISTERED
|
||||
else:
|
||||
logger.debug_print("\tDades d'identificació del servidor rebudes erronees, client passa a l'estat NOT_REGISTERED")
|
||||
client.current_state = NOT_REGISTERED
|
||||
else:
|
||||
logger.debug_print("\tDades d'identificació del servidor rebudes erronees, client passa a l'estat NOT_REGISTERED")
|
||||
client.current_state = NOT_REGISTERED
|
||||
else:
|
||||
logger.debug_print("\tNo ha hagut una resposta per part del servidor")
|
||||
|
||||
|
||||
def get_actual_date():
|
||||
date = datetime.datetime.now()
|
||||
info = f'{str(date.year)}-{str(date.month)}-{str(date.day)};{str(date.hour)}:{str(date.minute)}:{str(date.second)}'
|
||||
return info
|
||||
|
||||
|
||||
# --------------------------------------------------------------
|
||||
# --------------------- ESPERA DE CONNEXIONS--------------------
|
||||
# --------------------------------------------------------------
|
||||
|
||||
def wait_server_connections(sock):
|
||||
while client.has_state(SEND_ALIVE):
|
||||
(inputs, _, _) = select.select([sock], [], [], 0.0)
|
||||
if len(inputs) > 0:
|
||||
new_sock, addr = sock.accept()
|
||||
response = recv(new_sock)
|
||||
if response is not None:
|
||||
pck, client_id, elem = response[0], response[-1], response[3]
|
||||
if client.check_server_credentials(server_id=response[1], rand_num=response[2]) and client_id == client.id:
|
||||
if elem not in client.elems:
|
||||
send(new_sock, DATA_NACK, client.id,
|
||||
client.rand_num, elem, "", "Element no trobat")
|
||||
if pck == SET_DATA:
|
||||
value = response[4]
|
||||
set_data(new_sock, elem, value)
|
||||
elif pck == GET_DATA:
|
||||
get_data(new_sock, elem)
|
||||
else:
|
||||
send(new_sock, DATA_REJ, client.id, client.rand_num, elem, "",
|
||||
"Hi ha discrepancies en les dades del servidor i/o del dispositiu")
|
||||
client.current_state = NOT_REGISTERED
|
||||
else:
|
||||
send(new_sock, DATA_REJ, client.id, client.rand_num, elem, "",
|
||||
"Les dades rebudes estan mal formades")
|
||||
client.current_state = NOT_REGISTERED
|
||||
new_sock.close()
|
||||
sock.close()
|
||||
|
||||
|
||||
def set_data(sock, elem, value):
|
||||
global client
|
||||
if elem[-1] != 'I':
|
||||
send(sock, DATA_NACK, client.id, client.rand_num,
|
||||
elem, "", "Tipus de l'element incorrecte")
|
||||
else:
|
||||
client.elems[elem] = value
|
||||
logger.debug_print(
|
||||
f"Valor {value} assignat a l'element {elem} per el servidor")
|
||||
send(sock, DATA_ACK, client.id,
|
||||
client.rand_num, elem, value, client.id)
|
||||
|
||||
|
||||
def get_data(sock, elem):
|
||||
logger.debug_print(
|
||||
f"Dades de l'element {elem} demanades per el servidor.")
|
||||
value = client.elems[elem]
|
||||
send(sock, DATA_ACK, client.id,
|
||||
client.rand_num, elem, value, client.id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# ------------------------THREADS CREATION-----------------------
|
||||
# ---------------------------------------------------------------
|
||||
|
||||
def run_send_alive(udp_sock, server_address):
|
||||
s_alive = threading.Thread(target=send_alive, args=[
|
||||
udp_sock, server_address], daemon=True)
|
||||
s_alive.start()
|
||||
|
||||
|
||||
def run_recv_alive(udp_sock):
|
||||
r_alive = threading.Thread(target=recv_alive, args=[udp_sock], daemon=True)
|
||||
r_alive.start()
|
||||
|
||||
|
||||
def run_cli():
|
||||
cli = threading.Thread(target=start_cli, daemon=True)
|
||||
cli.start()
|
||||
|
||||
|
||||
def run_connections(sock):
|
||||
wait_connections = threading.Thread(
|
||||
target=wait_server_connections, args=[sock], daemon=True)
|
||||
wait_connections.start()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# ------------------------MAIN BLOCK-----------------------------
|
||||
# ---------------------------------------------------------------
|
||||
# Creem una instancia de la classe logger
|
||||
# que ens permetrà printar missatges de debug
|
||||
logger = Logger()
|
||||
cfgname = "client.cfg"
|
||||
# Analitzem els arguments
|
||||
# introduits per el script
|
||||
if len(sys.argv) > 1:
|
||||
option = sys.argv[1]
|
||||
if option == '-c':
|
||||
if len(sys.argv) != 3:
|
||||
print(f"{sys.argv[0]} {sys.argv[1]} <filename>")
|
||||
cfgname = sys.argv[2]
|
||||
elif option == '-d':
|
||||
logger.turn_debug_on()
|
||||
# Creem una instancia de la classe Client
|
||||
# que ens ajudarà a gestionar variables com el estat
|
||||
# del client i la seva configuració
|
||||
client = Client(cfgname)
|
||||
try:
|
||||
server_udp_address = (client.server, client.server_udp)
|
||||
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
udp_sock.bind(client.local_address())
|
||||
while not client.has_state(DISCONNECTED):
|
||||
if client.has_state(NOT_REGISTERED):
|
||||
# Iniciem la fase de registre
|
||||
register(udp_sock, server_udp_address)
|
||||
if client.has_state(REGISTERED):
|
||||
logger.debug_print("Enviant paquets ALIVE al servidor")
|
||||
# Comencem a enviar paquets ALIVE al servidor
|
||||
run_send_alive(udp_sock, server_udp_address)
|
||||
# Esperem el primer paquet alive
|
||||
recv_first_alive(udp_sock)
|
||||
if client.has_state(SEND_ALIVE):
|
||||
logger.debug_print("Primer paquet ALIVE rebut")
|
||||
logger.debug_print(
|
||||
"Registre finalitzat, estat actual: SEND_ALIVE")
|
||||
# Iniciem la rebuda de ALIVEs del servidor
|
||||
run_recv_alive(udp_sock)
|
||||
# Obrim el port tcp local per a les connexions amb el servidor
|
||||
tcp_sock = socket.socket(
|
||||
socket.AF_INET, socket.SOCK_STREAM)
|
||||
tcp_sock.bind(('', client.local_tcp))
|
||||
tcp_sock.listen()
|
||||
# Obrim la consola de comandes
|
||||
run_cli()
|
||||
# Iniciem la espera de connexions amb el servidor
|
||||
run_connections(tcp_sock)
|
||||
except OSError as err:
|
||||
print(f"OSError: {err}")
|
||||
finally:
|
||||
# Realitzem un exit el qual tanca tots els
|
||||
# descriptors de fitxer relacionats amb el procés
|
||||
sys.exit(0)
|
||||
187
clab/client-server-system/client/utils.py
Executable file
|
|
@ -0,0 +1,187 @@
|
|||
import socket
|
||||
import sys
|
||||
import struct
|
||||
import select
|
||||
import time
|
||||
import datetime
|
||||
import threading
|
||||
import signal
|
||||
import os
|
||||
|
||||
|
||||
# Paquets de la fase de registre
|
||||
REG_REQ = 0x00
|
||||
REG_INFO = 0x01
|
||||
REG_ACK = 0x02
|
||||
INFO_ACK = 0x03
|
||||
REG_NACK = 0x04
|
||||
INFO_NACK = 0x05
|
||||
REG_REJ = 0x06
|
||||
|
||||
# Paquets per a la comunicació periòdica
|
||||
ALIVE = 0x10
|
||||
ALIVE_REJ = 0x11
|
||||
|
||||
# Paquets per a la transferència de dades amb el servidor
|
||||
SEND_DATA = 0x20
|
||||
SET_DATA = 0x21
|
||||
GET_DATA = 0x22
|
||||
DATA_ACK = 0x23
|
||||
DATA_NACK = 0x24
|
||||
DATA_REJ = 0x25
|
||||
|
||||
# Els possibles estats que pot tenir un client
|
||||
DISCONNECTED = 0xa0
|
||||
NOT_REGISTERED = 0xa1
|
||||
WAIT_ACK_REG = 0xa2
|
||||
WAIT_INFO = 0xa3
|
||||
WAIT_ACK_INFO = 0xa4
|
||||
REGISTERED = 0xa5
|
||||
SEND_ALIVE = 0xa6
|
||||
|
||||
|
||||
# Valors per a les proves de protocol de registre
|
||||
t = 1.0
|
||||
u = 2.0
|
||||
n = 7.0
|
||||
o = 3.0
|
||||
p = 3.0
|
||||
q = 3.0
|
||||
v = 2.0
|
||||
r = 2.0
|
||||
s = 3.0
|
||||
m = 3.0
|
||||
|
||||
# -----------------------------------
|
||||
# ----------DEBUG UTILITIES----------
|
||||
# -----------------------------------
|
||||
|
||||
|
||||
class Logger:
|
||||
def __init__(self):
|
||||
self.debug_mode = False
|
||||
|
||||
def turn_debug_on(self):
|
||||
self.debug_mode = True
|
||||
|
||||
def debug_print(self, message):
|
||||
now = datetime.datetime.now()
|
||||
if self.debug_mode:
|
||||
print("{0}:{1}:{2} => {3}".format(
|
||||
now.hour, now.minute, now.second, message))
|
||||
|
||||
def handler(signum, frame):
|
||||
print('Procés acabat per ctrl+c')
|
||||
sys.exit(0)
|
||||
|
||||
# --------------------------------------------
|
||||
# -------------SOCKETS UTILITIES--------------
|
||||
# --------------------------------------------
|
||||
|
||||
|
||||
def unpack_response(fmt, response):
|
||||
try:
|
||||
t = struct.unpack(fmt, response)
|
||||
return tuple(x if isinstance(x, int) else x.split(b'\x00')[0].decode() for x in t)
|
||||
except:
|
||||
# Considerem un error en el desenpaquetament si
|
||||
# el servidor ens ha enviat un paquet mal format i
|
||||
# retornem null
|
||||
return None
|
||||
|
||||
|
||||
def recvfrom(sock):
|
||||
response, server_addr = sock.recvfrom(84)
|
||||
return unpack_response('!B13s9s61s', response), server_addr
|
||||
|
||||
|
||||
def sendto(sock, address, pack_type, client_id, rand_num, info):
|
||||
data = struct.pack('!B13s9s61s', pack_type, client_id.encode(),
|
||||
rand_num.encode(), info.encode())
|
||||
sock.sendto(data, address)
|
||||
|
||||
|
||||
def recv(sock):
|
||||
response = sock.recv(127)
|
||||
return unpack_response('!B13s9s8s16s80s', response)
|
||||
|
||||
|
||||
def send(sock, pack_type, client_id, rand_num, elem_name, elem_value, info):
|
||||
data = struct.pack('!B13s9s8s16s80s', pack_type, client_id.encode(), rand_num.encode(
|
||||
), elem_name.encode(), elem_value.encode(), info.encode())
|
||||
sock.send(data)
|
||||
|
||||
# -------------------------------------
|
||||
# ------------CLIENT CLASS-------------
|
||||
# -------------------------------------
|
||||
|
||||
|
||||
class Client():
|
||||
"""Representa l'estat d'un client amb la seva configuració
|
||||
"""
|
||||
|
||||
def __init__(self, configfile):
|
||||
config = read_cfg(configfile)
|
||||
self.id = config['Id']
|
||||
self.elems = config['Params']
|
||||
self.local_tcp = config['Local-TCP']
|
||||
self.server = config['Server']
|
||||
self.server_udp = config['Server-UDP']
|
||||
self.current_state = NOT_REGISTERED
|
||||
self.register_attemps = 0
|
||||
|
||||
def has_state(self, *states):
|
||||
for state in states:
|
||||
if self.current_state == state:
|
||||
return True
|
||||
return False
|
||||
|
||||
def set_udp_communication_port(self, udp_port):
|
||||
self.udp_port = udp_port
|
||||
|
||||
def set_tcp_communication_port(self, tcp_port):
|
||||
self.tcp_port = tcp_port
|
||||
|
||||
def set_server_credentials(self, server_id, rand_num, server_ip):
|
||||
self.server_id = server_id
|
||||
self.rand_num = rand_num
|
||||
self.server_ip = server_ip
|
||||
|
||||
def check_server_credentials(self, server_id=None, rand_num=None, server_ip=None):
|
||||
if server_id is not None:
|
||||
if server_id != self.server_id:
|
||||
return False
|
||||
if rand_num is not None:
|
||||
if rand_num != self.rand_num:
|
||||
return False
|
||||
if server_ip is not None:
|
||||
if server_ip != self.server_ip:
|
||||
return False
|
||||
return True
|
||||
|
||||
def local_address(self, port=0):
|
||||
return ('', port)
|
||||
|
||||
|
||||
def read_cfg(filename):
|
||||
"""Llegeix el fitxer de configuració del client
|
||||
i retorna un diccionari <String, dynamic> amb les dades llegides
|
||||
"""
|
||||
try:
|
||||
cfg = open(filename)
|
||||
config = dict()
|
||||
for line in cfg:
|
||||
items = line.strip().replace('=', ' ').split()
|
||||
if len(items) == 2:
|
||||
key, value = items
|
||||
config[key] = value
|
||||
t = config['Params'].strip().split(';')
|
||||
config['Params'] = dict((key, "") for key in t)
|
||||
config['Local-TCP'] = int(config['Local-TCP'])
|
||||
config['Server-UDP'] = int(config['Server-UDP'])
|
||||
config['Server'] = socket.gethostbyname(config['Server'])
|
||||
return config
|
||||
except FileNotFoundError:
|
||||
print(
|
||||
f"No s'ha trobat el fitxer {filename}")
|
||||
sys.exit()
|
||||
3
clab/client-server-system/server/bbdd_dev.dat
Executable file
|
|
@ -0,0 +1,3 @@
|
|||
KZ87MKAGB43N
|
||||
GHX0E32LWQ6C
|
||||
|
||||
9
clab/client-server-system/server/makefile
Executable file
|
|
@ -0,0 +1,9 @@
|
|||
#
|
||||
#
|
||||
LDFLAGS= -ansi -pedantic -Wall -lrt -pthread -std=c99
|
||||
|
||||
all: server.c
|
||||
gcc server.c -o server $(LDFLAGS)
|
||||
|
||||
clean:
|
||||
-rm -rf server
|
||||
564
clab/client-server-system/server/server.c
Executable file
|
|
@ -0,0 +1,564 @@
|
|||
#include "utils.h"
|
||||
|
||||
void handler(int sig);
|
||||
/* ATTEND CLIENT FUNCTIONS */
|
||||
void attendClients(int socket);
|
||||
void *handlePdu(void *args);
|
||||
/* REGISTRATION FUNCTIONS */
|
||||
void registerClient(int sock, udp_pdu pdu, struct sockaddr_in address, client_info *client);
|
||||
void waitInfo(int sock, client_info *client);
|
||||
void handleClientInfo(int sock, udp_pdu info, struct sockaddr_in clientAddress, client_info *client);
|
||||
/* ALIVES FUNCTIONS */
|
||||
void handleAlive(int sock, udp_pdu pdu, struct sockaddr_in clientAddress, client_info *client);
|
||||
void controlAlives();
|
||||
/* TCP CONNECTIONS FUNCTIONS*/
|
||||
void tcpConnections(int tcpSocket);
|
||||
void *handleTcpConnection(void *args);
|
||||
/* COMMAND LINE INTERFACE FUNCTIONS */
|
||||
void startCli();
|
||||
void listClients();
|
||||
void runConnection(unsigned char pack, char *clientId, char *elemId, char *newValue);
|
||||
/* AUXILIAR FUNCTIONS */
|
||||
int storeData(const char *pack, const char *clientId, const char *elem, const char *value);
|
||||
int isInputElem(const char *elemId);
|
||||
int validElems(char *elems);
|
||||
int validCredentials(tcp_pdu pdu, client_info *client);
|
||||
int validAlive(udp_pdu pdu, client_info *client);
|
||||
int validInfo(const char *id, const char *randNum, int tcpPort, char *elems, client_info *client);
|
||||
|
||||
config cfg; /* Configuració del servidor */
|
||||
clients_db cdb; /* Base de dades */
|
||||
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
signal(SIGINT, handler);
|
||||
signal(SIGTSTP, SIG_IGN);
|
||||
memset(&cfg, 0, sizeof(config));
|
||||
memset(&cdb, 0, sizeof(clients_db));
|
||||
const char *cfgname = "server.cfg";
|
||||
const char *dbname = "bbdd_dev.dat";
|
||||
if (argc > 1)
|
||||
{
|
||||
const char *option = argv[1];
|
||||
if (strcmp(option, "-c") == 0)
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
printf("%s -c <filename>\n", argv[0]);
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
cfgname = argv[2];
|
||||
}
|
||||
else if (strcmp(option, "-d") == 0)
|
||||
DEBUG_ON = 1;
|
||||
else if (strcmp(option, "-u") == 0)
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
printf("%s -u <filename>\n", argv[0]);
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
dbname = argv[2];
|
||||
}
|
||||
}
|
||||
check(readConfig(&cfg, cfgname),
|
||||
"Error llegint el fitxer de configuració.\n");
|
||||
check(readDb(&cdb, dbname),
|
||||
"Error llegint el fitxer de dispositius.\n");
|
||||
check(shareClientsInfo(&cdb), "Error compartint memoria\n");
|
||||
|
||||
int udpSocket, tcpSocket;
|
||||
check((udpSocket = socket(AF_INET, SOCK_DGRAM, 0)), "Error al connectar el socket udp.\n");
|
||||
check(bindTo(udpSocket, cfg.udpPort), "Error al bind del udpSocket");
|
||||
check((tcpSocket = socket(AF_INET, SOCK_STREAM, 0)), "Error al connectar el socket tcp.\n");
|
||||
check(bindTo(tcpSocket, cfg.tcpPort), "Error al bind del tcpSocket");
|
||||
pid_t regAtt, alives, waitConn, cli;
|
||||
if ((regAtt = fork()) == 0)
|
||||
attendClients(udpSocket);
|
||||
if ((alives = fork()) == 0)
|
||||
controlAlives();
|
||||
if ((waitConn = fork()) == 0)
|
||||
tcpConnections(tcpSocket);
|
||||
if ((cli = fork()) == 0)
|
||||
startCli();
|
||||
if (cli == -1 || waitConn == -1 || alives == -1 || regAtt == -1)
|
||||
{
|
||||
perror("Error realitzant un fork al procés principal\n");
|
||||
kill(-getpid(), SIGINT);
|
||||
}
|
||||
/* Si qualsevol procés fill acaba
|
||||
envia una señal SIGINT a tots els
|
||||
processos */
|
||||
wait(NULL);
|
||||
kill(-getpid(), SIGINT);
|
||||
}
|
||||
|
||||
/*--------------------------------------------------*/
|
||||
/*--------------------- CLI ------------------------*/
|
||||
/*--------------------------------------------------*/
|
||||
|
||||
void startCli()
|
||||
/* Simula l'execució de la consola de comandes */
|
||||
{
|
||||
while (1)
|
||||
{
|
||||
char input[100] = {'\0'};
|
||||
char *command;
|
||||
fgets(input, sizeof(input), stdin);
|
||||
command = strtok(input, " \n");
|
||||
if (command != NULL)
|
||||
{
|
||||
if (strcmp(command, "list") == 0)
|
||||
{
|
||||
listClients();
|
||||
}
|
||||
else if (strcmp(command, "quit") == 0)
|
||||
exit(EXIT_SUCCESS);
|
||||
else if (strcmp(command, "set") == 0)
|
||||
{
|
||||
char *clientId = strtok(NULL, " \n");
|
||||
char *elemId = strtok(NULL, " \n");
|
||||
char *newValue = strtok(NULL, " \n");
|
||||
if (clientId == NULL || elemId == NULL || newValue == NULL || strtok(NULL, " \n") != NULL)
|
||||
printf("set <identificador_dispositiu> <identificador_element> <nou_valor>\n");
|
||||
else
|
||||
runConnection(SET_DATA, clientId, elemId, newValue);
|
||||
}
|
||||
else if (strcmp(command, "get") == 0)
|
||||
{
|
||||
char *clientId = strtok(NULL, " \n");
|
||||
char *elemId = strtok(NULL, " \n");
|
||||
if (clientId == NULL || elemId == NULL || strtok(NULL, " \n") != NULL)
|
||||
printf("get <identificador_dispositiu> <identificador_element>\n");
|
||||
else
|
||||
runConnection(GET_DATA, clientId, elemId, "");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Comanda %s no reconeguda\n", command);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void listClients()
|
||||
{
|
||||
printf("\n-----Id----- --RNDM-- ------ IP ----- ----ESTAT--- --ELEMENTS-------------------------------------------\n");
|
||||
for (int i = 0; i < cdb.length; i++)
|
||||
{
|
||||
client_info client = cdb.clients[i];
|
||||
const char *state = client.state == DISCONNECTED ? "DISCONNECTED" : client.state == WAIT_INFO ? "WAIT_INFO" : client.state == SEND_ALIVE ? "SEND_ALIVE" : "\0";
|
||||
printf("%-12s %-8s %-15s %-12s %-50s\n", client.id, client.randNum, client.ip, state, client.elems);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
void runConnection(unsigned char pack, char *clientId, char *elemId, char *value)
|
||||
{
|
||||
int clientIndex, sock;
|
||||
if ((clientIndex = isAuthorized(&cdb, clientId)) > -1)
|
||||
{
|
||||
client_info *client = &(cdb.clients[clientIndex]);
|
||||
if (client->state == SEND_ALIVE)
|
||||
{
|
||||
if (hasElem(elemId, client))
|
||||
{
|
||||
if (pack == SET_DATA && !isInputElem(elemId))
|
||||
{
|
||||
printf("L'element %s no es un element d'entrada (actuador)\n", elemId);
|
||||
return;
|
||||
}
|
||||
check((sock = socket(AF_INET, SOCK_STREAM, 0)), "Error creant un socket\n");
|
||||
if (connectTo(sock, client->ip, client->tcpPort) >= 0)
|
||||
{
|
||||
check(sendTcp(sock, pack, cfg.id, client->randNum, elemId, value, client->id), "Error en el send\n");
|
||||
fd_set inputs;
|
||||
check(selectIn(sock, &inputs, M), "Error en el select\n");
|
||||
if (FD_ISSET(sock, &inputs))
|
||||
{
|
||||
tcp_pdu response;
|
||||
check(recv(sock, &response, sizeof(tcp_pdu), 0), "Error rebent informació\n");
|
||||
if (response.pack == DATA_ACK)
|
||||
{
|
||||
debugPrint("Dades acceptades");
|
||||
storeData(pack == SET_DATA ? "SET_DATA" : "GET_DATA", client->id, response.elem, response.value);
|
||||
}
|
||||
else if (response.pack == DATA_NACK)
|
||||
debugPrint("Dades no acceptades");
|
||||
else if (response.pack == DATA_REJ)
|
||||
{
|
||||
debugPrint("Dades rebutjades, client passa a l'estat DISCONNECTED");
|
||||
disconnectClient(client);
|
||||
}
|
||||
}
|
||||
else
|
||||
debugPrint("No s'ha rebut cap resposta del client");
|
||||
}
|
||||
else
|
||||
{
|
||||
debugPrint("Ha hagut un error connectant amb el client");
|
||||
disconnectClient(client);
|
||||
}
|
||||
close(sock);
|
||||
}
|
||||
else
|
||||
printf("\tL'element %s no forma part del client %s\n", elemId, clientId);
|
||||
}
|
||||
else
|
||||
printf("\tEl client %s no es troba connectat\n", clientId);
|
||||
}
|
||||
else
|
||||
printf("\tEl dispositiu introduit no forma part del sistema.\n");
|
||||
}
|
||||
|
||||
int isInputElem(const char *elemId)
|
||||
{
|
||||
int len = strlen(elemId);
|
||||
return elemId[len - 1] == 'I';
|
||||
}
|
||||
|
||||
/*--------------------------------------------------*/
|
||||
/*-------------- HANDLE TCP CONNECTIONS ------------*/
|
||||
/*--------------------------------------------------*/
|
||||
void tcpConnections(int tcpSocket)
|
||||
/* Executa el procés d'espera de connexions tcp */
|
||||
{
|
||||
check(listen(tcpSocket, SERVER_BACKLOG), "Error escoltant per el port tcp\n");
|
||||
while (1)
|
||||
{
|
||||
int clientSocket;
|
||||
pthread_t newThread;
|
||||
check((clientSocket = accept(tcpSocket, NULL, NULL)), "Ha hagut un error al acceptar un socket, el màxim permes està definit a la llibreria 'utils.h'\n");
|
||||
check(pthread_create(&newThread, NULL, handleTcpConnection, &clientSocket), "Error creating a thread");
|
||||
check(pthread_detach(newThread), "Error detaching a thread");
|
||||
}
|
||||
}
|
||||
|
||||
void *handleTcpConnection(void *args)
|
||||
{
|
||||
int clientSocket = *((int *)args);
|
||||
char debugMessage[55] = {'\0'};
|
||||
fd_set inputs;
|
||||
check(selectIn(clientSocket, &inputs, TCP_WAIT_TIME), "Error en el select\n");
|
||||
if (FD_ISSET(clientSocket, &inputs))
|
||||
{
|
||||
int clientIndex;
|
||||
tcp_pdu pdu;
|
||||
check(recv(clientSocket, &pdu, sizeof(tcp_pdu), 0), "Error rebent informació del client\n");
|
||||
if (pdu.pack == SEND_DATA)
|
||||
{
|
||||
if ((clientIndex = isAuthorized(&cdb, pdu.id)) != -1)
|
||||
{
|
||||
client_info *client = &(cdb.clients[clientIndex]);
|
||||
sprintf(debugMessage, "El client %s ha enviat un paquet SEND_DATA", client->id);
|
||||
debugPrint(debugMessage);
|
||||
if (validCredentials(pdu, client))
|
||||
{
|
||||
if (client->state == SEND_ALIVE)
|
||||
{
|
||||
if (hasElem(pdu.elem, client))
|
||||
{
|
||||
int dataStored = storeData("SEND_DATA", client->id, pdu.elem, pdu.value);
|
||||
if (dataStored == 0)
|
||||
{
|
||||
debugPrint("Dades emmagatzemades");
|
||||
check(sendTcp(clientSocket, DATA_ACK, cfg.id, client->randNum, pdu.elem, pdu.value, client->id), "Error en l'enviament de DATA_ACK\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
debugPrint("No s'han pogut emmagatzemar les dades");
|
||||
check(sendTcp(clientSocket, DATA_NACK, cfg.id, client->randNum, pdu.elem, pdu.value, "No s'han pogut emmagatzemar les dades al servidor"), "Error enviant DATA_NACK\n");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
debugPrint("L'element especificat en el paquet no forma part del client");
|
||||
check(sendTcp(clientSocket, DATA_NACK, cfg.id, client->randNum, pdu.elem, pdu.value, "L'element no es troba en el dispositiu"), "Error enviant DATA_NACK\n");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
debugPrint("El client no es troba en l'estat SEND_ALIVE");
|
||||
disconnectClient(client);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
debugPrint("Dades del client incorrectes");
|
||||
check(sendTcp(clientSocket, DATA_REJ, cfg.id, pdu.randNum, pdu.elem, pdu.value, ""), "Error enviant DATA_REJ\n");
|
||||
disconnectClient(client);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
debugPrint("Un client no autoritzat ha intentat enviar un paquet SEND_DATA");
|
||||
check(sendTcp(clientSocket, DATA_REJ, cfg.id, pdu.randNum, pdu.elem, pdu.value, ""), "Error enviant DATA_REJ\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*--------------------------------------------------*/
|
||||
/*-------------- CONTROL ALIVE CLIENTS -------------*/
|
||||
/*--------------------------------------------------*/
|
||||
void controlAlives()
|
||||
/* Comprova que cada client segueix operatiu */
|
||||
{
|
||||
while (1)
|
||||
{
|
||||
time_t now = time(NULL);
|
||||
for (int i = 0; i < cdb.length; i++)
|
||||
{
|
||||
client_info *client = &(cdb.clients[i]);
|
||||
if (client->lastAlive != -1)
|
||||
{
|
||||
time_t diff = difftime(now, client->lastAlive);
|
||||
if (client->state == REGISTERED)
|
||||
{
|
||||
if (diff >= FIRST_ALIVE_TIMEOUT)
|
||||
{
|
||||
char debugMessage[60] = {'\0'};
|
||||
sprintf(debugMessage, "No s'ha rebut el primer ALIVE del client %s", client->id);
|
||||
debugPrint(debugMessage);
|
||||
disconnectClient(client);
|
||||
}
|
||||
}
|
||||
else if (client->state == SEND_ALIVE)
|
||||
{
|
||||
if (diff >= ALIVE_TIMEOUT * 3)
|
||||
{
|
||||
char debugMessage[60] = {'\0'};
|
||||
sprintf(debugMessage, "El client %s no ha enviat 3 ALIVES consecutius", client->id);
|
||||
debugPrint(debugMessage);
|
||||
disconnectClient(client);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*--------------------------------------------------*/
|
||||
/*----------------- ATTEND CLIENTS -----------------*/
|
||||
/*--------------------------------------------------*/
|
||||
void attendClients(int socket)
|
||||
/* Espera a rebre paquets UDP dels clients */
|
||||
{
|
||||
reg_thread_args args;
|
||||
socklen_t len = sizeof(struct sockaddr_in);
|
||||
args.socket = socket;
|
||||
while (1)
|
||||
{
|
||||
pthread_t newThread;
|
||||
check(recvfrom(socket, &(args.pdu), sizeof(udp_pdu), 0, (struct sockaddr *)&(args.clientAddress), &len), "Error rebent informació del socket");
|
||||
check(pthread_create(&newThread, NULL, handlePdu, &args), "Error creating a thread");
|
||||
check(pthread_detach(newThread), "Error detaching a thread");
|
||||
}
|
||||
}
|
||||
|
||||
void *handlePdu(void *args)
|
||||
{
|
||||
reg_thread_args reg_args = *((reg_thread_args *)args);
|
||||
udp_pdu pdu = reg_args.pdu;
|
||||
int attSocket = reg_args.socket;
|
||||
struct sockaddr_in clientAddress = reg_args.clientAddress;
|
||||
int clientIndex;
|
||||
if ((clientIndex = isAuthorized(&cdb, pdu.id)) > -1)
|
||||
{
|
||||
client_info *client = &(cdb.clients[clientIndex]);
|
||||
if (pdu.pack == REG_REQ)
|
||||
registerClient(attSocket, pdu, clientAddress, client);
|
||||
else if (pdu.pack == ALIVE)
|
||||
handleAlive(attSocket, pdu, clientAddress, client);
|
||||
}
|
||||
else
|
||||
check(sendUdp(attSocket, REG_REJ, cfg.id, "00000000", "Dispositiu no autoritzat en el sistema", clientAddress), "Error enviant REG_REJ\n");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*--------------------------------------------------*/
|
||||
/*----------------- REGISTER CLIENTS ---------------*/
|
||||
/*--------------------------------------------------*/
|
||||
void registerClient(int sock, udp_pdu pdu, struct sockaddr_in address, client_info *client)
|
||||
{
|
||||
/* COMPROVEM LES DADES DE LA PDU I DEL CLIENT */
|
||||
if (strcmp(pdu.randNum, "00000000") != 0 || strcmp(pdu.data, "") != 0)
|
||||
{
|
||||
disconnectClient(client);
|
||||
check(sendUdp(sock, REG_REJ, cfg.id, "00000000", "Dades incorrectes", address), "Error enviant REG_REJ\n");
|
||||
return;
|
||||
}
|
||||
if (client->state != DISCONNECTED)
|
||||
{
|
||||
disconnectClient(client);
|
||||
return;
|
||||
}
|
||||
char randNum[9] = {'\0'}, data[61] = {'\0'}, debugMessage[60] = {'\0'};
|
||||
int newSocket, port;
|
||||
/* GENEREM NOMBRE ALEATORI I OBRIM UN NOU PORT */
|
||||
sprintf(randNum, "%d", generateRandNum(10000000, 99999999));
|
||||
check((newSocket = socket(AF_INET, SOCK_DGRAM, 0)), "Error al connectar el socket udp.\n");
|
||||
check(bindTo(newSocket, 0), "Error al bind del udpSocket");
|
||||
check((port = getPort(newSocket)), "Error agafant port\n");
|
||||
sprintf(data, "%d", port);
|
||||
check(sendUdp(newSocket, REG_ACK, cfg.id, randNum, data, address), "Error enviant REG_ACK\n");
|
||||
sprintf(debugMessage, "Client %s pasa a l'estat WAIT_INFO", client->id);
|
||||
debugPrint(debugMessage);
|
||||
client->state = WAIT_INFO;
|
||||
strcpy(client->randNum, randNum);
|
||||
waitInfo(newSocket, client);
|
||||
close(newSocket);
|
||||
}
|
||||
|
||||
void waitInfo(int sock, client_info *client)
|
||||
/* Executem el procés de rebuda d'informació del client */
|
||||
{
|
||||
fd_set inputs;
|
||||
check(selectIn(sock, &inputs, INFO_WAIT_TIME), "Error en el select\n");
|
||||
if (FD_ISSET(sock, &inputs))
|
||||
{
|
||||
udp_pdu info;
|
||||
struct sockaddr_in infoAddress;
|
||||
socklen_t len = sizeof(struct sockaddr_in);
|
||||
memset(&info, 0, sizeof(udp_pdu));
|
||||
check(recvfrom(sock, &info, sizeof(udp_pdu), 0, (struct sockaddr *)&infoAddress, &len), "Error al rebre l'informació");
|
||||
if (info.pack == REG_INFO)
|
||||
handleClientInfo(sock, info, infoAddress, client);
|
||||
else
|
||||
disconnectClient(client);
|
||||
}
|
||||
else
|
||||
disconnectClient(client);
|
||||
}
|
||||
|
||||
void handleClientInfo(int sock, udp_pdu info, struct sockaddr_in clientAddress, client_info *client)
|
||||
{
|
||||
int tcpPort = atoi(strtok(info.data, ","));
|
||||
char *elems = strtok(NULL, ",");
|
||||
if (validInfo(info.id, info.randNum, tcpPort, elems, client))
|
||||
{
|
||||
char data[6], debugMessage[60] = {'\0'};
|
||||
sprintf(data, "%d", cfg.tcpPort);
|
||||
check(sendUdp(sock, INFO_ACK, cfg.id, client->randNum, data, clientAddress), "Error enviant INFO_NACK\n");
|
||||
/* Registrem les dades del client */
|
||||
strcpy(client->elems, elems);
|
||||
strcpy(client->ip, inet_ntoa(clientAddress.sin_addr));
|
||||
client->tcpPort = tcpPort;
|
||||
client->lastAlive = time(NULL);
|
||||
client->state = REGISTERED;
|
||||
sprintf(debugMessage, "Client %s pasa a l'estat REGISTERED", client->id);
|
||||
debugPrint(debugMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
check(sendUdp(sock, INFO_NACK, cfg.id, client->randNum, "Dades incorrectes\n", clientAddress), "Error enviant INFO_NACK\n");
|
||||
disconnectClient(client);
|
||||
}
|
||||
}
|
||||
|
||||
/*--------------------------------------------------*/
|
||||
/*----------------- SEND ALIVES --------------------*/
|
||||
/*--------------------------------------------------*/
|
||||
void handleAlive(int sock, udp_pdu pdu, struct sockaddr_in clientAddress, client_info *client)
|
||||
{
|
||||
if (client->state == REGISTERED || client->state == SEND_ALIVE)
|
||||
{
|
||||
if (validAlive(pdu, client))
|
||||
{
|
||||
client->lastAlive = time(NULL);
|
||||
check(sendUdp(sock, ALIVE, cfg.id, client->randNum, client->id, clientAddress), "Error enviant ALIVE\n");
|
||||
if (client->state == REGISTERED)
|
||||
{
|
||||
char debugMessage[60] = {'\0'};
|
||||
sprintf(debugMessage, "Client %s pasa a l'estat SEND_ALIVE", client->id);
|
||||
debugPrint(debugMessage);
|
||||
client->state = SEND_ALIVE;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
check(sendUdp(sock, ALIVE_REJ, cfg.id, client->randNum, "Dades del paquet ALIVE incorrectes\n", clientAddress), "Error enviant ALIVE_REJ\n");
|
||||
disconnectClient(client);
|
||||
}
|
||||
}
|
||||
else
|
||||
disconnectClient(client);
|
||||
}
|
||||
|
||||
/*-------------------------------------------------*/
|
||||
/*-----------------AUXILIAR FUNCTIONS--------------*/
|
||||
/*-------------------------------------------------*/
|
||||
|
||||
void handler(int sig)
|
||||
{
|
||||
while (wait(NULL) > 0)
|
||||
;
|
||||
shmdt(cdb.clients);
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
|
||||
int storeData(const char *pack, const char *clientId,
|
||||
const char *elem, const char *value)
|
||||
{
|
||||
char filename[17] = {'\0'};
|
||||
sprintf(filename, "%s.data", clientId);
|
||||
FILE *fp = fopen(filename, "a");
|
||||
if (fp == NULL)
|
||||
return -1;
|
||||
time_t t = time(NULL);
|
||||
struct tm date = *localtime(&t);
|
||||
if (fprintf(fp, "%d-%d-%d;%s;%s;%s;%s\n", date.tm_year + 1900, date.tm_mon + 1, date.tm_mday, __TIME__, pack, elem, value) == -1)
|
||||
return -1;
|
||||
fflush(fp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int validAlive(udp_pdu pdu, client_info *client)
|
||||
{
|
||||
return strcmp(pdu.id, client->id) == 0 &&
|
||||
strcmp(pdu.randNum, client->randNum) == 0 &&
|
||||
strcmp(pdu.data, "") == 0;
|
||||
}
|
||||
|
||||
int validInfo(const char *id, const char *randNum, int tcpPort, char *elems, client_info *client)
|
||||
{
|
||||
return strcmp(id, client->id) == 0 &&
|
||||
strcmp(randNum, client->randNum) == 0 &&
|
||||
tcpPort >= 1024 &&
|
||||
tcpPort <= 65535 &&
|
||||
validElems(elems);
|
||||
}
|
||||
|
||||
int validCredentials(tcp_pdu pdu, client_info *client)
|
||||
{
|
||||
return strcmp(pdu.randNum, client->randNum) == 0;
|
||||
}
|
||||
|
||||
int validElems(char *elems)
|
||||
{
|
||||
int numElems = 0;
|
||||
char cpy[50] = {'\0'};
|
||||
strcpy(cpy, elems);
|
||||
char *elem = strtok(cpy, ";");
|
||||
while (elem != NULL)
|
||||
{
|
||||
numElems++;
|
||||
if (strlen(elem) != 7)
|
||||
return 0;
|
||||
if (!isdigit(elem[4]))
|
||||
return 0;
|
||||
if (elem[6] != 'I' && elem[6] != 'O')
|
||||
return 0;
|
||||
if (!isalpha(elem[0]) || !isupper(elem[0]) ||
|
||||
!isalpha(elem[1]) || !isupper(elem[1]) ||
|
||||
!isalpha(elem[2]) || !isupper(elem[2]))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
elem = strtok(NULL, ";");
|
||||
}
|
||||
if (numElems == 0)
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
3
clab/client-server-system/server/server.cfg
Executable file
|
|
@ -0,0 +1,3 @@
|
|||
Id = XERFP345SB2Z
|
||||
UDP-port = 9002
|
||||
TCP-port = 7005
|
||||
380
clab/client-server-system/server/utils.h
Executable file
|
|
@ -0,0 +1,380 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <signal.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include <sys/socket.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/types.h>
|
||||
#include <time.h>
|
||||
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/shm.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#define SERVER_BACKLOG 100
|
||||
#define INFO_WAIT_TIME 2
|
||||
#define TCP_WAIT_TIME 3
|
||||
#define FIRST_ALIVE_TIMEOUT 3
|
||||
#define ALIVE_TIMEOUT 2
|
||||
#define M 3
|
||||
/*--------------TIPUS DE PAQUETS-------------*/
|
||||
|
||||
/* Paquets de la fase de registre */
|
||||
unsigned char REG_REQ = 0x00;
|
||||
unsigned char REG_INFO = 0x01;
|
||||
unsigned char REG_ACK = 0x02;
|
||||
unsigned char INFO_ACK = 0x03;
|
||||
unsigned char REG_NACK = 0x04;
|
||||
unsigned char INFO_NACK = 0x05;
|
||||
unsigned char REG_REJ = 0x06;
|
||||
|
||||
/* Paquets per a la comunicació periòdica */
|
||||
unsigned char ALIVE = 0x10;
|
||||
unsigned char ALIVE_REJ = 0x11;
|
||||
|
||||
/* Paquets per a la transferència de dades amb el servidor */
|
||||
unsigned char SEND_DATA = 0x20;
|
||||
unsigned char SET_DATA = 0x21;
|
||||
unsigned char GET_DATA = 0x22;
|
||||
unsigned char DATA_ACK = 0x23;
|
||||
unsigned char DATA_NACK = 0x24;
|
||||
unsigned char DATA_REJ = 0x25;
|
||||
|
||||
/*---------------ESTATS----------------*/
|
||||
unsigned char DISCONNECTED = 0xa0;
|
||||
unsigned char NOT_REGISTERED = 0xa1;
|
||||
unsigned char WAIT_ACK_REG = 0xa2;
|
||||
unsigned char WAIT_INFO = 0xa3;
|
||||
unsigned char WAIT_ACK_INFO = 0xa4;
|
||||
unsigned char REGISTERED = 0xa5;
|
||||
unsigned char SEND_ALIVE = 0xa6;
|
||||
|
||||
/*-------------STRUCTS-------------*/
|
||||
typedef struct client_info
|
||||
{
|
||||
unsigned char state;
|
||||
char id[13];
|
||||
char randNum[9];
|
||||
char elems[50];
|
||||
char ip[16];
|
||||
unsigned short tcpPort;
|
||||
time_t lastAlive;
|
||||
} client_info;
|
||||
|
||||
typedef struct clients_db
|
||||
{
|
||||
client_info *clients;
|
||||
int length;
|
||||
} clients_db;
|
||||
|
||||
typedef struct udp_pdu
|
||||
{
|
||||
unsigned char pack;
|
||||
char id[13];
|
||||
char randNum[9];
|
||||
char data[61];
|
||||
} udp_pdu;
|
||||
|
||||
typedef struct tcp_pdu
|
||||
{
|
||||
unsigned char pack;
|
||||
char id[13];
|
||||
char randNum[9];
|
||||
char elem[8];
|
||||
char value[16];
|
||||
char data[80];
|
||||
} tcp_pdu;
|
||||
|
||||
typedef struct config
|
||||
{
|
||||
char *id;
|
||||
int udpPort;
|
||||
int tcpPort;
|
||||
} config;
|
||||
|
||||
typedef struct reg_thread_args
|
||||
{
|
||||
udp_pdu pdu;
|
||||
int socket;
|
||||
struct sockaddr_in clientAddress;
|
||||
} reg_thread_args;
|
||||
|
||||
int generateRandNum(int min, int max)
|
||||
{
|
||||
srand(time(0));
|
||||
return rand() % (max + 1 - min) + min;
|
||||
}
|
||||
|
||||
/*--------------------------------------------*/
|
||||
/*---------------DEBUG UTILS------------------*/
|
||||
/*--------------------------------------------*/
|
||||
int DEBUG_ON = 0;
|
||||
|
||||
void debugPrint(const char *message)
|
||||
{
|
||||
if (DEBUG_ON)
|
||||
{
|
||||
printf("%s => %s\n", __TIME__, message);
|
||||
fflush(stdout);
|
||||
}
|
||||
}
|
||||
|
||||
void check(int result, const char *message)
|
||||
{
|
||||
if (result < 0)
|
||||
{
|
||||
perror(message);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
/*--------------------------------------------*/
|
||||
/*---------------DATABASE UTILS---------------*/
|
||||
/*--------------------------------------------*/
|
||||
|
||||
int isAuthorized(clients_db *db, const char *id)
|
||||
{
|
||||
for (int i = 0; i < db->length; i++)
|
||||
if (strcmp(id, db->clients[i].id) == 0)
|
||||
return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void disconnectClient(client_info *client)
|
||||
{
|
||||
if (client->state != DISCONNECTED)
|
||||
{
|
||||
char debugMessage[60] = {'\0'};
|
||||
sprintf(debugMessage, "Client %s pasa a l'estat DISCONNECTED", client->id);
|
||||
debugPrint(debugMessage);
|
||||
}
|
||||
client->state = DISCONNECTED;
|
||||
memset(client->elems, '\0', sizeof(client->elems));
|
||||
memset(client->ip, '\0', sizeof(client->ip));
|
||||
memset(client->randNum, '\0', sizeof(client->randNum));
|
||||
client->tcpPort = -1;
|
||||
client->lastAlive = -1;
|
||||
}
|
||||
|
||||
int shareClientsInfo(clients_db *db)
|
||||
{
|
||||
int shmid;
|
||||
if ((shmid = shmget(IPC_PRIVATE, db->length * sizeof(client_info), IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR)) == -1)
|
||||
return -1;
|
||||
client_info *tmp;
|
||||
if ((tmp = shmat(shmid, (void *)0, 0)) == (void *)-1)
|
||||
return -1;
|
||||
for (int i = 0; i < db->length; i++)
|
||||
tmp[i] = db->clients[i];
|
||||
free(db->clients);
|
||||
db->clients = tmp;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int hasElem(const char *elem, client_info *client)
|
||||
{
|
||||
char cpy[50] = {'\0'};
|
||||
strcpy(cpy, client->elems);
|
||||
char *token = strtok(cpy, ";");
|
||||
while (token != NULL)
|
||||
{
|
||||
if (strcmp(elem, token) == 0)
|
||||
return 1;
|
||||
token = strtok(NULL, ";");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*--------------------------------------------*/
|
||||
/*---------------SOCKETS UTILS----------------*/
|
||||
/*--------------------------------------------*/
|
||||
int sendUdp(int sock, unsigned char pack, char id[13], char randNum[9], char data[61], struct sockaddr_in address)
|
||||
{
|
||||
udp_pdu pdu;
|
||||
pdu.pack = pack;
|
||||
strcpy(pdu.id, id);
|
||||
strcpy(pdu.randNum, randNum);
|
||||
strcpy(pdu.data, data);
|
||||
return sendto(sock, &pdu, sizeof(udp_pdu), 0, (struct sockaddr *)&address, sizeof(struct sockaddr_in));
|
||||
}
|
||||
|
||||
int sendTcp(int sock, unsigned char pack, char id[13], char randNum[9], char elem[8], char value[16], char info[80])
|
||||
{
|
||||
tcp_pdu pdu;
|
||||
pdu.pack = pack;
|
||||
strcpy(pdu.id, id);
|
||||
strcpy(pdu.randNum, randNum);
|
||||
strcpy(pdu.elem, elem);
|
||||
strcpy(pdu.value, value);
|
||||
strcpy(pdu.data, info);
|
||||
return send(sock, &pdu, sizeof(tcp_pdu), 0);
|
||||
}
|
||||
|
||||
int selectIn(int sock, fd_set *inputs, int timeout)
|
||||
{
|
||||
struct timeval t;
|
||||
t.tv_sec = timeout;
|
||||
t.tv_usec = 0;
|
||||
FD_ZERO(inputs);
|
||||
FD_SET(sock, inputs);
|
||||
return select(sock + 1, inputs, NULL, NULL, &t);
|
||||
}
|
||||
|
||||
int bindTo(int sock, uint16_t port)
|
||||
{
|
||||
struct sockaddr_in address;
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_port = htons(port);
|
||||
address.sin_addr.s_addr = INADDR_ANY;
|
||||
return bind(sock, (struct sockaddr *)&address, sizeof(struct sockaddr_in));
|
||||
}
|
||||
|
||||
int connectTo(int sock, const char *ip, unsigned short port)
|
||||
{
|
||||
struct sockaddr_in address;
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_port = htons(port);
|
||||
address.sin_addr.s_addr = inet_addr(ip);
|
||||
return connect(sock, (struct sockaddr *)&address, sizeof(struct sockaddr_in));
|
||||
}
|
||||
|
||||
int getPort(int fd)
|
||||
{
|
||||
struct sockaddr_in address;
|
||||
socklen_t len = sizeof(struct sockaddr_in);
|
||||
int port = 0;
|
||||
memset(&address, 0, sizeof(struct sockaddr_in));
|
||||
if (getsockname(fd, (struct sockaddr *)&address, &len) == -1)
|
||||
return -1;
|
||||
port = ntohs(address.sin_port);
|
||||
return port;
|
||||
}
|
||||
|
||||
/*----------------------------------------*/
|
||||
/*-------------READING UTILS--------------*/
|
||||
/*----------------------------------------*/
|
||||
char *getLine(FILE *fp)
|
||||
{
|
||||
size_t len = 3;
|
||||
char *line = (char *)malloc(len * sizeof(char));
|
||||
int c = fgetc(fp);
|
||||
int i = 0;
|
||||
while (c != '\n' && c != EOF)
|
||||
{
|
||||
line[i] = c;
|
||||
i++;
|
||||
if (i == len)
|
||||
{
|
||||
len++;
|
||||
line = (char *)realloc(line, len * sizeof(char));
|
||||
}
|
||||
c = fgetc(fp);
|
||||
}
|
||||
if (i == 0)
|
||||
{
|
||||
free(line);
|
||||
return NULL;
|
||||
}
|
||||
line[i] = '\0';
|
||||
return line;
|
||||
}
|
||||
|
||||
char *trim(char *str)
|
||||
{
|
||||
char *end;
|
||||
/*left trim*/
|
||||
while (isspace((unsigned char)*str))
|
||||
str++;
|
||||
if (*str == 0) /*Es tot espais*/
|
||||
return str;
|
||||
/*Right trim*/
|
||||
end = str + strlen(str) - 1;
|
||||
while (end > str && (isspace((unsigned char)*end) || (unsigned char)*end == '\n'))
|
||||
end--;
|
||||
end[1] = '\0';
|
||||
return str;
|
||||
}
|
||||
|
||||
char *getCfgLineInfo(FILE *fp)
|
||||
{
|
||||
char *line = getLine(fp);
|
||||
if (line == NULL)
|
||||
return NULL;
|
||||
char *tmp = strrchr(line, '=');
|
||||
tmp++;
|
||||
char *info = trim(tmp);
|
||||
if (strlen(info) <= 0)
|
||||
return NULL;
|
||||
return info;
|
||||
}
|
||||
|
||||
int readConfig(config *cfg, const char *filename)
|
||||
{
|
||||
char *attrs[3];
|
||||
FILE *fp;
|
||||
if ((fp = fopen(filename, "r")) == NULL)
|
||||
return -1;
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
if ((attrs[i] = getCfgLineInfo(fp)) == NULL)
|
||||
{
|
||||
fclose(fp);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
cfg->id = attrs[0];
|
||||
cfg->udpPort = atoi(attrs[1]);
|
||||
cfg->tcpPort = atoi(attrs[2]);
|
||||
fclose(fp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int readDb(clients_db *db, const char *filename)
|
||||
{
|
||||
FILE *fp;
|
||||
if ((fp = fopen(filename, "r")) == NULL)
|
||||
return -1;
|
||||
client_info *clients = (client_info *)malloc(sizeof(client_info));
|
||||
char *line;
|
||||
int len = 1, i = 0;
|
||||
while ((line = getLine(fp)) != NULL)
|
||||
{
|
||||
if (i == len)
|
||||
{
|
||||
len++;
|
||||
clients = (client_info *)realloc(clients, len * sizeof(client_info));
|
||||
}
|
||||
client_info client;
|
||||
memset(&client, 0, sizeof(client_info));
|
||||
client.state = DISCONNECTED;
|
||||
strcpy(client.id, line);
|
||||
memset(client.elems, '\0', sizeof(client.elems));
|
||||
memset(client.ip, '\0', sizeof(client.ip));
|
||||
memset(client.randNum, '\0', sizeof(client.randNum));
|
||||
client.tcpPort = -1;
|
||||
client.lastAlive = -1;
|
||||
clients[i] = client;
|
||||
i++;
|
||||
}
|
||||
if (i == 0)
|
||||
{
|
||||
fclose(fp);
|
||||
free(clients);
|
||||
return -1;
|
||||
}
|
||||
fclose(fp);
|
||||
db->clients = clients;
|
||||
db->length = len;
|
||||
return 0;
|
||||
}
|
||||
1
clab/client-server-system/test/KZ87MKAGB43N.data
Executable file
|
|
@ -0,0 +1 @@
|
|||
2020-04-14;03:10:34;SET_DATA;LUM-0-I;patata
|
||||
8
clab/client-server-system/test/bbdd_dev.dat
Executable file
|
|
@ -0,0 +1,8 @@
|
|||
GHX0E32LWQ6C
|
||||
J4RTN56AC05R
|
||||
00RT45JQ23AC
|
||||
PEG6J2Q98R02
|
||||
AE45F3123BAA
|
||||
AA345FCC23FA
|
||||
FA345778123A
|
||||
KZ87MKAGB43N
|
||||
BIN
clab/client-server-system/test/client
Executable file
5
clab/client-server-system/test/client.cfg
Executable file
|
|
@ -0,0 +1,5 @@
|
|||
Id = GHX0E32LWQ6C
|
||||
Params = LUM-0-O;LUM-0-I;PRE-0-O;TEM-0-O
|
||||
Local-TCP = 6857
|
||||
Server = localhost
|
||||
Server-UDP = 9002
|
||||
5
clab/client-server-system/test/client1.cfg
Executable file
|
|
@ -0,0 +1,5 @@
|
|||
Id = J4RTN56AC05R
|
||||
Params = PIC-0-O;HUM-0-I;HUM-0-O;LUM-0-I
|
||||
Local-TCP = 3927
|
||||
Server = localhost
|
||||
Server-UDP = 2020
|
||||
5
clab/client-server-system/test/client2.cfg
Executable file
|
|
@ -0,0 +1,5 @@
|
|||
Id = 00RT45JQ23AC
|
||||
Params = STA-O-I;TIM-1-O;TIM-1-I
|
||||
Local-TCP = 4206
|
||||
Server = localhost
|
||||
Server-UDP = 2020
|
||||
5
clab/client-server-system/test/client3.cfg
Executable file
|
|
@ -0,0 +1,5 @@
|
|||
Id = PEG6J2Q98R02
|
||||
Params = VID-O-O;VID-0-I;HUM-0-0;TXT-0-I
|
||||
Local-TCP = 5391
|
||||
Server = localhost
|
||||
Server-UDP = 2020
|
||||
5
clab/client-server-system/test/client4.cfg
Executable file
|
|
@ -0,0 +1,5 @@
|
|||
Id = NO87DISP9AUT
|
||||
Params = PRE-O-O;PRE-0-I;STA-0-0;LEC-0-I
|
||||
Local-TCP = 7654
|
||||
Server = localhost
|
||||
Server-UDP = 2020
|
||||
BIN
clab/client-server-system/test/server
Executable file
5
clab/client-server-system/test/server.cfg
Executable file
|
|
@ -0,0 +1,5 @@
|
|||
Id = SRV001GPRX20
|
||||
UDP-port = 2028
|
||||
TCP-port = 7461
|
||||
|
||||
|
||||
674
clab/prime-calculator/LICENSE
Executable file
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
2
clab/prime-calculator/README.md
Executable file
|
|
@ -0,0 +1,2 @@
|
|||
# PrimeNumbersCalculation
|
||||
A C program that check whether a serie of numbers from 2 to N are prime numbers by multiprocessing
|
||||
52
clab/prime-calculator/_gitignore
Executable file
|
|
@ -0,0 +1,52 @@
|
|||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Object files
|
||||
*.o
|
||||
*.ko
|
||||
*.obj
|
||||
*.elf
|
||||
|
||||
# Linker output
|
||||
*.ilk
|
||||
*.map
|
||||
*.exp
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Libraries
|
||||
*.lib
|
||||
*.a
|
||||
*.la
|
||||
*.lo
|
||||
|
||||
# Shared objects (inc. Windows DLLs)
|
||||
*.dll
|
||||
*.so
|
||||
*.so.*
|
||||
*.dylib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
*.i*86
|
||||
*.x86_64
|
||||
*.hex
|
||||
|
||||
# Debug files
|
||||
*.dSYM/
|
||||
*.su
|
||||
*.idb
|
||||
*.pdb
|
||||
|
||||
# Kernel Module Compile Results
|
||||
*.mod*
|
||||
*.cmd
|
||||
.tmp_versions/
|
||||
modules.order
|
||||
Module.symvers
|
||||
Mkfile.old
|
||||
dkms.conf
|
||||
66
clab/prime-calculator/calculador.c
Executable file
|
|
@ -0,0 +1,66 @@
|
|||
/*-------------------------------------------------------------------------
|
||||
PRA1: Pralab2
|
||||
Codi font: calculador.c
|
||||
|
||||
Víctor Martínez Montané
|
||||
--------------------------------------------------------------------------*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
int isprime(long);
|
||||
void sighandler(int);
|
||||
int numprimes = 0;
|
||||
|
||||
/*Reads numbers from the numbers pipe,
|
||||
calculates if those numbers are primes
|
||||
and send the result to the response pipe*/
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
if(signal(SIGTERM, sighandler) == SIG_ERR)
|
||||
{
|
||||
perror("Signal: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
int number;
|
||||
t_infoNumber results;
|
||||
results.pid = getpid();
|
||||
/*Reads every number, calculates and write the results*/
|
||||
while(read(PIPE_NUMBERS_READ, &number, sizeof(int)) > 0)
|
||||
{
|
||||
results.number = number;
|
||||
if(isprime(number))
|
||||
{
|
||||
++numprimes;
|
||||
results.prime = 'Y';
|
||||
}
|
||||
else results.prime = 'N';
|
||||
|
||||
if(write(PIPE_RESPONSES_WRITE, &results, sizeof(t_infoNumber)) == -1)
|
||||
{
|
||||
perror("Error writing into the pipe: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
/*Close the pipes and wait for SIGTERM signal*/
|
||||
close(PIPE_RESPONSES_WRITE);
|
||||
close(PIPE_NUMBERS_READ);
|
||||
pause();
|
||||
}
|
||||
|
||||
/*Handles the signal*/
|
||||
void sighandler(int signum)
|
||||
{
|
||||
exit(numprimes);
|
||||
}
|
||||
|
||||
/*Calculates if n is prime*/
|
||||
int isprime(long n)
|
||||
{
|
||||
for(int i = 2; i < n; ++i)
|
||||
{
|
||||
if(n%i == 0)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
21
clab/prime-calculator/common.h
Executable file
|
|
@ -0,0 +1,21 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
|
||||
#define PIPE_NUMBERS_READ 10
|
||||
#define PIPE_NUMBERS_WRITE 11
|
||||
#define PIPE_RESPONSES_READ 20
|
||||
#define PIPE_RESPONSES_WRITE 21
|
||||
|
||||
#define MAXNUMSIZE 10
|
||||
|
||||
enum boolean {false, true};
|
||||
|
||||
typedef struct{
|
||||
int pid;
|
||||
int number;
|
||||
char prime;
|
||||
} t_infoNumber;
|
||||
155
clab/prime-calculator/controlador.c
Executable file
|
|
@ -0,0 +1,155 @@
|
|||
/*-------------------------------------------------------------------------
|
||||
PRA1: Pralab2
|
||||
Codi font: controlador.c
|
||||
|
||||
Víctor Martínez Montané
|
||||
--------------------------------------------------------------------------*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
/*Creates one generator process and multiple calculator process.
|
||||
Reads the reponses pipe and print the results*/
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
int cp[2], gp[2]; //cp: Responses pipe, gp: Numbers pipe
|
||||
int num_calculators = atoi(argv[1]); //Num of calculators to create
|
||||
int prime_numbers_exit = 0, prime_numbers_pipe = 0;
|
||||
char number[MAXNUMSIZE + 1];
|
||||
pid_t genpid, contpids[num_calculators];
|
||||
|
||||
/* Writing to prompt*/
|
||||
if (write(1, "Calculate prime numbers from 2 to: ", 36) == -1)
|
||||
{
|
||||
perror("Error writing standard out: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/*Reading the number*/
|
||||
if (read(0, number, MAXNUMSIZE) == -1)
|
||||
{
|
||||
perror("Error reading standard int: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/*Print error if the given number is < 2*/
|
||||
if (atoi(number) < 2)
|
||||
{
|
||||
if (write(1, "Error number < 2\n", 16) == -1)
|
||||
perror("Error writing standard out: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/*Creates the pipes*/
|
||||
if (pipe(gp) == -1)
|
||||
{
|
||||
perror("Error creating generator pipe:");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/*Creates the generator*/
|
||||
if((genpid = fork()) == 0)
|
||||
{
|
||||
dup2(gp[1], PIPE_NUMBERS_WRITE);
|
||||
close(gp[0]);
|
||||
close(gp[1]);
|
||||
execlp("./generador", "generador", number, NULL);
|
||||
perror("Error running the generator.");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
else if(genpid == -1)
|
||||
{
|
||||
perror("Fork error on generator.");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/*Creates the responses pipe*/
|
||||
if (pipe(cp) == -1)
|
||||
{
|
||||
perror("Creating numbers pipe:");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/*Creates the calculators*/
|
||||
for (int i = 0; i < num_calculators; ++i)
|
||||
{
|
||||
if((contpids[i] = fork()) == 0)
|
||||
{
|
||||
dup2(gp[0], PIPE_NUMBERS_READ);
|
||||
dup2(cp[1], PIPE_RESPONSES_WRITE);
|
||||
close(gp[1]);
|
||||
close(gp[0]);
|
||||
close(cp[1]);
|
||||
close(cp[0]);
|
||||
execlp("./calculador", "calculador", NULL);
|
||||
perror("Error running the calculator");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
else if(contpids[i] == -1)
|
||||
{
|
||||
perror("Fork error on calculator.");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
/*Duplicates the numbers pipe entry and closes the remaining descriptors*/
|
||||
dup2(cp[0], PIPE_RESPONSES_READ);
|
||||
close(gp[0]);
|
||||
close(gp[1]);
|
||||
close(cp[0]);
|
||||
close(cp[1]);
|
||||
|
||||
/*Treat the response and print the result*/
|
||||
t_infoNumber infon;
|
||||
char buffer[100];
|
||||
while(read(PIPE_RESPONSES_READ, &infon, sizeof(t_infoNumber)) > 0)
|
||||
{
|
||||
sprintf(buffer, "Calculator PID: %5d, \t Number: %4d, Is prime? %2c\n", infon.pid, infon.number, infon.prime);
|
||||
if(write(1, buffer, strlen(buffer)) == -1)
|
||||
{
|
||||
perror("Error writing standart out: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
if(infon.prime == 'Y') ++prime_numbers_pipe;
|
||||
}
|
||||
|
||||
int status = 0;
|
||||
/*Sends SIGTERM to generator*/
|
||||
if(kill(genpid, SIGTERM) == -1)
|
||||
{
|
||||
perror("Error closing generator: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
wait(NULL);
|
||||
|
||||
for(int i = 0; i < num_calculators; ++i)
|
||||
{
|
||||
/*Sends SIGTERM to calculator*/
|
||||
if (kill(contpids[i], SIGTERM) == -1)
|
||||
{
|
||||
perror("Error closing calculator: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
wait(&status);
|
||||
|
||||
/*Checks if the child exited normally*/
|
||||
if(WIFEXITED(status))
|
||||
{
|
||||
prime_numbers_exit += WEXITSTATUS(status);
|
||||
}
|
||||
else
|
||||
{
|
||||
perror("Error on calculador exit: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
/*Show the number of primes detected*/
|
||||
sprintf(buffer, "\nPrime numbers pipe: %d, \t Prime numbers exit: %d\n", prime_numbers_pipe, prime_numbers_exit);
|
||||
if(write(1, buffer, strlen(buffer)) == -1)
|
||||
{
|
||||
perror("Error writing standart out: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
33
clab/prime-calculator/generador.c
Executable file
|
|
@ -0,0 +1,33 @@
|
|||
/*-------------------------------------------------------------------------
|
||||
PRA1: Pralab2
|
||||
Codi font: generador.c
|
||||
|
||||
Víctor Martínez Montané
|
||||
--------------------------------------------------------------------------*/
|
||||
|
||||
#include "common.h"
|
||||
|
||||
/*Writes numbers from 2 to n into the numbers pipe*/
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
/*Wait for SIGTERM signal and exit*/
|
||||
if(signal(SIGTERM, SIG_DFL) == SIG_ERR)
|
||||
{
|
||||
perror("Signal: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
int number = atoi(argv[1]);
|
||||
/*Generate and write the numbers*/
|
||||
for (int i = 2; i <= number; ++i)
|
||||
{
|
||||
if(write(PIPE_NUMBERS_WRITE, &i, sizeof(int)) == -1)
|
||||
{
|
||||
perror("Error writing the generator numbers.");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
close(PIPE_NUMBERS_WRITE);
|
||||
pause();
|
||||
}
|
||||
|
||||
19
clab/prime-calculator/makefile
Executable file
|
|
@ -0,0 +1,19 @@
|
|||
FLAGS = -Wall
|
||||
|
||||
all: controlador.c generador.c calculador.c
|
||||
gcc controlador.c -o controlador $(FLAGS)
|
||||
gcc generador.c -o generador $(FLAGS)
|
||||
gcc calculador.c -o calculador $(FLAGS)
|
||||
|
||||
controlador: controlador.c common.h
|
||||
gcc -I controlador.c -o controlador -I . $(FLAGS)
|
||||
|
||||
generador: generador.c common.h
|
||||
gcc generador.c -o generador $(FLAGS)
|
||||
|
||||
calculador: calculador.c common.h
|
||||
gcc -I calculador.c -o calculador -I . $(FLAGS)
|
||||
|
||||
clean:
|
||||
rm -f calculador controlador generador
|
||||
ls
|
||||
1
java-lab/ArraySorter/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
.idea/
|
||||
120
java-lab/ArraySorter/AlgorithmAnalysis/IntArraySorterCharts.java
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
/**
|
||||
*This class runs the sort algorithms in some ways to check the efficiency and plot the results in charts.
|
||||
*/
|
||||
public class IntArraySorterCharts {
|
||||
private final int xAxisMaxValues = 200;
|
||||
private int xAxisValue;
|
||||
private int shuffleGrade;
|
||||
private int[] array;
|
||||
private IntArraySorter sorter;
|
||||
|
||||
private double[][] bubbleSortSwaps = new double[2][xAxisMaxValues];
|
||||
private double[][] insertionSortSwaps = new double[2][xAxisMaxValues];
|
||||
private double[][] selectionSortSwaps = new double[2][xAxisMaxValues];
|
||||
private double[][] quickSortSwaps = new double[2][xAxisMaxValues];
|
||||
private double[][] radixSortSwaps = new double[2][xAxisMaxValues];
|
||||
|
||||
private double[][] bubbleSortComps = new double[2][xAxisMaxValues];
|
||||
private double[][] insertionSortComps = new double[2][xAxisMaxValues];
|
||||
private double[][] selectionSortComps = new double[2][xAxisMaxValues];
|
||||
private double[][] quickSortComps = new double[2][xAxisMaxValues];
|
||||
private double[][] radixSortComps = new double[2][xAxisMaxValues];
|
||||
|
||||
/**
|
||||
* Runs the sort algorithms increasing the array shuffle grade from 0 to array.length (XAxisMaxValues).
|
||||
* Set the array length constant.
|
||||
* Creates the charts from the results.
|
||||
*/
|
||||
private void shuffleGradeChart() {
|
||||
array = ArrayBuilder.buildArray(xAxisMaxValues);
|
||||
for (shuffleGrade = 0; shuffleGrade < xAxisMaxValues; ++shuffleGrade) {
|
||||
xAxisValue = shuffleGrade;
|
||||
testBubbleSortAndStoreResults(shuffleGrade, array.length, xAxisValue);
|
||||
testInsertionSortAndStoreResults(shuffleGrade, array.length, xAxisValue);
|
||||
testSelectionSortAndStoreResults(shuffleGrade, array.length, xAxisValue);
|
||||
testQuickSortAndStoreResults(shuffleGrade, array.length, xAxisValue);
|
||||
testRadixSortAndStoreResults(shuffleGrade, array.length, xAxisValue);
|
||||
}
|
||||
buildLinealCharts("Shuffle Grade");
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the sort algorithms increasing the array length from 0 to XAxisMaxValues .
|
||||
* Set the shuffle grade constant.
|
||||
* Creates the charts from the results.
|
||||
*/
|
||||
private void lengthGradeChart(){
|
||||
for (int arrayLength = 0; arrayLength < xAxisMaxValues; ++arrayLength) {
|
||||
xAxisValue = arrayLength;
|
||||
shuffleGrade = arrayLength;
|
||||
testBubbleSortAndStoreResults(shuffleGrade, arrayLength, xAxisValue);
|
||||
testInsertionSortAndStoreResults(shuffleGrade, arrayLength, xAxisValue);
|
||||
testSelectionSortAndStoreResults(shuffleGrade, arrayLength, xAxisValue);
|
||||
testQuickSortAndStoreResults(shuffleGrade, arrayLength, xAxisValue);
|
||||
testRadixSortAndStoreResults(shuffleGrade, arrayLength, xAxisValue);
|
||||
}
|
||||
buildLinealCharts("Array length");
|
||||
}
|
||||
|
||||
private void testBubbleSortAndStoreResults(int shuffleGrade, int arrayLength, int XAxisData){
|
||||
buildSorterAndShuffle(shuffleGrade, arrayLength);
|
||||
sorter.bubbleSort();
|
||||
addValues(bubbleSortSwaps, XAxisData, sorter.getNumSwaps());
|
||||
addValues(bubbleSortComps, XAxisData, sorter.getNumComparisons());
|
||||
}
|
||||
|
||||
private void testInsertionSortAndStoreResults(int shuffleGrade, int arrayLength, int XAxisData){
|
||||
buildSorterAndShuffle(shuffleGrade, arrayLength);
|
||||
sorter.insertionSort();
|
||||
addValues(insertionSortSwaps, XAxisData, sorter.getNumSwaps());
|
||||
addValues(insertionSortComps, XAxisData, sorter.getNumComparisons());
|
||||
}
|
||||
private void testSelectionSortAndStoreResults(int shuffleGrade, int arrayLength, int XAxisData){
|
||||
buildSorterAndShuffle(shuffleGrade, arrayLength);
|
||||
sorter.selectionSort();
|
||||
addValues(selectionSortSwaps, XAxisData, sorter.getNumSwaps());
|
||||
addValues(selectionSortComps, XAxisData, sorter.getNumComparisons());
|
||||
}
|
||||
|
||||
private void testQuickSortAndStoreResults(int shuffleGrade, int arrayLength, int XAxisData) {
|
||||
buildSorterAndShuffle(shuffleGrade, arrayLength);
|
||||
sorter.quickSort();
|
||||
addValues(quickSortSwaps, XAxisData, sorter.getNumSwaps());
|
||||
addValues(quickSortComps, XAxisData, sorter.getNumComparisons());
|
||||
}
|
||||
|
||||
private void testRadixSortAndStoreResults(int shuffleGrade, int arrayLength, int XAxisData) {
|
||||
buildSorterAndShuffle(shuffleGrade, arrayLength);
|
||||
sorter.radixSort();
|
||||
addValues(radixSortSwaps, XAxisData, sorter.getNumSwaps());
|
||||
addValues(radixSortComps, XAxisData, sorter.getNumComparisons());
|
||||
}
|
||||
|
||||
private void buildLinealCharts(String xAxisName){
|
||||
LinearChartBuilder chart = new LinearChartBuilder("Num Swaps by " + xAxisName, "Swaps", xAxisName);
|
||||
chart.buildLinearChart(bubbleSortSwaps, insertionSortSwaps, selectionSortSwaps, quickSortSwaps, radixSortSwaps);
|
||||
chart = new LinearChartBuilder("Num Comparisons by " + xAxisName, "Comparisons", xAxisName);
|
||||
chart.buildLinearChart(bubbleSortComps, insertionSortComps, selectionSortComps, quickSortComps, radixSortComps);
|
||||
}
|
||||
|
||||
private void addValues(double[][] array, int x, int y) {
|
||||
array[0][x] = x;
|
||||
array[1][x] = y;
|
||||
}
|
||||
|
||||
private void buildSorterAndShuffle(int shuffleLevel, int arrayLength) {
|
||||
array = ArrayBuilder.buildArray(arrayLength);
|
||||
sorter = new IntArraySorter(array);
|
||||
sorter.fisherYatesShuffle(shuffleLevel);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
IntArraySorterCharts test = new IntArraySorterCharts();
|
||||
test.run();
|
||||
}
|
||||
|
||||
public void run() {
|
||||
shuffleGradeChart();
|
||||
lengthGradeChart();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
import org.jfree.chart.ChartFactory;
|
||||
import org.jfree.chart.JFreeChart;
|
||||
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
|
||||
import org.jfree.data.xy.DefaultXYDataset;
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
/** This class allows us to build linear charts from a set of 2D double arrays. */
|
||||
public class LinearChartBuilder {
|
||||
private String chartTitle;
|
||||
private String YAxis;
|
||||
private String XAxis;
|
||||
|
||||
/**
|
||||
* Creates a LinearChartBuilder with the specified title, YAxis and XAxis name.
|
||||
* @param chartTitle The chart title.
|
||||
* @param YAxis The YAxis name.
|
||||
* @param XAxis The XAxis name.
|
||||
*/
|
||||
public LinearChartBuilder(String chartTitle, String YAxis, String XAxis){
|
||||
this.chartTitle = chartTitle;
|
||||
this.YAxis = YAxis;
|
||||
this.XAxis = XAxis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the linear chart and creates a .png image that contains it.
|
||||
* @param bubbleSortData Contains the data to plot the bubble sort results.
|
||||
* @param insertionSortData Contains the data to plot the insertion sort results.
|
||||
* @param selectionSortData Contains the data to plot the selection sort results.
|
||||
* @param qsData Contains the data to plot the quick sort results.
|
||||
*/
|
||||
public void buildLinearChart(double[][] bubbleSortData,
|
||||
double[][] insertionSortData,
|
||||
double[][] selectionSortData,
|
||||
double[][] qsData,
|
||||
double[][] rsData) {
|
||||
|
||||
DefaultXYDataset dataset = new DefaultXYDataset();
|
||||
dataset.addSeries("Bubble sort", bubbleSortData);
|
||||
dataset.addSeries("Insertion sort", insertionSortData);
|
||||
dataset.addSeries("Selection sort", selectionSortData);
|
||||
dataset.addSeries("Quick sort", qsData);
|
||||
dataset.addSeries("Radix sort", rsData);
|
||||
|
||||
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
|
||||
setRenderSettings(renderer);
|
||||
JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, XAxis, YAxis, dataset);
|
||||
chart.getXYPlot().setRenderer(renderer);
|
||||
|
||||
BufferedImage image = chart.createBufferedImage(1200, 700);
|
||||
buildImage(image, chartTitle);
|
||||
}
|
||||
|
||||
private void buildImage(BufferedImage image, String chartTitle){
|
||||
try {
|
||||
ImageIO.write(image, "png", new File(chartTitle +".png"));
|
||||
} catch (IOException exc) {
|
||||
System.out.println("Error creating image.");
|
||||
}
|
||||
}
|
||||
|
||||
private void setRenderSettings(XYLineAndShapeRenderer renderer){
|
||||
setSeriesPaint(renderer);
|
||||
setSeriesStroke(renderer);
|
||||
}
|
||||
|
||||
private void setSeriesPaint(XYLineAndShapeRenderer renderer){
|
||||
renderer.setSeriesPaint(0, Color.ORANGE);
|
||||
renderer.setSeriesPaint(1, Color.BLUE);
|
||||
renderer.setSeriesPaint(2, Color.GREEN);
|
||||
renderer.setSeriesPaint(3, Color.RED);
|
||||
renderer.setSeriesPaint(4, Color.CYAN);
|
||||
}
|
||||
|
||||
private void setSeriesStroke(XYLineAndShapeRenderer renderer){
|
||||
renderer.setSeriesStroke(0, new BasicStroke(2));
|
||||
renderer.setSeriesStroke(1, new BasicStroke(2));
|
||||
renderer.setSeriesStroke(2, new BasicStroke(2));
|
||||
renderer.setSeriesStroke(3, new BasicStroke(2));
|
||||
renderer.setSeriesStroke(4, new BasicStroke(2));
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 109 KiB |
|
After Width: | Height: | Size: 79 KiB |
BIN
java-lab/ArraySorter/Chart_Images/Num Swaps by Array length.png
Normal file
|
After Width: | Height: | Size: 107 KiB |
BIN
java-lab/ArraySorter/Chart_Images/Num Swaps by Shuffle Grade.png
Normal file
|
After Width: | Height: | Size: 102 KiB |
38
java-lab/ArraySorter/IntArraySorter.iml
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<?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$/Test" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/AlgorithmAnalysis" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="module-library" scope="TEST">
|
||||
<library name="JUnit5.4">
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter/5.4.2/junit-jupiter-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-api/5.4.2/junit-jupiter-api-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/apiguardian/apiguardian-api/1.0.0/apiguardian-api-1.0.0.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/opentest4j/opentest4j/1.1.1/opentest4j-1.1.1.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-commons/1.4.2/junit-platform-commons-1.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-params/5.4.2/junit-jupiter-params-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-engine/5.4.2/junit-jupiter-engine-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-engine/1.4.2/junit-platform-engine-1.4.2.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</orderEntry>
|
||||
<orderEntry type="module-library" exported="">
|
||||
<library>
|
||||
<CLASSES>
|
||||
<root url="jar://$USER_HOME$/Escritorio/Java/jfreechart-1.5.0.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</orderEntry>
|
||||
</component>
|
||||
</module>
|
||||
37
java-lab/ArraySorter/Test/BubbleSortTest.java
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BubbleSortTest {
|
||||
static final int length = 50;
|
||||
|
||||
@Test
|
||||
void array_ordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.bubbleSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_del_reves() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildReversedArray(length));
|
||||
sorter.bubbleSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_poco_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.fisherYatesShuffle(length/3);
|
||||
sorter.bubbleSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_muy_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.fisherYatesShuffle(length);
|
||||
sorter.bubbleSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
}
|
||||
37
java-lab/ArraySorter/Test/InsertionSortTest.java
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class InsertionSortTest {
|
||||
static final int length = 50;
|
||||
|
||||
@Test
|
||||
void array_ordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.insertionSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_del_reves() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildReversedArray(length));
|
||||
sorter.insertionSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_poco_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.fisherYatesShuffle(length/3);
|
||||
sorter.insertionSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_muy_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.fisherYatesShuffle(length);
|
||||
sorter.insertionSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
}
|
||||
38
java-lab/ArraySorter/Test/Quick_sort_test.java
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class Quick_sort_test {
|
||||
static final int length = 50;
|
||||
|
||||
@Test
|
||||
void array_ordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.quickSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_ordenado_al_reves() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildReversedArray(length));
|
||||
sorter.quickSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_poco_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.fisherYatesShuffle(length/3);
|
||||
sorter.quickSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_muy_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.fisherYatesShuffle(length);
|
||||
sorter.quickSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
}
|
||||
38
java-lab/ArraySorter/Test/Radix_sort_test.java
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
|
||||
class Radix_sort_test {
|
||||
static final int length = 50;
|
||||
|
||||
@Test
|
||||
void array_ordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.radixSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_ordenado_del_reves() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildReversedArray(length));
|
||||
sorter.radixSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_poco_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildReversedArray(length));
|
||||
sorter.fisherYatesShuffle(length/3);
|
||||
sorter.radixSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_muy_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildReversedArray(length));
|
||||
sorter.fisherYatesShuffle(length);
|
||||
sorter.radixSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
}
|
||||
39
java-lab/ArraySorter/Test/SelectionSortTest.java
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SelectionSortTest {
|
||||
static final int length = 50;
|
||||
|
||||
@Test
|
||||
void array_ordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.selectionSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_del_reves() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildReversedArray(length));
|
||||
sorter.selectionSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_poco_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.fisherYatesShuffle(length/3);
|
||||
sorter.selectionSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void array_muy_desordenado() {
|
||||
IntArraySorter sorter = new IntArraySorter(ArrayBuilder.buildArray(length));
|
||||
sorter.fisherYatesShuffle(length);
|
||||
sorter.selectionSort();
|
||||
assertTrue(sorter.isSorted());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
30
java-lab/ArraySorter/src/ArrayBuilder.java
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
/**
|
||||
* This class helps us to build and copy arrays.
|
||||
*/
|
||||
public class ArrayBuilder {
|
||||
/**
|
||||
* Builds a sorted array of integers from 0 to length.
|
||||
* @param length the array length
|
||||
* @return the array created.
|
||||
*/
|
||||
public static int[] buildArray(int length) {
|
||||
int[] array = new int[length];
|
||||
for (int j = 0; j < array.length; ++j) {
|
||||
array[j] = j;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a sorted array of integers from length to 0.
|
||||
* @param length the array length
|
||||
* @return the array created.
|
||||
*/
|
||||
public static int[] buildReversedArray(int length) {
|
||||
int[] array = new int[length];
|
||||
for (int i = array.length - 1; i >= 0; --i) {
|
||||
array[array.length - 1 - i] = i;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
}
|
||||
198
java-lab/ArraySorter/src/IntArraySorter.java
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
import java.util.Random;
|
||||
|
||||
public class IntArraySorter {
|
||||
private final int[] array;
|
||||
private int numComparisons;
|
||||
private int numSwaps;
|
||||
|
||||
public int getNumComparisons() {
|
||||
return numComparisons;
|
||||
}
|
||||
|
||||
public int getNumSwaps() {
|
||||
return numSwaps;
|
||||
}
|
||||
|
||||
public IntArraySorter(int[] array) {
|
||||
this.array = array;
|
||||
}
|
||||
|
||||
public boolean isSorted() {
|
||||
for (int i = 0; i < array.length - 1; i++) {
|
||||
if (array[i] > array[i + 1]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void swap(int i, int j) {
|
||||
int tmp = array[i];
|
||||
array[i] = array[j];
|
||||
array[j] = tmp;
|
||||
numSwaps += 1;
|
||||
}
|
||||
|
||||
public boolean lessThanOrEqual(int i1, int i2) {
|
||||
numComparisons += 1;
|
||||
return i1 <= i2;
|
||||
}
|
||||
|
||||
public void insertionSort() {
|
||||
for (int s = 1; s < array.length; ++s) {
|
||||
int insert = s;
|
||||
for (int i = s - 1; i >= 0; i--) {
|
||||
if (!lessThanOrEqual(array[i], array[insert])) {
|
||||
swap(i, insert);
|
||||
insert = i;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void bubbleSort() {
|
||||
for (int s = 0; s < array.length; s++) {
|
||||
int swaps = numSwaps;
|
||||
for (int i = array.length - 1; i > s; i--) {
|
||||
if (!lessThanOrEqual(array[i - 1], array[i])) {
|
||||
swap(i - 1, i);
|
||||
}
|
||||
}
|
||||
if (numSwaps == swaps) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void selectionSort() {
|
||||
for (int i = 0; i < array.length - 1; ++i) {
|
||||
int lesser = i;
|
||||
for (int s = i + 1; s < array.length; ++s) {
|
||||
if (lessThanOrEqual(array[s], array[lesser])) {
|
||||
lesser = s;
|
||||
}
|
||||
}
|
||||
if (lesser != i) {
|
||||
swap(i, lesser);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void quickSort() {
|
||||
int left = 0, right = array.length;
|
||||
quickSort(left, right);
|
||||
}
|
||||
|
||||
private void quickSort(int left, int right) {
|
||||
if (left < right) {
|
||||
int pivotPos = choosePivotPos(left, right);
|
||||
int pivotValue = array[pivotPos];
|
||||
swap(pivotPos, right - 1);
|
||||
int pos = partition(pivotValue, left, right - 1);
|
||||
swap(pos, right - 1);
|
||||
quickSort(left, pos);
|
||||
quickSort(pos + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
private int partition(int pivotValue, int left, int right) {
|
||||
while (true) {
|
||||
left = itemFromLeftPos(pivotValue, left, right);
|
||||
right = itemFromRightPos(pivotValue, left, right);
|
||||
if (left >= right) {
|
||||
return left;
|
||||
}
|
||||
swap(left, right);
|
||||
}
|
||||
}
|
||||
|
||||
public void fisherYatesShuffle(int n) {
|
||||
for (int i = 0; i < n; ++i) {
|
||||
int j = new Random().nextInt(n);
|
||||
int tmp = array[i];
|
||||
array[i] = array[j];
|
||||
array[j] = tmp;
|
||||
}
|
||||
}
|
||||
|
||||
/*-----------------------AUXILIARY METHODS------------------------------*/
|
||||
|
||||
private int itemFromLeftPos(int pivot, int left, int right) {
|
||||
for (int i = left; i < right; ++i) {
|
||||
if (!lessThanOrEqual(array[i], pivot)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return right;
|
||||
}
|
||||
|
||||
private int itemFromRightPos(int pivot, int left, int right) {
|
||||
for (int i = right - 1; i >= left; --i) {
|
||||
if (lessThanOrEqual(array[i], pivot)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
private int choosePivotPos(int left, int right) {
|
||||
return left + new Random().nextInt(right - left);
|
||||
}
|
||||
|
||||
|
||||
/*--------------------------RADIX SORT------------------------------*/
|
||||
|
||||
private boolean maxDigitLengthReached = false;
|
||||
|
||||
public void radixSort() {
|
||||
int n = 1;
|
||||
while (!maxDigitLengthReached) {
|
||||
countSort(n);
|
||||
n *= 10;
|
||||
}
|
||||
}
|
||||
|
||||
private void countSort(int n) {
|
||||
maxDigitLengthReached = true;
|
||||
int[] results = new int[array.length];
|
||||
int[] buckets = new int[10];
|
||||
count(buckets, n);
|
||||
if (!maxDigitLengthReached) {
|
||||
sumCount(buckets);
|
||||
sort(buckets, results, n);
|
||||
for (int i = 0; i < array.length; ++i) {
|
||||
array[i] = results[i];
|
||||
numSwaps += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void count(int[] buckets, int n) {
|
||||
for (int i = 0; i < array.length; ++i) {
|
||||
int value = array[i] / n;
|
||||
int digit = value % 10;
|
||||
if (value > 0) {
|
||||
maxDigitLengthReached = false;
|
||||
numComparisons += 1;
|
||||
}
|
||||
buckets[digit] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
private void sumCount(int[] buckets) {
|
||||
for (int i = 1; i < buckets.length; ++i) {
|
||||
buckets[i] += buckets[i - 1];
|
||||
}
|
||||
}
|
||||
|
||||
private void sort(int[] buckets, int[] results, int n) {
|
||||
for (int i = array.length - 1; i >= 0; --i) {
|
||||
int digit = (array[i] / n) % 10;
|
||||
int pos = buckets[digit] - 1;
|
||||
results[pos] = array[i];
|
||||
buckets[digit] -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
26
java-lab/BankersQueue/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
|
||||
#out
|
||||
out
|
||||
28
java-lab/BankersQueue/Bankers.iml
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<?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$/Test" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="module-library" scope="TEST">
|
||||
<library name="JUnit5.4">
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter/5.4.2/junit-jupiter-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-api/5.4.2/junit-jupiter-api-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/apiguardian/apiguardian-api/1.0.0/apiguardian-api-1.0.0.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/opentest4j/opentest4j/1.1.1/opentest4j-1.1.1.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-commons/1.4.2/junit-platform-commons-1.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-params/5.4.2/junit-jupiter-params-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-engine/5.4.2/junit-jupiter-engine-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-engine/1.4.2/junit-platform-engine-1.4.2.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</orderEntry>
|
||||
</component>
|
||||
</module>
|
||||
674
java-lab/BankersQueue/LICENSE
Normal file
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
3
java-lab/BankersQueue/README.md
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# BankersQueue
|
||||
## Requisites
|
||||
Import [**Jfreechart**](http://repo1.maven.org/maven2/org/jfree/jfreechart/1.5.0/jfreechart-1.5.0.jar) library to run the chart builder class.
|
||||
51
java-lab/BankersQueue/Test/BankersQueueTest.java
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BankersQueueTest {
|
||||
|
||||
@Test
|
||||
void test_add_and_remove(){
|
||||
BankersQueue<Integer> bq = new BankersQueue<>();
|
||||
assertTrue(bq.isEmpty());
|
||||
assertEquals(bq.size(), 0);
|
||||
bq.add(3);
|
||||
bq.add(4);
|
||||
bq.add(43);
|
||||
assertEquals(bq.size(), 3);
|
||||
bq.remove();
|
||||
assertEquals(bq.size(), 2);
|
||||
assertFalse(bq.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_element(){
|
||||
BankersQueue<Integer> bq = new BankersQueue<>();
|
||||
bq.add(3);
|
||||
bq.add(4);
|
||||
bq.add(6);
|
||||
assertEquals(bq.element(), 3);
|
||||
bq.remove();
|
||||
assertEquals(bq.element(), 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_iterator(){
|
||||
BankersQueue<Integer> bq = new BankersQueue<>();
|
||||
bq.add(3);
|
||||
bq.add(4);
|
||||
bq.element();
|
||||
bq.add(54);
|
||||
|
||||
Iterator<Integer> it = bq.iterator();
|
||||
assertEquals(it.next(), 3);
|
||||
assertTrue(it.hasNext());
|
||||
assertEquals(it.next(), 4);
|
||||
assertTrue(it.hasNext());
|
||||
assertEquals(it.next(), 54);
|
||||
assertFalse(it.hasNext());
|
||||
}
|
||||
|
||||
}
|
||||
26
java-lab/BankersQueue/src/BankClient.java
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
public class BankClient {
|
||||
private int arrivalTime;
|
||||
private int exitTime;
|
||||
|
||||
public BankClient(int arrivalTime, int exitTime) {
|
||||
this.arrivalTime = arrivalTime;
|
||||
this.exitTime = exitTime;
|
||||
}
|
||||
|
||||
|
||||
public int getExitTime() {
|
||||
return exitTime;
|
||||
}
|
||||
|
||||
public void setExitTime(int exitTime) {
|
||||
this.exitTime = exitTime;
|
||||
}
|
||||
|
||||
public int getArrivalTime() {
|
||||
return arrivalTime;
|
||||
}
|
||||
|
||||
public void setArrivalTime(int arrivalTime) {
|
||||
this.arrivalTime = arrivalTime;
|
||||
}
|
||||
}
|
||||
54
java-lab/BankersQueue/src/BankSimulator.java
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
public class BankSimulator {
|
||||
private BankersQueue<BankClient> bank = new BankersQueue<>();
|
||||
private static final int numMaximumClients = 100;
|
||||
private static final int clientTime = 15;
|
||||
private static final int serviceTime = 120;
|
||||
private static final int numMaxBankers = 10;
|
||||
private float mean = 0;
|
||||
private static float[] meanDataSet = new float[numMaxBankers];
|
||||
|
||||
void run() {
|
||||
for (int numBankers = 1; numBankers <= numMaxBankers; ++numBankers) {
|
||||
simulation(numBankers);
|
||||
meanDataSet[numBankers - 1] = mean;
|
||||
System.out.println(String.format("Simulació amb %d caixers: %.1f", numBankers, mean));
|
||||
mean = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void simulation(int numBankers) {
|
||||
for (int numCurrentClients = 0, time = 0; numCurrentClients < numMaximumClients; numCurrentClients++, time += clientTime) {
|
||||
int exitTime = checkPreviousClients(numCurrentClients, time, numBankers);
|
||||
bank.add(new BankClient(time, exitTime));
|
||||
mean += exitTime - time;
|
||||
}
|
||||
removeRemainingClients();
|
||||
mean = mean / numMaximumClients;
|
||||
}
|
||||
|
||||
private int checkPreviousClients(int numCurrentClients, int time, int numBankers) {
|
||||
if (numCurrentClients < numBankers)
|
||||
return time + serviceTime;
|
||||
else {
|
||||
BankClient firstClientOnQueue = bank.element();
|
||||
bank.remove();
|
||||
return (time >= firstClientOnQueue.getExitTime()) ? time + serviceTime : firstClientOnQueue.getExitTime() + serviceTime;
|
||||
}
|
||||
}
|
||||
|
||||
private void removeRemainingClients() {
|
||||
while (!bank.isEmpty()) {
|
||||
bank.remove();
|
||||
}
|
||||
}
|
||||
|
||||
public float getMean(int i) {
|
||||
return meanDataSet[i];
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
BankSimulator main = new BankSimulator();
|
||||
main.run();
|
||||
}
|
||||
}
|
||||
90
java-lab/BankersQueue/src/BankersQueue.java
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import java.util.*;
|
||||
|
||||
public class BankersQueue<E> implements Queue<E>, Iterable<E> {
|
||||
private ArrayList<E> front;
|
||||
private ArrayList<E> back;
|
||||
private int modCount = 0;
|
||||
|
||||
public BankersQueue() {
|
||||
front = new ArrayList<>();
|
||||
back = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(E e) {
|
||||
back.add(e);
|
||||
++modCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
checkIfEmpty();
|
||||
front.remove(front.size() - 1);
|
||||
++modCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public E element() {
|
||||
checkIfEmpty();
|
||||
return front.get(front.size() - 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return front.isEmpty() && back.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return front.size() + back.size();
|
||||
}
|
||||
|
||||
private void checkIfEmpty(){
|
||||
if(isEmpty())
|
||||
throw new NoSuchElementException();
|
||||
if (front.isEmpty())
|
||||
backToFront();
|
||||
}
|
||||
|
||||
private void backToFront() {
|
||||
ListIterator<E> it = back.listIterator(back.size());
|
||||
while (it.hasPrevious()) {
|
||||
front.add(it.previous());
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Iterator<E> iterator() {
|
||||
return new BankersIterator();
|
||||
}
|
||||
|
||||
private class BankersIterator implements Iterator<E>{
|
||||
private int expectedModCount = modCount;
|
||||
ListIterator<E> frontIt = front.listIterator(front.size());
|
||||
ListIterator<E> backIt = back.listIterator();
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return frontIt.hasPrevious() || backIt.hasNext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E next() {
|
||||
if(expectedModCount != modCount)
|
||||
throw new ConcurrentModificationException();
|
||||
if(frontIt.hasPrevious())
|
||||
return frontIt.previous();
|
||||
else if(backIt.hasNext())
|
||||
return backIt.next();
|
||||
else
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
66
java-lab/BankersQueue/src/ChartBuilder.java
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import org.jfree.chart.ChartFactory;
|
||||
import org.jfree.chart.JFreeChart;
|
||||
import org.jfree.chart.plot.PlotOrientation;
|
||||
import org.jfree.data.category.CategoryDataset;
|
||||
import org.jfree.data.category.DefaultCategoryDataset;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.swing.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ChartBuilder extends JFrame {
|
||||
private BankSimulator bank = new BankSimulator();
|
||||
|
||||
private ChartBuilder() {
|
||||
builder();
|
||||
}
|
||||
|
||||
private void builder() {
|
||||
CategoryDataset dataset = createDataset();
|
||||
JFreeChart chart = createChart(dataset);
|
||||
BufferedImage image = chart.createBufferedImage(1200, 700);
|
||||
buildImage(image);
|
||||
}
|
||||
|
||||
private JFreeChart createChart(CategoryDataset dataset) {
|
||||
return ChartFactory.createBarChart(
|
||||
"BankersQueue",
|
||||
"Num Bankers",
|
||||
"Minutes",
|
||||
dataset,
|
||||
PlotOrientation.VERTICAL,
|
||||
false, true, false);
|
||||
}
|
||||
|
||||
private CategoryDataset createDataset() {
|
||||
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
|
||||
bank.run();
|
||||
dataset.setValue(bank.getMean(0) / 60, "Minutes", "1 banker");
|
||||
dataset.setValue(bank.getMean(1) / 60, "Minutes", "2 bankers");
|
||||
dataset.setValue(bank.getMean(2) / 60, "Minutes", "3 bankers");
|
||||
dataset.setValue(bank.getMean(3) / 60, "Minutes", "4 bankers");
|
||||
dataset.setValue(bank.getMean(4) / 60, "Minutes", "5 bankers");
|
||||
dataset.setValue(bank.getMean(5) / 60, "Minutes", "6 bankers");
|
||||
dataset.setValue(bank.getMean(6) / 60, "Minutes", "7 bankers");
|
||||
dataset.setValue(bank.getMean(7) / 60, "Minutes", "8 bankers");
|
||||
dataset.setValue(bank.getMean(8) / 60, "Minutes", "9 bankers");
|
||||
dataset.setValue(bank.getMean(9) / 60, "Minutes", "10 bankers");
|
||||
return dataset;
|
||||
}
|
||||
|
||||
private void buildImage(BufferedImage image) {
|
||||
try {
|
||||
ImageIO.write(image, "png", new File("queue.png"));
|
||||
} catch (IOException exc) {
|
||||
System.out.println("Error creating image.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SwingUtilities.invokeLater(() -> {
|
||||
ChartBuilder ex = new ChartBuilder();
|
||||
});
|
||||
}
|
||||
}
|
||||
7
java-lab/BankersQueue/src/Queue.java
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
public interface Queue<E> {
|
||||
void add(E e);
|
||||
void remove();
|
||||
E element();
|
||||
boolean isEmpty();
|
||||
int size();
|
||||
}
|
||||
23
java-lab/HeapQueue/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
674
java-lab/HeapQueue/LICENSE
Normal file
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
1
java-lab/HeapQueue/README.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
# HeapQueue
|
||||
44
java-lab/HeapQueue/Test/HeapQueueTest.java
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class HeapQueueTest {
|
||||
private HeapQueue<String, Integer> heapQueue = new HeapQueue<>();
|
||||
|
||||
@Test
|
||||
void test_add_remove(){
|
||||
heapQueue = new HeapQueue<>();
|
||||
heapQueue.add("Victor", 2);
|
||||
heapQueue.add("Jordi", 6);
|
||||
heapQueue.add("Manel", 6);
|
||||
heapQueue.add("Fran", 10);
|
||||
heapQueue.add("Albert", 13);
|
||||
heapQueue.add("Pedro", null);
|
||||
test_add();
|
||||
test_remove();
|
||||
}
|
||||
|
||||
void test_add(){
|
||||
assertFalse(heapQueue.hasLeft(5) || heapQueue.hasRight(5));
|
||||
assertTrue(heapQueue.hasLeft(1) && heapQueue.hasRight(1));
|
||||
assertTrue(heapQueue.hasLeft(2) && !heapQueue.hasRight(2));
|
||||
assertTrue(heapQueue.hasParent(1));
|
||||
assertTrue(heapQueue.hasParent(3));
|
||||
}
|
||||
|
||||
void test_remove(){
|
||||
assertEquals(heapQueue.remove(), "Albert");
|
||||
assertEquals(heapQueue.remove(), "Fran");
|
||||
assertEquals(heapQueue.remove(), "Jordi");
|
||||
assertEquals(heapQueue.remove(), "Manel");
|
||||
assertEquals(heapQueue.remove(), "Victor");
|
||||
assertEquals(heapQueue.remove(), "Pedro");
|
||||
try{
|
||||
heapQueue.remove();
|
||||
}catch (NoSuchElementException e){
|
||||
assertEquals(e.getMessage(), "Empty queue!");
|
||||
}
|
||||
}
|
||||
}
|
||||
159
java-lab/HeapQueue/src/HeapQueue.java
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* This class represents a queue based on a heap structure.
|
||||
* @param <V> The value we want to store into the heapQueue its type can be anything
|
||||
* @param <P> The value priority whose type has to be comparable
|
||||
*/
|
||||
public class HeapQueue<V, P extends Comparable<? super P>> implements PriorityQueue<V, P> {
|
||||
|
||||
private final ArrayList<TSPair<V, P>> pairs = new ArrayList<>();
|
||||
private long nextTimeStamp = 0L;
|
||||
|
||||
/**
|
||||
* Adds a value with his priority into the queue.
|
||||
* @param value The value that TSPair will store
|
||||
* @param priority The value priority
|
||||
*/
|
||||
@Override
|
||||
public void add(V value, P priority) {
|
||||
TSPair<V, P> pair = new TSPair<>(value, priority, nextTimeStamp);
|
||||
pairs.add(pair);
|
||||
toMaxHeapFromBottom();
|
||||
nextTimeStamp += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the value with the highest priority
|
||||
* @return the value removed.
|
||||
*/
|
||||
@Override
|
||||
public V remove() {
|
||||
V value = element();
|
||||
Collections.swap(pairs, 0, size() - 1);
|
||||
pairs.remove(size() - 1);
|
||||
toMaxHeapFromTop();
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value with the highest priority
|
||||
* @return the value with the highest priority
|
||||
*/
|
||||
@Override
|
||||
public V element() {
|
||||
if (size() == 0)
|
||||
throw new NoSuchElementException("Empty queue!");
|
||||
return pairs.get(0).value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the heapQueue size.
|
||||
* @return the heapQueue size
|
||||
*/
|
||||
@Override
|
||||
public int size() {
|
||||
return pairs.size();
|
||||
}
|
||||
|
||||
|
||||
/** ------------ AUXILIARY METHODS ------------- */
|
||||
|
||||
private void toMaxHeapFromBottom() {
|
||||
int lastPairIndex = size() - 1;
|
||||
toMaxHeapFromBottom(lastPairIndex);
|
||||
}
|
||||
|
||||
private void toMaxHeapFromBottom(int index) {
|
||||
if (hasParent(index)) {
|
||||
TSPair<V, P> parent = pairs.get(parent(index));
|
||||
TSPair<V, P> child = pairs.get(index);
|
||||
if (child.compareTo(parent) > 0) {
|
||||
Collections.swap(pairs, index, parent(index));
|
||||
toMaxHeapFromBottom(parent(index));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void toMaxHeapFromTop() {
|
||||
int parentIndex = 0;
|
||||
toMaxHeapFromTop(parentIndex);
|
||||
}
|
||||
|
||||
private void toMaxHeapFromTop(int index) {
|
||||
int left = left(index);
|
||||
int right = right(index);
|
||||
if (hasLeft(index) && hasRight(index)) {
|
||||
int maxPairIndex = (pairs.get(left).compareTo(pairs.get(right)) > 0) ? left : right;
|
||||
checkMaxPair(maxPairIndex, index);
|
||||
} else if (hasLeft(index)) {
|
||||
checkMaxPair(left, index);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkMaxPair(int child, int parent) {
|
||||
if (pairs.get(child).compareTo(pairs.get(parent)) > 0) {
|
||||
Collections.swap(pairs, child, parent);
|
||||
toMaxHeapFromTop(child);
|
||||
}
|
||||
}
|
||||
|
||||
boolean hasParent(int index) {
|
||||
return index > 0;
|
||||
}
|
||||
|
||||
boolean hasLeft(int index) {
|
||||
return isValid(left(index));
|
||||
}
|
||||
|
||||
boolean hasRight(int index) {
|
||||
return isValid(right(index));
|
||||
}
|
||||
|
||||
private static int parent(int index) {
|
||||
if (index % 2 != 0)
|
||||
return (index + 1) / 2 - 1;
|
||||
else
|
||||
return index / 2 - 1;
|
||||
}
|
||||
|
||||
private static int left(int index) {
|
||||
return 2 * (index + 1) - 1;
|
||||
}
|
||||
|
||||
private static int right(int index) {
|
||||
return 2 * (index + 1);
|
||||
}
|
||||
|
||||
private boolean isValid(int index) {
|
||||
return 0 <= index && index < size();
|
||||
}
|
||||
|
||||
private static class TSPair<V, P extends Comparable<? super P>> implements Comparable<TSPair<V, P>> {
|
||||
private final V value;
|
||||
private final P priority;
|
||||
private final long timeStamp;
|
||||
|
||||
TSPair(V value, P priority, long timeStamp) {
|
||||
this.value = value;
|
||||
this.priority = priority;
|
||||
this.timeStamp = timeStamp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(TSPair<V, P> tsPair) {
|
||||
if (tsPair.priority == null && this.priority == null)
|
||||
return 0;
|
||||
else if (tsPair.priority == null)
|
||||
return 1;
|
||||
else if (this.priority == null)
|
||||
return -1;
|
||||
else
|
||||
return priority.compareTo(tsPair.priority) > 0 ? 1
|
||||
: priority.compareTo((tsPair.priority)) < 0 ? -1
|
||||
: Long.compare(tsPair.timeStamp, timeStamp);
|
||||
}
|
||||
}
|
||||
}
|
||||
6
java-lab/HeapQueue/src/PriorityQueue.java
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
public interface PriorityQueue<V, P extends Comparable<? super P>> {
|
||||
void add(V value, P priority);
|
||||
V remove();
|
||||
V element();
|
||||
int size();
|
||||
}
|
||||
23
java-lab/SENKU-GAME/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
13
java-lab/SENKU-GAME/SENKU-GAME.iml
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<?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" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" name="acm-javadoc" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
85
java-lab/SENKU-GAME/src/Board.java
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import java.util.StringTokenizer;
|
||||
|
||||
// Only a rectangle of cells. Do not know game rules.
|
||||
|
||||
public class Board {
|
||||
|
||||
private final int width;
|
||||
private final int height;
|
||||
private final Cell[][] cells;
|
||||
|
||||
public Board(int width, int height, String board) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
cells = new Cell[height][width];
|
||||
initializeCells(board);
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public boolean isForbidden(Position pos) {
|
||||
return outOfBounds(pos) ||
|
||||
cells[pos.getY()][pos.getX()].isForbidden();
|
||||
}
|
||||
|
||||
public boolean isFilled(Position pos) {
|
||||
return !outOfBounds(pos) &&
|
||||
cells[pos.getY()][pos.getX()].isFilled();
|
||||
}
|
||||
|
||||
public boolean isEmpty(Position pos) {
|
||||
return !outOfBounds(pos) &&
|
||||
cells[pos.getY()][pos.getX()].isEmpty();
|
||||
}
|
||||
|
||||
public void fillPosition(Position pos) {
|
||||
if (!isFilled(pos)) {
|
||||
cells[pos.getY()][pos.getX()] = Cell.FILLED;
|
||||
}
|
||||
}
|
||||
|
||||
public void emptyPosition(Position pos) {
|
||||
if (!isEmpty(pos)) {
|
||||
cells[pos.getY()][pos.getX()] = Cell.EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int y = 0; y < height; ++y) {
|
||||
for (int x = 0; x < width; ++x) {
|
||||
sb.append(cells[y][x].toString());
|
||||
}
|
||||
if (y != height - 1) {
|
||||
sb.append("\n");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void initializeCells(String board) {
|
||||
StringTokenizer boardLine = new StringTokenizer(board, "\n");
|
||||
for (int row = 0; boardLine.hasMoreTokens() && row < cells.length; ++row) {
|
||||
addCells(boardLine.nextToken(), row);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCells(String token, int row) {
|
||||
for (int col = 0; col < token.length() && col < cells[row].length; ++col) {
|
||||
char cellType = token.charAt(col);
|
||||
cells[row][col] = Cell.fromChar(cellType);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean outOfBounds(Position pos) {
|
||||
return pos.getX() < 0 || pos.getX() >= width ||
|
||||
pos.getY() < 0 || pos.getY() >= height;
|
||||
}
|
||||
}
|
||||
40
java-lab/SENKU-GAME/src/Cell.java
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
public class Cell {
|
||||
|
||||
private static final char C_FORBIDDEN = '#';
|
||||
private static final char C_FILLED = 'o';
|
||||
private static final char C_EMPTY = '·';
|
||||
|
||||
public static final Cell FORBIDDEN = new Cell(C_FORBIDDEN);
|
||||
public static final Cell FILLED = new Cell(C_FILLED);
|
||||
public static final Cell EMPTY = new Cell(C_EMPTY);
|
||||
|
||||
private final char status;
|
||||
|
||||
private Cell(char status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public static Cell fromChar(char status) {
|
||||
if(status == C_EMPTY || status == C_FILLED || status == C_FORBIDDEN){
|
||||
return new Cell(status);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isForbidden(){
|
||||
return status == C_FORBIDDEN;
|
||||
}
|
||||
|
||||
public boolean isFilled() {
|
||||
return status == C_FILLED;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return status == C_EMPTY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(status);
|
||||
}
|
||||
}
|
||||
27
java-lab/SENKU-GAME/src/Direction.java
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
public class Direction {
|
||||
|
||||
public static final Direction UP = new Direction(0, -1);
|
||||
public static final Direction RIGHT = new Direction(1, 0);
|
||||
public static final Direction DOWN = new Direction(0, 1);
|
||||
public static final Direction LEFT = new Direction(-1, 0);
|
||||
|
||||
public static final Direction[] ALL = new Direction[]{UP, RIGHT, DOWN, LEFT};
|
||||
|
||||
private final int dx;
|
||||
private final int dy;
|
||||
|
||||
private Direction(int dx, int dy) {
|
||||
this.dx = dx;
|
||||
this.dy = dy;
|
||||
}
|
||||
|
||||
public Position apply(Position from) {
|
||||
return new Position(from.getX() + dx,
|
||||
from.getY() + dy);
|
||||
}
|
||||
|
||||
public Position apply2Times(Position from) {
|
||||
return new Position(from.getX() + dx * 2,
|
||||
from.getY() + dy * 2);
|
||||
}
|
||||
}
|
||||
151
java-lab/SENKU-GAME/src/Display.java
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import acm.graphics.*;
|
||||
|
||||
import java.awt.*;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
public class Display {
|
||||
|
||||
private final String board;
|
||||
private final GCanvas gCanvas;
|
||||
private final Geometry geometry;
|
||||
|
||||
private GObject highlighted;
|
||||
private GObject selected;
|
||||
|
||||
public Display(Geometry geometry, String board, GCanvas gCanvas) {
|
||||
this.board = board;
|
||||
this.gCanvas = gCanvas;
|
||||
this.geometry = geometry;
|
||||
}
|
||||
|
||||
public void initializeDisplay() {
|
||||
gCanvas.setBackground(Palette.BACKGROUND);
|
||||
// We assume the string corresponds to a valid map of given dimensions
|
||||
StringTokenizer st = new StringTokenizer(board, "\n");
|
||||
for (int y = 0; y < geometry.getRows(); y++) {
|
||||
initializeRow(y, st.nextToken());
|
||||
}
|
||||
}
|
||||
|
||||
private void initializeRow(int y, String row) {
|
||||
for (int x = 0; x < geometry.getColumns(); x++) {
|
||||
initializePosition(row.charAt(x), new Position(x, y));
|
||||
}
|
||||
}
|
||||
|
||||
private void initializePosition(char status, Position pos) {
|
||||
if (status == 'o') {
|
||||
paintFilled(pos);
|
||||
} else if (status == '·') {
|
||||
paintEmpty(pos);
|
||||
}
|
||||
}
|
||||
|
||||
private void paintEmpty(Position pos) {
|
||||
GOval oval = createOval(pos);
|
||||
oval.setColor(Palette.EMPTY);
|
||||
gCanvas.add(oval);
|
||||
}
|
||||
|
||||
private void paintFilled(Position pos) {
|
||||
GOval oval = createOval(pos);
|
||||
oval.setColor(Palette.FILLED);
|
||||
gCanvas.add(oval);
|
||||
}
|
||||
|
||||
private GOval createOval(Position pos) {
|
||||
GDimension dimension = geometry.tokenDimension();
|
||||
GPoint topLeft = geometry.tokenTopLeft(pos.getX(), pos.getY());
|
||||
GOval oval = createOval(topLeft, dimension);
|
||||
oval.setFilled(true);
|
||||
return oval;
|
||||
}
|
||||
|
||||
private GOval createOval(GPoint topLeft, GDimension dimension) {
|
||||
return new GOval(
|
||||
topLeft.getX(),
|
||||
topLeft.getY(),
|
||||
dimension.getWidth(),
|
||||
dimension.getHeight());
|
||||
}
|
||||
|
||||
public void highlight(double x, double y) {
|
||||
GObject gObject = gCanvas.getElementAt(x, y);
|
||||
if (ignoreHighlight(gObject)) return;
|
||||
if (gObject != highlighted) clearHighlight();
|
||||
highlighted = gObject;
|
||||
Color highlightColor = Palette.highlightColor(gObject.getColor());
|
||||
highlighted.setColor(highlightColor);
|
||||
}
|
||||
|
||||
private boolean ignoreHighlight(GObject gObject) {
|
||||
return !(gObject instanceof GOval) || gObject == highlighted;
|
||||
}
|
||||
|
||||
public void clearHighlight() {
|
||||
if (highlighted == null) return;
|
||||
Color normalColor = Palette.normalColor(highlighted.getColor());
|
||||
highlighted.setColor(normalColor);
|
||||
highlighted = null;
|
||||
}
|
||||
|
||||
public void select(double x, double y) {
|
||||
GObject gObject = gCanvas.getElementAt(x, y);
|
||||
if (ignoreSelection(gObject)) return;
|
||||
selected = gObject;
|
||||
highlighted = null;
|
||||
selected.setColor(Palette.SELECTED_FILLED);
|
||||
}
|
||||
|
||||
private boolean ignoreSelection(GObject gObject) {
|
||||
return !(gObject instanceof GOval);
|
||||
}
|
||||
|
||||
public void clearSelect() {
|
||||
if (selected == null) return;
|
||||
selected.setColor(Palette.FILLED);
|
||||
selected = null;
|
||||
}
|
||||
|
||||
public void setEmpty(Position position) {
|
||||
setColor(position, Palette.EMPTY);
|
||||
}
|
||||
|
||||
public void setFilled(Position position) {
|
||||
setColor(position, Palette.FILLED);
|
||||
}
|
||||
|
||||
private void setColor(Position position, Color color) {
|
||||
GPoint center = geometry.centerAt(position.getX(), position.getY());
|
||||
GObject gObject = gCanvas.getElementAt(center);
|
||||
if (gObject == selected) selected = null;
|
||||
if (gObject == highlighted) highlighted = null;
|
||||
gObject.setColor(color);
|
||||
}
|
||||
|
||||
public static String getStatusMessage(int validMoves, int movesCounter) {
|
||||
return validMovesMessage(validMoves) + " / " + movesCounterMessage(movesCounter);
|
||||
}
|
||||
|
||||
private static String validMovesMessage(int validMoves) {
|
||||
if (validMoves == 0) {
|
||||
return "No hi ha cap moviment vàlid. GAME OVER.";
|
||||
} else if (validMoves == 1) {
|
||||
return "Hi ha un moviment vàlid";
|
||||
} else {
|
||||
return String.format("Hi ha %d moviments vàlids", validMoves);
|
||||
}
|
||||
}
|
||||
|
||||
private static String movesCounterMessage(int movesCounter) {
|
||||
if (movesCounter == 0) {
|
||||
return "No has fet cap moviment";
|
||||
} else if (movesCounter == 1) {
|
||||
return "Has fet un moviment";
|
||||
} else {
|
||||
return String.format("Has fet %d moviments", movesCounter);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
88
java-lab/SENKU-GAME/src/Game.java
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
// It knows the game rules
|
||||
|
||||
public class Game {
|
||||
|
||||
private final Board board;
|
||||
|
||||
public Game(Board board) {
|
||||
this.board = board;
|
||||
}
|
||||
|
||||
public boolean isValidFrom(Position from) {
|
||||
if (board.isFilled(from)) {
|
||||
boolean[] possibleMoves = possibleDirectionsTo(from); // To Up, Down, Right, Left
|
||||
for (int i = 0; i < possibleMoves.length; ++i) {
|
||||
if (possibleMoves[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Assumes validFrom is a valid starting position
|
||||
public boolean isValidTo(Position validFrom, Position to) {
|
||||
if (board.isEmpty(to)) {
|
||||
return validFrom.colinear(to) && validFrom.distance(to) == 2;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Assumes both positions are valid
|
||||
public Position move(Position validFrom, Position validTo) {
|
||||
board.emptyPosition(validFrom);
|
||||
board.fillPosition(validTo);
|
||||
board.emptyPosition(validFrom.middle(validTo));
|
||||
return validFrom.middle(validTo);
|
||||
}
|
||||
|
||||
public boolean hasValidMovesFrom() {
|
||||
for (int i = 0; i < board.getHeight(); ++i) {
|
||||
for (int j = 0; j < board.getWidth(); ++j) {
|
||||
if (isValidFrom(new Position(j, i))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int countValidMovesFrom() {
|
||||
int validMovesFrom = 0;
|
||||
for (int i = 0; i < board.getHeight(); ++i) {
|
||||
for (int j = 0; j < board.getWidth(); ++j) {
|
||||
if (isValidFrom(new Position(j, i))) {
|
||||
validMovesFrom += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return validMovesFrom;
|
||||
}
|
||||
|
||||
// Assumes validFrom is a valid starting position
|
||||
public int countValidMovesTo(Position validFrom) {
|
||||
int validMovesTo = 0;
|
||||
for (int i = 0; i < Direction.ALL.length; ++i) {
|
||||
Position validTo = Direction.ALL[i].apply2Times(validFrom);
|
||||
if (isValidTo(validFrom, validTo)) {
|
||||
validMovesTo += 1;
|
||||
}
|
||||
}
|
||||
return validMovesTo;
|
||||
}
|
||||
|
||||
private boolean[] possibleDirectionsTo(Position pos) {
|
||||
boolean[] directions = new boolean[Direction.ALL.length];
|
||||
for (int i = 0; i < Direction.ALL.length; i++) {
|
||||
setValidDirections(directions, i, pos);
|
||||
}
|
||||
return directions;
|
||||
}
|
||||
|
||||
private void setValidDirections(boolean[] directions, int index, Position pos) {
|
||||
Position posToKill = Direction.ALL[index].apply(pos);
|
||||
Position posToJump = Direction.ALL[index].apply2Times(pos);
|
||||
directions[index] = board.isFilled(posToKill) &&
|
||||
board.isEmpty(posToJump);
|
||||
}
|
||||
}
|
||||
87
java-lab/SENKU-GAME/src/Geometry.java
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import acm.graphics.GDimension;
|
||||
import acm.graphics.GPoint;
|
||||
|
||||
public class Geometry {
|
||||
|
||||
private final int windowWidth;
|
||||
private final int windowHeight;
|
||||
private final int numCols;
|
||||
private final int numRows;
|
||||
private final double boardPadding;
|
||||
private final double cellPadding;
|
||||
|
||||
public Geometry(int windowWidth, int windowHeight, int numCols, int numRows, double boardPadding, double cellPadding) {
|
||||
this.windowWidth = windowWidth;
|
||||
this.windowHeight = windowHeight;
|
||||
this.numCols = numCols;
|
||||
this.numRows = numRows;
|
||||
this.boardPadding = boardPadding;
|
||||
this.cellPadding = cellPadding;
|
||||
}
|
||||
|
||||
public int getRows() {
|
||||
return numRows;
|
||||
}
|
||||
|
||||
public int getColumns() {
|
||||
return numCols;
|
||||
}
|
||||
|
||||
public GDimension boardDimension() {
|
||||
return new GDimension(
|
||||
windowWidth * (1 - boardPadding * 2),
|
||||
windowHeight * (1 - boardPadding * 2));
|
||||
}
|
||||
|
||||
public GPoint boardTopLeft() {
|
||||
return new GPoint(
|
||||
windowWidth * boardPadding,
|
||||
windowHeight * boardPadding);
|
||||
}
|
||||
|
||||
public GDimension cellDimension() {
|
||||
GDimension boardDimension = boardDimension();
|
||||
return new GDimension(
|
||||
boardDimension.getWidth() / numCols,
|
||||
boardDimension.getHeight() / numRows);
|
||||
}
|
||||
|
||||
public GPoint cellTopLeft(int x, int y) {
|
||||
GPoint boardTopLeft = boardTopLeft();
|
||||
GDimension cellDimension = cellDimension();
|
||||
return new GPoint(
|
||||
boardTopLeft.getX() + cellDimension.getWidth() * x,
|
||||
boardTopLeft.getY() + cellDimension.getHeight() * y);
|
||||
}
|
||||
|
||||
public GDimension tokenDimension() {
|
||||
GDimension cellDimension = cellDimension();
|
||||
return new GDimension(
|
||||
cellDimension.getWidth() * (1 - cellPadding * 2),
|
||||
cellDimension.getHeight() * (1 - cellPadding * 2));
|
||||
}
|
||||
|
||||
public GPoint tokenTopLeft(int x, int y) {
|
||||
GPoint cellTopLeft = cellTopLeft(x, y);
|
||||
GDimension cellDimension = cellDimension();
|
||||
return new GPoint(
|
||||
cellTopLeft.getX() + cellDimension.getWidth() * cellPadding,
|
||||
cellTopLeft.getY() + cellDimension.getHeight() * cellPadding);
|
||||
}
|
||||
|
||||
public GPoint centerAt(int x, int y) {
|
||||
GDimension tokenDimension = tokenDimension();
|
||||
GPoint tokenTopLeft = tokenTopLeft(x, y);
|
||||
return new GPoint(
|
||||
tokenTopLeft.getX() + tokenDimension.getWidth() / 2,
|
||||
tokenTopLeft.getY() + tokenDimension.getHeight() / 2);
|
||||
}
|
||||
|
||||
public Position xyToCell(double x, double y) {
|
||||
GPoint boardTopLeft = boardTopLeft();
|
||||
GDimension cellDimension = cellDimension();
|
||||
return new Position(
|
||||
(int) ((x - boardTopLeft.getX()) / cellDimension.getWidth()),
|
||||
(int) ((y - boardTopLeft.getY()) / cellDimension.getHeight()));
|
||||
}
|
||||
}
|
||||
25
java-lab/SENKU-GAME/src/Palette.java
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import java.awt.*;
|
||||
|
||||
public class Palette {
|
||||
|
||||
public static final Color BACKGROUND = new Color(155, 78, 44); // 100
|
||||
|
||||
public static final Color EMPTY = new Color(135, 68, 43); // 120
|
||||
public static final Color HIGHLIGHT_EMPTY = new Color(115, 55, 43); // 140
|
||||
|
||||
public static final Color FILLED = new Color(120, 138, 155); // 100
|
||||
public static final Color HIGHLIGHT_FILLED = new Color(100, 118, 135); // 120
|
||||
public static final Color SELECTED_FILLED = new Color(80, 98, 115); // 140
|
||||
|
||||
private static boolean isFilled(Color color) {
|
||||
return color == FILLED || color == HIGHLIGHT_FILLED || color == SELECTED_FILLED;
|
||||
}
|
||||
|
||||
public static Color highlightColor(Color color) {
|
||||
return isFilled(color) ? HIGHLIGHT_FILLED : HIGHLIGHT_EMPTY;
|
||||
}
|
||||
|
||||
public static Color normalColor(Color color) {
|
||||
return isFilled(color) ? FILLED : EMPTY;
|
||||
}
|
||||
}
|
||||
53
java-lab/SENKU-GAME/src/Position.java
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
public class Position {
|
||||
|
||||
private final int x;
|
||||
private final int y;
|
||||
|
||||
public Position(int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public boolean colinear(Position other) {
|
||||
return x == other.x ||
|
||||
y == other.y;
|
||||
}
|
||||
|
||||
public int distance(Position other) {
|
||||
return Math.abs(x - other.x) +
|
||||
Math.abs(y - other.y);
|
||||
}
|
||||
|
||||
public Position middle(Position other) {
|
||||
|
||||
return new Position((x + other.x) / 2,
|
||||
(y + other.y) / 2);
|
||||
}
|
||||
|
||||
// Needed for testing
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Position position = (Position) o;
|
||||
return x == position.x &&
|
||||
y == position.y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Position{" +
|
||||
"x=" + x +
|
||||
", y=" + y +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
125
java-lab/SENKU-GAME/src/Senku.java
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import acm.program.GraphicsProgram;
|
||||
|
||||
import java.awt.event.MouseEvent;
|
||||
|
||||
public class Senku extends GraphicsProgram {
|
||||
|
||||
public static final int APPLICATION_WIDTH = 600;
|
||||
public static final int APPLICATION_HEIGHT = 600;
|
||||
|
||||
private static final double OUTER = 0.05;
|
||||
private static final double INNER = 0.03;
|
||||
|
||||
private static final int ROWS = 7;
|
||||
private static final int COLUMNS = 7;
|
||||
private static final String BOARD = "" +
|
||||
"##ooo##\n" +
|
||||
"#ooooo#\n" +
|
||||
"ooooooo\n" +
|
||||
"ooo·ooo\n" +
|
||||
"ooooooo\n" +
|
||||
"#ooooo#\n" +
|
||||
"##ooo##";
|
||||
|
||||
private Geometry geometry;
|
||||
private Display display;
|
||||
private Board board;
|
||||
private Game game;
|
||||
|
||||
private Position selectedFrom;
|
||||
|
||||
private int movesCounter;
|
||||
|
||||
@Override
|
||||
public void mouseMoved(MouseEvent e) {
|
||||
double x = e.getX();
|
||||
double y = e.getY();
|
||||
if (selectedFrom == null) {
|
||||
highlightOrClearFrom(x, y);
|
||||
} else {
|
||||
highlightOrClearTo(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
private void highlightOrClearFrom(double x, double y) {
|
||||
Position position = geometry.xyToCell(x, y);
|
||||
if (game.isValidFrom(position)) {
|
||||
display.highlight(x, y);
|
||||
} else {
|
||||
display.clearHighlight();
|
||||
}
|
||||
}
|
||||
|
||||
private void highlightOrClearTo(double x, double y) {
|
||||
Position position = geometry.xyToCell(x, y);
|
||||
if (game.isValidTo(selectedFrom, position)) {
|
||||
display.highlight(x, y);
|
||||
} else if (!position.equals(selectedFrom)) {
|
||||
display.clearHighlight();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
double x = e.getX();
|
||||
double y = e.getY();
|
||||
Position position = geometry.xyToCell(x, y);
|
||||
if (selectedFrom == null) {
|
||||
selectIfValid(x, y);
|
||||
} else if (position.equals(selectedFrom)) {
|
||||
unselect();
|
||||
} else if (game.isValidTo(selectedFrom, position)) {
|
||||
move(position);
|
||||
}
|
||||
}
|
||||
|
||||
private void selectIfValid(double x, double y) {
|
||||
Position position = geometry.xyToCell(x, y);
|
||||
if (game.isValidFrom(position)) {
|
||||
selectedFrom = position;
|
||||
display.select(x, y);
|
||||
updateTitle(game.countValidMovesTo(selectedFrom));
|
||||
}
|
||||
}
|
||||
|
||||
private void unselect() {
|
||||
selectedFrom = null;
|
||||
display.clearSelect();
|
||||
updateTitle(game.countValidMovesFrom());
|
||||
}
|
||||
|
||||
private void move(Position position) {
|
||||
Position middle = game.move(selectedFrom, position);
|
||||
display.setEmpty(selectedFrom);
|
||||
selectedFrom = null;
|
||||
display.setEmpty(middle);
|
||||
display.setFilled(position);
|
||||
movesCounter += 1;
|
||||
updateTitle(game.countValidMovesFrom());
|
||||
}
|
||||
|
||||
private void updateTitle(int validMoves) {
|
||||
setTitle(Display.getStatusMessage(validMoves, movesCounter));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
addMouseListeners();
|
||||
runGame();
|
||||
}
|
||||
|
||||
private void runGame() {
|
||||
geometry = new Geometry(APPLICATION_WIDTH, APPLICATION_HEIGHT, COLUMNS, ROWS, OUTER, INNER);
|
||||
display = new Display(geometry, BOARD, getGCanvas());
|
||||
board = new Board(COLUMNS, ROWS, BOARD);
|
||||
game = new Game(board);
|
||||
display.initializeDisplay();
|
||||
movesCounter = 0;
|
||||
updateTitle(game.countValidMovesFrom());
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new Senku().start(args);
|
||||
}
|
||||
|
||||
}
|
||||
63
java-lab/SENKU-GAME/test/BoardTest.java
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BoardTest {
|
||||
|
||||
private static final String BOARD = "" +
|
||||
"##ooo##\n" +
|
||||
"#ooooo#\n" +
|
||||
"ooooooo\n" +
|
||||
"ooo·ooo\n" +
|
||||
"ooooooo\n" +
|
||||
"#ooooo#\n" +
|
||||
"##ooo##";
|
||||
|
||||
private final Board board = new Board(7, 7, BOARD);
|
||||
|
||||
private final Position outOfBounds = new Position(4, 9);
|
||||
private final Position forbidden = new Position(0, 1);
|
||||
private final Position filled = new Position(2, 4);
|
||||
private final Position empty = new Position(3, 3);
|
||||
|
||||
@Test
|
||||
void is_forbidden() {
|
||||
assertTrue(board.isForbidden(outOfBounds));
|
||||
assertTrue(board.isForbidden(forbidden));
|
||||
assertFalse(board.isForbidden(filled));
|
||||
assertFalse(board.isForbidden(empty));
|
||||
}
|
||||
|
||||
@Test
|
||||
void is_filled() {
|
||||
assertFalse(board.isFilled(outOfBounds));
|
||||
assertFalse(board.isFilled(forbidden));
|
||||
assertTrue(board.isFilled(filled));
|
||||
assertFalse(board.isFilled(empty));
|
||||
}
|
||||
|
||||
@Test
|
||||
void is_empty() {
|
||||
assertFalse(board.isEmpty(outOfBounds));
|
||||
assertFalse(board.isEmpty(forbidden));
|
||||
assertFalse(board.isEmpty(filled));
|
||||
assertTrue(board.isEmpty(empty));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fill_position() {
|
||||
board.fillPosition(empty);
|
||||
assertTrue(board.isFilled(empty));
|
||||
}
|
||||
|
||||
@Test
|
||||
void empty_position() {
|
||||
board.emptyPosition(filled);
|
||||
assertTrue(board.isEmpty(filled));
|
||||
}
|
||||
|
||||
@Test
|
||||
void roundtrip() {
|
||||
assertEquals(BOARD, board.toString());
|
||||
}
|
||||
}
|
||||
49
java-lab/SENKU-GAME/test/CellTest.java
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CellTest {
|
||||
|
||||
@Test
|
||||
void forbidden_cell() {
|
||||
Cell forbidden = Cell.FORBIDDEN;
|
||||
assertTrue(forbidden.isForbidden());
|
||||
assertFalse(forbidden.isEmpty());
|
||||
assertFalse(forbidden.isFilled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void empty_cell() {
|
||||
Cell empty = Cell.EMPTY;
|
||||
assertTrue(empty.isEmpty());
|
||||
assertFalse(empty.isForbidden());
|
||||
assertFalse(empty.isFilled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void filled_cell() {
|
||||
Cell filled = Cell.FILLED;
|
||||
assertTrue(filled.isFilled());
|
||||
assertFalse(filled.isForbidden());
|
||||
assertFalse(filled.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cell_from_char() {
|
||||
Cell forbidden = Cell.fromChar('#');
|
||||
assertTrue(forbidden.isForbidden());
|
||||
Cell empty = Cell.fromChar('·');
|
||||
assertTrue(empty.isEmpty());
|
||||
Cell filled = Cell.fromChar('o');
|
||||
assertTrue(filled.isFilled());
|
||||
Cell invalid = Cell.fromChar('?');
|
||||
assertNull(invalid);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cell_to_string() {
|
||||
assertEquals("#", Cell.FORBIDDEN.toString());
|
||||
assertEquals("o", Cell.FILLED.toString());
|
||||
assertEquals("·", Cell.EMPTY.toString());
|
||||
}
|
||||
}
|
||||
31
java-lab/SENKU-GAME/test/DirectionTest.java
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DirectionTest {
|
||||
|
||||
@Test
|
||||
void up() {
|
||||
Position from = new Position(4, 3);
|
||||
assertEquals(new Position(4, 2), Direction.UP.apply(from));
|
||||
}
|
||||
|
||||
@Test
|
||||
void right() {
|
||||
Position from = new Position(4, 3);
|
||||
assertEquals(new Position(5, 3), Direction.RIGHT.apply(from));
|
||||
}
|
||||
|
||||
@Test
|
||||
void down() {
|
||||
Position from = new Position(4, 3);
|
||||
assertEquals(new Position(4, 4), Direction.DOWN.apply(from));
|
||||
}
|
||||
|
||||
@Test
|
||||
void left() {
|
||||
Position from = new Position(4, 3);
|
||||
assertEquals(new Position(3, 3), Direction.LEFT.apply(from));
|
||||
}
|
||||
|
||||
}
|
||||
163
java-lab/SENKU-GAME/test/GameTest.java
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class GameTest {
|
||||
|
||||
private static final String BOARD = "" +
|
||||
"##ooo##\n" +
|
||||
"#ooooo#\n" +
|
||||
"ooooooo\n" +
|
||||
"o·o·ooo\n" +
|
||||
"ooooooo\n" +
|
||||
"#o·ooo#\n" +
|
||||
"##ooo##";
|
||||
|
||||
private final Board board = new Board(7, 7, BOARD);
|
||||
private final Game game = new Game(board);
|
||||
|
||||
private final int[][] validFromXY = new int[][]{{1, 1}, {3, 1}, {2, 3}, {5, 3}, {1, 5}, {3, 5}, {4, 5}};
|
||||
private final int[] validToCount = new int[] {1, 1, 1, 1, 1, 1, 1};
|
||||
|
||||
private boolean inValidFromXY(int x, int y) {
|
||||
for (int[] xy : validFromXY) {
|
||||
if (xy[0] == x && xy[1] == y) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Test
|
||||
void valid_from() {
|
||||
for (int i = 0; i < validFromXY.length; i++) {
|
||||
int[] xy = validFromXY[i];
|
||||
Position valid = new Position(xy[0], xy[1]);
|
||||
assertTrue(game.isValidFrom(valid));
|
||||
assertEquals(validToCount[i], game.countValidMovesTo(valid));
|
||||
}
|
||||
assertEquals(validFromXY.length, game.countValidMovesFrom());
|
||||
}
|
||||
|
||||
@Test
|
||||
void not_is_valid_from() {
|
||||
for (int x = 0; x < 7; x++) {
|
||||
for (int y = 0; y < 7; y++) {
|
||||
if (!inValidFromXY(x, y)) {
|
||||
assertFalse(game.isValidFrom(new Position(x, y)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void is_valid_to() {
|
||||
assertTrue(game.isValidTo(new Position(1, 1), new Position(1, 3)));
|
||||
assertTrue(game.isValidTo(new Position(3, 1), new Position(3, 3)));
|
||||
assertTrue(game.isValidTo(new Position(2, 3), new Position(2, 5)));
|
||||
assertTrue(game.isValidTo(new Position(5, 3), new Position(3, 3)));
|
||||
assertTrue(game.isValidTo(new Position(1, 5), new Position(1, 3)));
|
||||
assertTrue(game.isValidTo(new Position(3, 5), new Position(3, 3)));
|
||||
assertTrue(game.isValidTo(new Position(4, 5), new Position(2, 5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void not_is_valid_to() {
|
||||
assertFalse(game.isValidTo(new Position(1, 1), new Position(1, -1)));
|
||||
assertFalse(game.isValidTo(new Position(1, 1), new Position(3, 1)));
|
||||
assertFalse(game.isValidTo(new Position(1, 1), new Position(1, 4)));
|
||||
assertFalse(game.isValidTo(new Position(1, 1), new Position(2, 2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void has_valid_moves() {
|
||||
assertTrue(game.hasValidMovesFrom());
|
||||
}
|
||||
|
||||
@Test
|
||||
void one_move() {
|
||||
String EXPECTED = "" +
|
||||
"##ooo##\n" +
|
||||
"#·oooo#\n" +
|
||||
"o·ooooo\n" +
|
||||
"ooo·ooo\n" +
|
||||
"ooooooo\n" +
|
||||
"#o·ooo#\n" +
|
||||
"##ooo##";
|
||||
Position middle = game.move(new Position(1, 1), new Position(1, 3));
|
||||
assertEquals(new Position(1, 2), middle);
|
||||
assertEquals(EXPECTED, board.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void two_moves() {
|
||||
String EXPECTED = "" +
|
||||
"##ooo##\n" +
|
||||
"#·oooo#\n" +
|
||||
"o·ooooo\n" +
|
||||
"o··oooo\n" +
|
||||
"ooooooo\n" +
|
||||
"#o·ooo#\n" +
|
||||
"##ooo##";
|
||||
game.move(new Position(1, 1), new Position(1, 3));
|
||||
Position middle = game.move(new Position(1, 3), new Position(3, 3));
|
||||
assertEquals(new Position(2, 3), middle);
|
||||
assertEquals(EXPECTED, board.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void three_moves() {
|
||||
String EXPECTED = "" +
|
||||
"##ooo##\n" +
|
||||
"#·oooo#\n" +
|
||||
"o·ooooo\n" +
|
||||
"o··oooo\n" +
|
||||
"ooooooo\n" +
|
||||
"#oo··o#\n" +
|
||||
"##ooo##";
|
||||
game.move(new Position(1, 1), new Position(1, 3));
|
||||
game.move(new Position(1, 3), new Position(3, 3));
|
||||
Position middle = game.move(new Position(4, 5), new Position(2, 5));
|
||||
assertEquals(new Position(3, 5), middle);
|
||||
assertEquals(EXPECTED, board.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void no_more_moves() {
|
||||
String EXPECTED = "" +
|
||||
"##··o##\n" +
|
||||
"#o····#\n" +
|
||||
"····o·o\n" +
|
||||
"··o····\n" +
|
||||
"o······\n" +
|
||||
"#····o#\n" +
|
||||
"##ooo##";
|
||||
game.move(new Position(1, 1), new Position(1, 3));
|
||||
game.move(new Position(1, 3), new Position(3, 3));
|
||||
game.move(new Position(4, 5), new Position(2, 5));
|
||||
game.move(new Position(3, 1), new Position(1, 1));
|
||||
game.move(new Position(3, 3), new Position(3, 1));
|
||||
game.move(new Position(3, 0), new Position(3, 2));
|
||||
game.move(new Position(2, 5), new Position(2, 3));
|
||||
game.move(new Position(2, 3), new Position(2, 1));
|
||||
game.move(new Position(2, 0), new Position(2, 2));
|
||||
game.move(new Position(3, 2), new Position(1, 2));
|
||||
game.move(new Position(1, 5), new Position(1, 3));
|
||||
game.move(new Position(0, 2), new Position(2, 2));
|
||||
game.move(new Position(5, 1), new Position(3, 1));
|
||||
game.move(new Position(4, 4), new Position(2, 4));
|
||||
game.move(new Position(0, 3), new Position(2, 3));
|
||||
game.move(new Position(2, 3), new Position(2, 1));
|
||||
game.move(new Position(5, 2), new Position(3, 2));
|
||||
game.move(new Position(3, 1), new Position(3, 3));
|
||||
game.move(new Position(4, 3), new Position(2, 3));
|
||||
game.move(new Position(2, 4), new Position(2, 2));
|
||||
game.move(new Position(2, 1), new Position(2, 3));
|
||||
game.move(new Position(5, 4), new Position(5, 2));
|
||||
game.move(new Position(6, 2), new Position(4, 2));
|
||||
game.move(new Position(6, 4), new Position(6, 2));
|
||||
assertEquals(EXPECTED, board.toString());
|
||||
assertFalse(game.hasValidMovesFrom());
|
||||
assertEquals(0, game.countValidMovesFrom());
|
||||
}
|
||||
}
|
||||
78
java-lab/SENKU-GAME/test/GeometryTest.java
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import acm.graphics.GDimension;
|
||||
import acm.graphics.GPoint;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class GeometryTest {
|
||||
|
||||
Geometry geometry = new Geometry(
|
||||
800,
|
||||
300,
|
||||
4,
|
||||
3,
|
||||
0.05,
|
||||
0.10);
|
||||
|
||||
@Test
|
||||
void getters() {
|
||||
assertEquals(3, geometry.getRows());
|
||||
assertEquals(4, geometry.getColumns());
|
||||
}
|
||||
|
||||
@Test
|
||||
void board_dimension() {
|
||||
assertEquals(
|
||||
new GDimension(720.0, 270.0),
|
||||
geometry.boardDimension());
|
||||
}
|
||||
|
||||
@Test
|
||||
void board_top_left() {
|
||||
assertEquals(
|
||||
new GPoint(40.0, 15.0),
|
||||
geometry.boardTopLeft());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cell_dimension() {
|
||||
assertEquals(
|
||||
new GDimension(180.0, 90.0),
|
||||
geometry.cellDimension());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cell_top_left() {
|
||||
assertEquals(
|
||||
new GPoint(400.0, 105.0),
|
||||
geometry.cellTopLeft(2, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void token_dimension() {
|
||||
assertEquals(
|
||||
new GDimension(144.0, 72.0),
|
||||
geometry.tokenDimension());
|
||||
}
|
||||
|
||||
@Test
|
||||
void token_top_left() {
|
||||
assertEquals(
|
||||
new GPoint(418.0, 114.0),
|
||||
geometry.tokenTopLeft(2, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void xy_to_cell() {
|
||||
assertEquals(
|
||||
new Position(3, 1),
|
||||
geometry.xyToCell(600.0, 110.0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void center_at() {
|
||||
assertEquals(
|
||||
new GPoint(310.0, 240.0),
|
||||
geometry.centerAt(1, 2));
|
||||
}
|
||||
}
|
||||
53
java-lab/SENKU-GAME/test/PositionTest.java
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PositionTest {
|
||||
|
||||
@Test
|
||||
void getter_and_constructor() {
|
||||
Position pos = new Position(4, 3);
|
||||
assertEquals(4, pos.getX());
|
||||
assertEquals(3, pos.getY());
|
||||
}
|
||||
|
||||
@Test
|
||||
void colinear_horizontal() {
|
||||
Position pos1 = new Position(3, 8);
|
||||
Position pos2 = new Position(6, 8);
|
||||
assertTrue(pos1.colinear(pos2));
|
||||
assertTrue(pos2.colinear(pos1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void colinear_vertical() {
|
||||
Position pos1 = new Position(6, 4);
|
||||
Position pos2 = new Position(6, 8);
|
||||
assertTrue(pos1.colinear(pos2));
|
||||
assertTrue(pos2.colinear(pos1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void not_colinear() {
|
||||
Position pos1 = new Position(3, 8);
|
||||
Position pos2 = new Position(6, 4);
|
||||
assertFalse(pos1.colinear(pos2));
|
||||
assertFalse(pos2.colinear(pos1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void distance() {
|
||||
Position pos1 = new Position(3, -2);
|
||||
Position pos2 = new Position(6, 4);
|
||||
assertEquals(9, pos1.distance(pos2));
|
||||
assertEquals(9, pos2.distance(pos1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void middle() {
|
||||
Position pos1 = new Position(3, -2);
|
||||
Position pos2 = new Position(6, 4);
|
||||
assertEquals(new Position(4, 1), pos1.middle(pos2));
|
||||
assertEquals(new Position(4, 1), pos2.middle(pos1));
|
||||
}
|
||||
}
|
||||
23
java-lab/Tree_Traversals/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
674
java-lab/Tree_Traversals/LICENSE
Normal file
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
44
java-lab/Tree_Traversals/Laboratori-5.iml
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
<?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" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="module-library" scope="TEST">
|
||||
<library name="JUnit5.4">
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter/5.4.2/junit-jupiter-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-api/5.4.2/junit-jupiter-api-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/apiguardian/apiguardian-api/1.0.0/apiguardian-api-1.0.0.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/opentest4j/opentest4j/1.1.1/opentest4j-1.1.1.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-commons/1.4.2/junit-platform-commons-1.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-params/5.4.2/junit-jupiter-params-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-engine/5.4.2/junit-jupiter-engine-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-engine/1.4.2/junit-platform-engine-1.4.2.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</orderEntry>
|
||||
<orderEntry type="module-library" scope="TEST">
|
||||
<library name="JUnit5.4">
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter/5.4.2/junit-jupiter-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-api/5.4.2/junit-jupiter-api-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/apiguardian/apiguardian-api/1.0.0/apiguardian-api-1.0.0.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/opentest4j/opentest4j/1.1.1/opentest4j-1.1.1.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-commons/1.4.2/junit-platform-commons-1.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-params/5.4.2/junit-jupiter-params-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/jupiter/junit-jupiter-engine/5.4.2/junit-jupiter-engine-5.4.2.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/junit/platform/junit-platform-engine/1.4.2/junit-platform-engine-1.4.2.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</orderEntry>
|
||||
</component>
|
||||
</module>
|
||||
BIN
java-lab/Tree_Traversals/docu/Diagram.png
Normal file
|
After Width: | Height: | Size: 39 KiB |
BIN
java-lab/Tree_Traversals/docu/Lab_5.pdf
Normal file
149
java-lab/Tree_Traversals/docu/Lab_5.tex
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
\documentclass{article}
|
||||
\usepackage[utf8]{inputenc}
|
||||
\usepackage[spanish]{babel}
|
||||
\usepackage[pdftex]{graphicx}
|
||||
\usepackage{listings}
|
||||
\usepackage{parskip}
|
||||
\usepackage{fancyhdr}
|
||||
\usepackage{amsmath}
|
||||
\usepackage{indentfirst}
|
||||
\usepackage{vmargin}
|
||||
\setmarginsrb{3 cm }{ 2.5cm }{3 cm }{2.5 cm}{1 cm}{1.5 cm}{1 cm}{1.5 cm}
|
||||
\title{Binarytree}
|
||||
\author{Martin, Francisco Manuel \\
|
||||
Martinez, Victor
|
||||
}
|
||||
|
||||
\makeatletter
|
||||
\let\thetitle\@title
|
||||
\let\theauthor\@author
|
||||
\let\thedate\@date
|
||||
\makeatother
|
||||
\pagestyle{fancy}
|
||||
\fancyhf{}
|
||||
\rhead{\theauthor}
|
||||
\lhead{\thetitle}
|
||||
\cfoot{\thepage}
|
||||
%\addto\captionspanish{
|
||||
\renewcommand*\contentsname{Índex}%}
|
||||
\setlength{\parindent}{1cm}
|
||||
|
||||
\begin{document}
|
||||
\begin{titlepage}
|
||||
\centering
|
||||
\vspace*{0.5 cm}
|
||||
|
||||
\textsc{\LARGE Universidad Politécnica de Lleida}\\[2.0 cm] % University Name
|
||||
\textsc{\large Practica 5}\\[0.5 cm] % Course Name
|
||||
\rule{\linewidth}{0.2 mm} \\[0.4 cm]
|
||||
{ \huge \bfseries \thetitle}\\
|
||||
\rule{\linewidth}{0.2 mm} \\[1.5 cm]
|
||||
|
||||
\begin{minipage}{0.4\textwidth}
|
||||
\begin{flushleft} \large
|
||||
\emph{Author:}\\
|
||||
\theauthor
|
||||
\end{flushleft}
|
||||
\end{minipage}~
|
||||
\begin{minipage}{0.4\textwidth}
|
||||
\begin{flushright} \large
|
||||
\emph{DNI:} \\
|
||||
48057095k \\
|
||||
78100640T% Your Student Number
|
||||
\end{flushright}
|
||||
\end{minipage}\\[2 cm]
|
||||
|
||||
{\large \thedate}\\[2 cm]
|
||||
|
||||
\vfill
|
||||
|
||||
\end{titlepage}
|
||||
\tableofcontents
|
||||
\pagebreak
|
||||
|
||||
|
||||
\section{Tarea 1: Implementación de los árboles binarios}
|
||||
\subsection{Constructores}
|
||||
En esta sección solo vamos a comentar un pequeño detalle sobre el tercer constructor. \newline
|
||||
Tratamos \textbf{left} y \textbf{right} de manera que, si uno de ellos es null inicializamos la instancia de Node correspondiente a null. \newline
|
||||
de esta manera,evitamos un NullPointerException en caso de intentar acceder al atributo root del árbol en cuestión.
|
||||
|
||||
\subsection{método equals}
|
||||
\subsubsection{equals de LinkedBinaryTree}
|
||||
En primer lugar, comprobamos que el objecto de tipo \textit{Object} pasado como parámetro apunte a una instancia de LinkedBinaryTree.
|
||||
Si es así, realizamos un cast y ejecutamos el método estático \textit{recEquals} de la clase Node que comprobará recursivamente si los \textit{roots} de los árboles son iguales.
|
||||
\subsubsection{equals de Node}
|
||||
Aunque este método no lo usamos en LinkedBinaryTree ya que directamente empleamos el método \textit{recEquals}, nunca está de más definir el método equals dentro de una classe.
|
||||
En este caso comprobamos que el parámetro \textit{obj} apunte a una instancia de Node y
|
||||
ejecutamos el método \textit{recEquals}
|
||||
\subsubsection{método recEquals}
|
||||
En primer lugar, comprobamos si alguno de los parámetros apunta a null, si es así devolvemos el resultado de igualar los dos parámetros (si uno es null el otro también debe serlo para cumplir la igualdad).
|
||||
En caso contrario seguimos comprobando si los dos nodos son iguales (Contienen el mismo elemento y sus nodos derecho e izquierdo son también iguales).
|
||||
\newline
|
||||
|
||||
\section{Tarea 2: Recorridos iterativos en árboles binarios}
|
||||
|
||||
\subsection{Interfaz Traversals}
|
||||
\textbf{ ¿Qué diferencias provocaría que la interfaz fuera genérica y los
|
||||
métodos no?}\\
|
||||
En caso de que los métodos sean genéricos y la clase no, podremos usar los métodos con cualquier BinaryTree sin importar de que tipo sean los elementos que contiene.
|
||||
|
||||
En cambio, si implementamos la interfaz de manera genérica y los métodos no-genericos, solo podremos usar dichos métodos con árboles binarios que contengan elementos del mismo tipo con el cual hemos inicializado la instancia de \textbf{Traversals}, \newline por lo cual necesitaremos crear una instancia de \textbf{Traversals} para cada árbol binario que definamos con un tipo distinto.
|
||||
|
||||
\subsection{Clase IterativeTraversals}
|
||||
En esta clase implementamos los diferentes recorridos en profundidad sobre árboles binarios de manera iterativa. \newline
|
||||
Los stacks con los que trabajamos contendrán elementos de tipo BinaryTree, y así iremos comprobando si están vacíos o no para realizar las operaciones.\newline
|
||||
En la explicación de los siguientes métodos voy a referirme algunas
|
||||
veces a \textit{el último elemento introducido en el stack} como el elemento que contiene el root del árbol que es el objeto con el que realmente trabajamos.
|
||||
|
||||
\subsubsection{Preorder}
|
||||
Como debemos recorrer los nodos con el patrón \textit{Parent},
|
||||
\textit{left}, \textit{right}, en este algoritmo empezamos añadiendo al stack el árbol introducido como parametro.\newline
|
||||
Vamos añadiendo a la lista el último elemento introducido en el stack y llenando el stack con los hijos derecho e izquierdo del elemento, tal y como lo plantearíamos en el algoritmo recursivo.
|
||||
|
||||
\subsubsection{Inorder}
|
||||
La idea del algoritmo implementado para éste recorrido (\textit{left}, \textit{parent}, \textit{right}) se basa en posicionarse en el elemento más a la izquierda del árbol y, en cuanto lo encontramos lo añadimos a la lista, añadimos a su padre (que estamos seguros de que será el último elemento añadido en el stack) y visitamos el hijo derecho. \newline
|
||||
Seguimos hasta que el stack esté vacío y el último árbol visitado esté vacío también.
|
||||
|
||||
\subsubsection{Postorder}
|
||||
El algoritmo implementado en éste recorrido (\textit{left}, \textit{right}, \textit{parent})
|
||||
se basa en una idea un poco diferente a las anteriores.\newline
|
||||
Se trata en mirar el recorrido de manera inversa, por lo que recorreremos de \textit{Parent} a \textit{right} a \textit{left} y iremos añadiendo los elementos al principio de la lista y no al final. De esta manera, el código nos queda muy simple y prácticamente igual a la implementación de PreOrder solo que cambiando el orden en que añadimos los hijos. \newline
|
||||
Cabe destacar que es necesario que la lista sea de tipo \textit{LinkedList} para que las inserciones sean óptimas, en caso de ser un \textit{ArrayList} estaríamos aumentando el coste del algoritmo prácticamente de manera exponencial.
|
||||
|
||||
|
||||
\section{Tarea 3: Reconstrucción del árbol binario}
|
||||
La idea en la resolución de éste método se basa en los dos argumentos siguientes:
|
||||
\begin{enumerate}
|
||||
\item El último elemento de la lista que contiene los elementos en postOrden siempre será el root del árbol.
|
||||
\item Debemos encontrar la posición de ese elemento en la lista de inOrden para de esta manera, poder separar los elementos que se encuentran a su izquierda y a su derecha como árbol izquierdo y árbol derecho.
|
||||
\end{enumerate}
|
||||
Siguiendo estas dos premisas implementamos el método de manera recursiva mediante sublistas.
|
||||
\begin{centering}
|
||||
\includegraphics[scale=0.36]{Diagram.png}
|
||||
\end{centering}
|
||||
\section{Conclusiones}
|
||||
|
||||
Durante la resolución del laboratorio hemos aprendido bastante sobre como trata Java los genéricos en tiempo de compilación (mediante el proceso de \textit{type erasure}).
|
||||
Como java en tiempo de ejecución no tiene información sobre los tipos genéricos, es un error realizar un cast de la siguiente manera:
|
||||
\begin{verbatim}
|
||||
Node<E> node = (Node<E>) obj;
|
||||
\end{verbatim}
|
||||
\newline
|
||||
Y en su lugar debemos utilizar comodines:
|
||||
\begin{verbatim}
|
||||
Node<?> node = (Node<?>) obj;
|
||||
\end{verbatim}
|
||||
De esta manera,evitamos un posible error de ejecución.
|
||||
|
||||
En la implementación del método \textit{postAndIn} estubimos debatiendo sobre si implementarlo utilizando índices o sublistas.\newline
|
||||
En el primer caso, la idea se basaba en utilizar 4 índices (2 índices indicando el principio y el final del segmento que queríamos tratar sobre la lista postOrder y 2 índices indicando los mismos parámetros sobre la lista inOrder).\newline
|
||||
En el segundo caso simplemente vamos reduciendo los segmentos a tratar generando sublistas, por lo que nos parecía que era más ineficiente que el primer caso.\newline
|
||||
En cambio, después de adentrarnos en el codigo fuente de la clase ArrayList vimos que el método sublist no genera una lista nueva, sino que devuelve una vista sobre la lista original, por lo que siempre trabajamos sobre el mismo objeto y de una manera muy parecida al primer caso que hemos comentado en el que trabajamos siempre sobre las mismas listas acotando segmentos mediante índices.\newline
|
||||
El método sublist de la clase LinkedList (heredado de la clase AbstractList) se
|
||||
basa en la misma idea, pero el coste de realizar la operación get va a ser
|
||||
mayor, ya que cuando lo hagamos sobre una sublista, realmente se va a realizar
|
||||
sobre la lista original por lo que el coste de realizar dicho get siempre va a
|
||||
ser O(n).
|
||||
|
||||
\end{document}
|
||||
6
java-lab/Tree_Traversals/src/BinaryTree.java
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
public interface BinaryTree<E> {
|
||||
E elem();
|
||||
BinaryTree<E> left();
|
||||
BinaryTree<E> right();
|
||||
boolean isEmpty();
|
||||
}
|
||||
75
java-lab/Tree_Traversals/src/IterativeTraversals.java
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
|
||||
public class IterativeTraversals implements Traversals {
|
||||
|
||||
/**
|
||||
* This method traverses a binary tree in a pre-order way
|
||||
* @param tree the tree its going to be traversed
|
||||
* @param <E> Generic type
|
||||
* @return A list with the pre-order traversal elements of the tree
|
||||
*/
|
||||
@Override
|
||||
public <E> List<E> preOrder(BinaryTree<E> tree) {
|
||||
List<E> list = new LinkedList<>();
|
||||
Stack<BinaryTree<E>> stack = new Stack<>();
|
||||
stack.push(tree);
|
||||
while (!stack.isEmpty()) {
|
||||
BinaryTree<E> actualTree = stack.pop();
|
||||
if (!actualTree.isEmpty()) {
|
||||
list.add(actualTree.elem());
|
||||
stack.push(actualTree.right());
|
||||
stack.push(actualTree.left());
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method traverses a binary tree in a post-order way
|
||||
* @param tree the tree its going to be traversed
|
||||
* @param <E> Generic type
|
||||
* @return A list with the post-order traversal elements of the tree
|
||||
*/
|
||||
@Override
|
||||
public <E> List<E> postOrder(BinaryTree<E> tree) {
|
||||
List<E> list = new LinkedList<>();
|
||||
Stack<BinaryTree<E>> stack = new Stack<>();
|
||||
stack.push(tree);
|
||||
while (!stack.isEmpty()) {
|
||||
BinaryTree<E> current = stack.pop();
|
||||
if (!current.isEmpty()) {
|
||||
stack.push(current.left());
|
||||
stack.push(current.right());
|
||||
list.add(0, current.elem());
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method traverses a binary tree in a in-order way
|
||||
* @param tree the tree its going to be traversed
|
||||
* @param <E> Generic type
|
||||
* @return A list with the in-order traversal elements of the tree
|
||||
*/
|
||||
@Override
|
||||
public <E> List<E> inOrder(BinaryTree<E> tree) {
|
||||
List<E> list = new LinkedList<>();
|
||||
Stack<BinaryTree<E>> stack = new Stack<>();
|
||||
stack.push(tree);
|
||||
BinaryTree<E> current = tree.left();
|
||||
while (!stack.isEmpty() || !current.isEmpty()) {
|
||||
if (!current.isEmpty()) {
|
||||
stack.push(current);
|
||||
current = current.left();
|
||||
} else {
|
||||
current = stack.pop();
|
||||
list.add(current.elem());
|
||||
current = current.right();
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
132
java-lab/Tree_Traversals/src/LinkedBinaryTree.java
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
import java.util.NoSuchElementException;
|
||||
|
||||
public class LinkedBinaryTree<E> implements BinaryTree<E> {
|
||||
private Node<E> root;
|
||||
|
||||
/**
|
||||
* This class represents the internal linked nodes that every LinkedBinaryTree will contains as root
|
||||
*/
|
||||
private static class Node<E> {
|
||||
E elem;
|
||||
Node<E> left;
|
||||
Node<E> right;
|
||||
|
||||
Node(E elem, Node<E> left, Node<E> right) {
|
||||
this.elem = elem;
|
||||
this.left = left;
|
||||
this.right = right;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof Node<?>)) return false;
|
||||
Node<?> other = (Node<?>) obj;
|
||||
return recEquals(this, other);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method recursively checks if two nodes and all his child's are equals
|
||||
* @param root1 The first Node
|
||||
* @param root2 The second Node
|
||||
* @return True if equals, otherwise false
|
||||
*/
|
||||
private static boolean recEquals(Node<?> root1, Node<?> root2) {
|
||||
if (root1 == null || root2 == null) return root1 == root2;
|
||||
return root1.elem.equals(root2.elem)
|
||||
&& recEquals(root1.left, root2.left)
|
||||
&& recEquals(root1.right, root2.right);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Empty LinkedBinaryTree constructor
|
||||
*/
|
||||
public LinkedBinaryTree() {
|
||||
root = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A constructor that initialize an instance
|
||||
* from the element that will be stored into the root
|
||||
* @param elem The element of the root
|
||||
*/
|
||||
public LinkedBinaryTree(E elem) {
|
||||
root = new Node<E>(elem, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* A constructor that initialize an instance from an element, left tree and right tree
|
||||
* @param elem The element to store into the root
|
||||
* @param left The left binary tree
|
||||
* @param right The right binary tree
|
||||
*/
|
||||
public LinkedBinaryTree(E elem, LinkedBinaryTree<E> left, LinkedBinaryTree<E> right) {
|
||||
Node<E> leftNode = (left == null) ? null : left.root;
|
||||
Node<E> rightNode = (right == null) ? null : right.root;
|
||||
root = new Node<>(elem, leftNode, rightNode);
|
||||
}
|
||||
|
||||
/**
|
||||
* A private constructor to initialize an instance from the root Node
|
||||
* @param root the root node
|
||||
*/
|
||||
private LinkedBinaryTree(Node<E> root) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
/**
|
||||
* A getter for the element stored into the root.
|
||||
* @return An object of type E
|
||||
*/
|
||||
@Override
|
||||
public E elem() {
|
||||
if (isEmpty())
|
||||
throw new NoSuchElementException();
|
||||
return root.elem;
|
||||
}
|
||||
|
||||
/**
|
||||
* A getter for the left binary tree
|
||||
* @return A BinaryTree
|
||||
*/
|
||||
@Override
|
||||
public BinaryTree<E> left() {
|
||||
if (isEmpty())
|
||||
throw new NoSuchElementException();
|
||||
return new LinkedBinaryTree<>(root.left);
|
||||
}
|
||||
|
||||
/**
|
||||
* A getter for the right binary tree
|
||||
* @return A BinaryTree
|
||||
*/
|
||||
@Override
|
||||
public BinaryTree<E> right() {
|
||||
if (isEmpty())
|
||||
throw new NoSuchElementException();
|
||||
return new LinkedBinaryTree<>(root.right);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the tree is empty
|
||||
* @return True if empty, otherwise false
|
||||
*/
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return root == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if two LinkedBinaryTrees are equals
|
||||
* @param obj The object to compare
|
||||
* @return True if equals, otherwise false
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof LinkedBinaryTree))
|
||||
return false;
|
||||
LinkedBinaryTree<?> lb = (LinkedBinaryTree<?>) obj;
|
||||
return Node.recEquals(root, lb.root);
|
||||
}
|
||||
}
|
||||
31
java-lab/Tree_Traversals/src/Regenerator.java
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import java.util.List;
|
||||
|
||||
public class Regenerator {
|
||||
/**
|
||||
*This function reconstructs a LinkedBinaryTree from its post-order and in-order sequences.
|
||||
* @param postOrder The post-order sequence of the tree
|
||||
* @param inOrder The in-order sequence of the tree
|
||||
* @param <E> Generic type
|
||||
* @return the reconstructed binary tree
|
||||
*/
|
||||
public static <E> LinkedBinaryTree<E> postAndIn(List<? extends E> postOrder, List<? extends E> inOrder) {
|
||||
int treeSize = postOrder.size();
|
||||
if (treeSize == 0)
|
||||
return new LinkedBinaryTree<>();
|
||||
else if (treeSize == 1) {
|
||||
E root = postOrder.get(treeSize - 1);
|
||||
return new LinkedBinaryTree<>(root);
|
||||
} else {
|
||||
E root = postOrder.get(treeSize - 1);
|
||||
int indexOfRoot = inOrder.indexOf(root);
|
||||
List<? extends E> inOrderLeft = inOrder.subList(0, indexOfRoot);
|
||||
List<? extends E> inOrderRight = inOrder.subList(indexOfRoot + 1, treeSize);
|
||||
List<? extends E> postOrderLeft = postOrder.subList(0, indexOfRoot);
|
||||
List<? extends E> postOrderRight = postOrder.subList(indexOfRoot, treeSize - 1);
|
||||
|
||||
return new LinkedBinaryTree<>(root,
|
||||
postAndIn(postOrderLeft, inOrderLeft),
|
||||
postAndIn(postOrderRight, inOrderRight));
|
||||
}
|
||||
}
|
||||
}
|
||||
7
java-lab/Tree_Traversals/src/Traversals.java
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import java.util.List;
|
||||
|
||||
public interface Traversals {
|
||||
<E> List<E> preOrder(BinaryTree<E> tree);
|
||||
<E> List<E> inOrder(BinaryTree<E> tree);
|
||||
<E> List<E> postOrder(BinaryTree<E> tree);
|
||||
}
|
||||
58
java-lab/Tree_Traversals/test/IterativeTraversalsTest.java
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
class IterativeTraversalsTest {
|
||||
private final LinkedBinaryTree<Integer> bt = new LinkedBinaryTree<>(3,
|
||||
new LinkedBinaryTree<>(4,
|
||||
null,
|
||||
new LinkedBinaryTree<>(43)),
|
||||
new LinkedBinaryTree<>(5,
|
||||
new LinkedBinaryTree<>(25),
|
||||
new LinkedBinaryTree<>(53,
|
||||
new LinkedBinaryTree<>(2),
|
||||
null)
|
||||
)
|
||||
);
|
||||
|
||||
private final LinkedBinaryTree<String> bt2 = new LinkedBinaryTree<>("Hi!",
|
||||
new LinkedBinaryTree<>("Bye!",
|
||||
new LinkedBinaryTree<>("Stre!"),
|
||||
new LinkedBinaryTree<>("Oui!",
|
||||
null,
|
||||
new LinkedBinaryTree<>("Uala!"))),
|
||||
new LinkedBinaryTree<>("Ecs!",
|
||||
new LinkedBinaryTree<>("Lolo"),
|
||||
new LinkedBinaryTree<>("lala",
|
||||
new LinkedBinaryTree<>("Ei!",
|
||||
new LinkedBinaryTree<>("Prra!"),
|
||||
null),
|
||||
new LinkedBinaryTree<>())
|
||||
)
|
||||
);
|
||||
|
||||
@Test
|
||||
void test_traversals_integer_tree() {
|
||||
List<Integer> preOrder = new LinkedList<>(List.of(3, 4, 43, 5, 25, 53, 2));
|
||||
List<Integer> inOrder = new LinkedList<>(List.of(4, 43, 3, 25, 5, 2, 53));
|
||||
List<Integer> postOrder = new LinkedList<>(List.of(43, 4, 25, 2, 53, 5, 3));
|
||||
IterativeTraversals it = new IterativeTraversals();
|
||||
assertEquals(preOrder, it.preOrder(bt));
|
||||
assertEquals(inOrder, it.inOrder(bt));
|
||||
assertEquals(postOrder, it.postOrder(bt));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_traversals_string_tree(){
|
||||
List<String> preOrder = new LinkedList<>(List.of("Hi!", "Bye!", "Stre!", "Oui!", "Uala!", "Ecs!", "Lolo", "lala", "Ei!", "Prra!"));
|
||||
List<String> inOrder = new LinkedList<>(List.of("Stre!", "Bye!", "Oui!", "Uala!", "Hi!", "Lolo", "Ecs!", "Prra!", "Ei!", "lala"));
|
||||
List<String> postOrder = new LinkedList<>(List.of("Stre!", "Uala!", "Oui!", "Bye!", "Lolo", "Prra!", "Ei!", "lala", "Ecs!", "Hi!"));
|
||||
IterativeTraversals it = new IterativeTraversals();
|
||||
assertEquals(preOrder, it.preOrder(bt2));
|
||||
assertEquals(inOrder, it.inOrder(bt2));
|
||||
assertEquals(postOrder, it.postOrder(bt2));
|
||||
}
|
||||
|
||||
}
|
||||
69
java-lab/Tree_Traversals/test/LinkedBinaryTreeTest.java
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class LinkedBinaryTreeTest {
|
||||
|
||||
private final LinkedBinaryTree<Integer> bt = new LinkedBinaryTree<>(3,
|
||||
new LinkedBinaryTree<>(4,
|
||||
new LinkedBinaryTree<>(34),
|
||||
new LinkedBinaryTree<>()),
|
||||
new LinkedBinaryTree<>(5,
|
||||
new LinkedBinaryTree<>(25),
|
||||
new LinkedBinaryTree<>(53)
|
||||
)
|
||||
);
|
||||
|
||||
private final LinkedBinaryTree<Integer> bt2 = new LinkedBinaryTree<>(3,
|
||||
new LinkedBinaryTree<>(4,
|
||||
new LinkedBinaryTree<>(34),
|
||||
new LinkedBinaryTree<>()),
|
||||
new LinkedBinaryTree<>(5,
|
||||
new LinkedBinaryTree<>(25),
|
||||
new LinkedBinaryTree<>(53)
|
||||
)
|
||||
);
|
||||
|
||||
private final LinkedBinaryTree<String> bt3 = new LinkedBinaryTree<>("Hi!",
|
||||
new LinkedBinaryTree<>("Bye!",
|
||||
new LinkedBinaryTree<>("Stre!"),
|
||||
new LinkedBinaryTree<>("Oui!",
|
||||
null,
|
||||
new LinkedBinaryTree<>("Uala!"))),
|
||||
new LinkedBinaryTree<>("Ecs!",
|
||||
new LinkedBinaryTree<>("Lolo"),
|
||||
new LinkedBinaryTree<>("lala",
|
||||
new LinkedBinaryTree<>("Ei!",
|
||||
new LinkedBinaryTree<>("Prra!"),
|
||||
null),
|
||||
new LinkedBinaryTree<>())
|
||||
)
|
||||
);
|
||||
|
||||
private final LinkedBinaryTree<String> emptyBt = new LinkedBinaryTree<>();
|
||||
|
||||
@Test
|
||||
void test_equals() {
|
||||
assertEquals(bt, bt2);
|
||||
assertNotEquals(bt, bt3);
|
||||
assertEquals(bt.left(), bt2.left());
|
||||
assertEquals(bt.right(), bt2.right());
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_elem(){
|
||||
assertEquals(3, bt.elem());
|
||||
assertEquals(4, bt.left().elem());
|
||||
assertEquals(5, bt.right().elem());
|
||||
assertEquals("Hi!", bt3.elem());
|
||||
assertEquals("Bye!", bt3.left().elem());
|
||||
assertEquals("Ecs!", bt3.right().elem());
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_empty(){
|
||||
assertFalse(bt.isEmpty());
|
||||
assertFalse(bt3.isEmpty());
|
||||
assertFalse(bt.right().isEmpty());
|
||||
assertTrue(emptyBt.isEmpty());
|
||||
}
|
||||
}
|
||||
70
java-lab/Tree_Traversals/test/RegeneratorTest.java
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RegeneratorTest {
|
||||
private final LinkedBinaryTree<Integer> bt = new LinkedBinaryTree<>(3,
|
||||
new LinkedBinaryTree<>(4,
|
||||
new LinkedBinaryTree<>(34),
|
||||
null),
|
||||
new LinkedBinaryTree<>(5,
|
||||
new LinkedBinaryTree<>(25),
|
||||
new LinkedBinaryTree<>(53,
|
||||
new LinkedBinaryTree<>(2),
|
||||
new LinkedBinaryTree<>())
|
||||
)
|
||||
);
|
||||
|
||||
private final IterativeTraversals it = new IterativeTraversals();
|
||||
|
||||
@Test
|
||||
void test_regenerator_integer_tree() {
|
||||
List<Integer> postOrder = it.postOrder(bt);
|
||||
List<Integer> inOrder = it.inOrder(bt);
|
||||
LinkedBinaryTree<Integer> regeneratedTree = Regenerator.postAndIn(postOrder, inOrder);
|
||||
assertEquals(postOrder, it.postOrder(regeneratedTree));
|
||||
assertEquals(inOrder, it.inOrder(regeneratedTree));
|
||||
}
|
||||
|
||||
private final LinkedBinaryTree<String> bt2 = new LinkedBinaryTree<>("Hi!",
|
||||
new LinkedBinaryTree<>("Bye!",
|
||||
new LinkedBinaryTree<>("Stre!"),
|
||||
new LinkedBinaryTree<>("Oui!",
|
||||
null,
|
||||
new LinkedBinaryTree<>("Uala!"))),
|
||||
new LinkedBinaryTree<>("Ecs!",
|
||||
new LinkedBinaryTree<>("Lolo"),
|
||||
new LinkedBinaryTree<>("lala",
|
||||
new LinkedBinaryTree<>("Ei!",
|
||||
new LinkedBinaryTree<>("Prra!"),
|
||||
null),
|
||||
new LinkedBinaryTree<>())
|
||||
)
|
||||
);
|
||||
|
||||
@Test
|
||||
void test_regenerator_string_tree(){
|
||||
List<String> postOrder = it.postOrder(bt2);
|
||||
List<String> inOrder = it.inOrder(bt2);
|
||||
LinkedBinaryTree<String> regeneratedTree = Regenerator.postAndIn(postOrder, inOrder);
|
||||
assertEquals(postOrder, it.postOrder(regeneratedTree));
|
||||
assertEquals(inOrder, it.inOrder(regeneratedTree));
|
||||
}
|
||||
|
||||
private final LinkedBinaryTree<Double> bt3 = new LinkedBinaryTree<>(3.5465423,
|
||||
new LinkedBinaryTree<>(4.5465),
|
||||
new LinkedBinaryTree<>(2.5431)
|
||||
);
|
||||
|
||||
@Test
|
||||
void test_regenerator_double_tree(){
|
||||
List<Double> postOrder = it.postOrder(bt3);
|
||||
List<Double> inOrder = it.inOrder(bt3);
|
||||
LinkedBinaryTree<Double> regeneratedTree = Regenerator.postAndIn(postOrder, inOrder);
|
||||
assertEquals(postOrder, it.postOrder(regeneratedTree));
|
||||
assertEquals(inOrder, it.inOrder(regeneratedTree));
|
||||
}
|
||||
|
||||
}
|
||||