First commit, aggregated repos
This commit is contained in:
176
.gitignore
vendored
Normal file
176
.gitignore
vendored
Normal file
@@ -0,0 +1,176 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
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
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .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
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
27
Cryptography/README.md
Normal file
27
Cryptography/README.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# CS327-Cryptography
|
||||
|
||||
Nicholas Tamassia
|
||||
|
||||
February 27, 2025
|
||||
|
||||
CS-327
|
||||
|
||||
Cryptography PA
|
||||
|
||||
**Program Location:** `/cs/home/stu/tamassno/cs327/cryptography_PA/affine.py`
|
||||
|
||||
**Usage:** `python affine.py [encrypt | decrypt | decipher] --help`
|
||||
|
||||
## Questions
|
||||
|
||||
### 7.1 Part 1
|
||||
$D(c,a,b)=a^{-1}(c-b)\;\text{mod}\;128$
|
||||
|
||||
### 7.1 Part 2
|
||||
Restrictions on $a$ and $b$:
|
||||
1. $0 < a < 128$, $a$ and $128$ must be coprime, i.e. $\text{gcd}(128,a)=1$
|
||||
2. $0 \leq b < 128$
|
||||
|
||||
### 7.1 Part 3
|
||||
Because 128 is coprime with all odd numbers less than itself (1, 3, 5, …, 127), there are 64 possible values for a. There are 128 options for b so there exists an upper limit on valid $a$, $b$
|
||||
pairs of 8192.
|
||||
178
Cryptography/affine.py
Normal file
178
Cryptography/affine.py
Normal file
@@ -0,0 +1,178 @@
|
||||
from typing import TextIO
|
||||
import re
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
|
||||
ASCII_MODULO = 128
|
||||
|
||||
def encrypt_string(string: str, a: int, b: int):
|
||||
def encrypt_char(m): return (a * m + b) % ASCII_MODULO
|
||||
return ''.join(chr(encrypt_char(ord(char))) for char in string)
|
||||
|
||||
|
||||
def encrypt(plaintext_file: TextIO, output_file: TextIO, a: int, b: int) -> None:
|
||||
valid_a = a > 0 and a < ASCII_MODULO and egcd(ASCII_MODULO, a)[0] == 1
|
||||
valid_b = b >= 0 and b < ASCII_MODULO
|
||||
|
||||
if (not (valid_a and valid_b)):
|
||||
print(f"The key pair ({a}, {b}) is invalid, please select another key")
|
||||
return
|
||||
|
||||
plaintext_characters: str = ''.join(plaintext_file.readlines())
|
||||
output_file.write(encrypt_string(plaintext_characters, a, b))
|
||||
|
||||
|
||||
def decrypt_string(string: str, inverse_a: int, b: int) -> str:
|
||||
def decrypt_char(m): return (inverse_a * (m - b)) % ASCII_MODULO
|
||||
return ''.join(chr(decrypt_char(ord(char))) for char in string)
|
||||
|
||||
|
||||
def decrypt(ciphertext_file: TextIO, output_file: TextIO, a: int, b: int) -> None:
|
||||
valid_a = a > 0 and a < ASCII_MODULO and egcd(ASCII_MODULO, a)[0] == 1
|
||||
valid_b = b >= 0 and b < ASCII_MODULO
|
||||
|
||||
if not (valid_a and valid_b):
|
||||
print(f"The key pair ({a}, {b}) is invalid, please select another key")
|
||||
return
|
||||
|
||||
inverse_a = modular_inverse(a, ASCII_MODULO)
|
||||
ciphered_text: str = ''.join(ciphertext_file.readlines())
|
||||
output_file.write(decrypt_string(ciphered_text, inverse_a, b))
|
||||
|
||||
|
||||
def decipher(ciphertext_file: TextIO, output_file: TextIO, dictionary_file: TextIO) -> None:
|
||||
dictionary = set(word.strip().lower()
|
||||
for word in dictionary_file.readlines())
|
||||
|
||||
ciphered_text: str = ''.join(ciphertext_file.readlines())
|
||||
|
||||
best_word_count = -1
|
||||
best_a = -1
|
||||
best_b = -1
|
||||
|
||||
for a in range(1, ASCII_MODULO, 2):
|
||||
inverse_a = modular_inverse(a, ASCII_MODULO)
|
||||
|
||||
for b in range(0, ASCII_MODULO):
|
||||
decrypted_string = decrypt_string(ciphered_text, inverse_a, b)
|
||||
word_count = count_words(decrypted_string, dictionary)
|
||||
|
||||
if word_count > best_word_count:
|
||||
best_word_count = word_count
|
||||
best_a = a
|
||||
best_b = b
|
||||
|
||||
best_inverse_a = modular_inverse(best_a, ASCII_MODULO)
|
||||
deciphered_text = decrypt_string(ciphered_text, best_inverse_a, best_b)
|
||||
output_file.write(f"{best_a} {best_b}\n")
|
||||
output_file.write("DECIPHERED MESSAGE:\n")
|
||||
output_file.write(f"{deciphered_text}")
|
||||
|
||||
|
||||
def count_words(string: str, dictionary: set[str]) -> int:
|
||||
words: list[str] = re.findall(r'\b\w+\b', string)
|
||||
return sum(1 * len(word) for word in words if word.strip().lower() in dictionary)
|
||||
|
||||
|
||||
def modular_inverse(a: int, mod: int) -> int:
|
||||
d, s, _ = egcd(a, mod)
|
||||
if d != 1:
|
||||
return -1 # No modular inverse exists
|
||||
return s % mod # Ensure it's positive
|
||||
|
||||
|
||||
def egcd(a: int, b: int) -> tuple[int, int, int]:
|
||||
s, t, u, v = 1, 0, 0, 1
|
||||
|
||||
while b != 0:
|
||||
q = a // b
|
||||
a, b = b, a % b
|
||||
s, t, u, v = u, v, s - u * q, t - v * q
|
||||
|
||||
d = a
|
||||
|
||||
return d, s, t
|
||||
|
||||
|
||||
def create_arg_parser():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="CLI tool for encryption, decryption, and deciphering.")
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
# Encrypt command
|
||||
encrypt_parser = subparsers.add_parser(
|
||||
"encrypt", help="Encrypt a plaintext file.")
|
||||
encrypt_parser.add_argument(
|
||||
"plaintext_file", help="Path to the plaintext .txt file.")
|
||||
encrypt_parser.add_argument(
|
||||
"output_file", help="Path to the output encrypted .txt file.")
|
||||
encrypt_parser.add_argument(
|
||||
"a", type=int, help="Parameter a for encryption.")
|
||||
encrypt_parser.add_argument(
|
||||
"b", type=int, help="Parameter b for encryption.")
|
||||
|
||||
# Decrypt command
|
||||
decrypt_parser = subparsers.add_parser(
|
||||
"decrypt", help="Decrypt a ciphertext file.")
|
||||
decrypt_parser.add_argument(
|
||||
"ciphertext_file", help="Path to the ciphertext .txt file.")
|
||||
decrypt_parser.add_argument(
|
||||
"output_file", help="Path to the output decrypted .txt file.")
|
||||
decrypt_parser.add_argument(
|
||||
"a", type=int, help="Parameter a for decryption.")
|
||||
decrypt_parser.add_argument(
|
||||
"b", type=int, help="Parameter b for decryption.")
|
||||
|
||||
# Decipher command
|
||||
decipher_parser = subparsers.add_parser(
|
||||
"decipher", help="Decipher a ciphertext file using a dictionary.")
|
||||
decipher_parser.add_argument(
|
||||
"ciphertext_file", help="Path to the ciphertext .txt file.")
|
||||
decipher_parser.add_argument(
|
||||
"output_file", help="Path to the output deciphered .txt file.")
|
||||
decipher_parser.add_argument(
|
||||
"dictionary_file", help="Path to the dictionary .txt file.")
|
||||
return parser
|
||||
|
||||
|
||||
def valid_file_path(path: Path) -> bool:
|
||||
return path.exists() and path.suffix == ".txt"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = create_arg_parser()
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.command == "encrypt":
|
||||
plaintext_file_path = Path(args.plaintext_file).resolve()
|
||||
output_file_path = Path(args.output_file).resolve()
|
||||
|
||||
if valid_file_path(plaintext_file_path) and valid_file_path(output_file_path):
|
||||
with open(plaintext_file_path, 'r') as plaintext_file, open(output_file_path, 'w') as output_file:
|
||||
encrypt(plaintext_file, output_file, args.a, args.b)
|
||||
else:
|
||||
print("Invalid file path(s), check paths point to .txt files")
|
||||
parser.print_help()
|
||||
|
||||
elif args.command == "decrypt":
|
||||
ciphertext_file_path = Path(args.ciphertext_file).resolve()
|
||||
output_file_path = Path(args.output_file).resolve()
|
||||
|
||||
if valid_file_path(ciphertext_file_path) and valid_file_path(output_file_path):
|
||||
with open(ciphertext_file_path, 'r') as ciphertext_file, open(output_file_path, 'w') as output_file:
|
||||
decrypt(ciphertext_file, output_file, args.a, args.b)
|
||||
else:
|
||||
print("Invalid file path(s), check paths point to .txt files")
|
||||
parser.print_help()
|
||||
|
||||
elif args.command == "decipher":
|
||||
ciphertext_file_path = Path(args.ciphertext_file).resolve()
|
||||
output_file_path = Path(args.output_file).resolve()
|
||||
dictionary_file_path = Path(args.dictionary_file).resolve()
|
||||
|
||||
if valid_file_path(ciphertext_file_path) and valid_file_path(output_file_path) and valid_file_path(dictionary_file_path):
|
||||
with open(ciphertext_file_path, 'r') as ciphertext_file, open(output_file_path, 'w') as output_file, open(dictionary_file_path, 'r') as dictionary_file:
|
||||
decipher(ciphertext_file, output_file, dictionary_file)
|
||||
else:
|
||||
print("Invalid file path(s), check paths point to .txt files")
|
||||
parser.print_help()
|
||||
BIN
Cryptography/text_files/all_characters.txt
Normal file
BIN
Cryptography/text_files/all_characters.txt
Normal file
Binary file not shown.
BIN
Cryptography/text_files/all_characters_caesar.txt
Normal file
BIN
Cryptography/text_files/all_characters_caesar.txt
Normal file
Binary file not shown.
1
Cryptography/text_files/ciphertext.txt
Normal file
1
Cryptography/text_files/ciphertext.txt
Normal file
@@ -0,0 +1 @@
|
||||
bWb\W>bk\W/b/z>bbabWu\brf C Pf >b>zuCb uRz Hb9\>uW\b/WHk]b H buCbb9\zbWb *>HPPC>9
|
||||
466544
Cryptography/text_files/words.txt
Normal file
466544
Cryptography/text_files/words.txt
Normal file
File diff suppressed because it is too large
Load Diff
349
Desk-Calculator/Evaluator.java
Normal file
349
Desk-Calculator/Evaluator.java
Normal file
@@ -0,0 +1,349 @@
|
||||
package evaluator;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.LinkedList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Simulate a PDA to evaluate a series of postfix expressions provided by a
|
||||
* lexer. The constructor argument is the lexer of type Lexer. A single line is
|
||||
* evaluated and its value is printed. Expression values can also be assigned to
|
||||
* variables for later use. If no variable is explicitly assigned, then the
|
||||
* default variable "it" is assigned the value of the most recently evaluated
|
||||
* expression.
|
||||
*
|
||||
* @author YOU NAME HERE
|
||||
*/
|
||||
public class Evaluator {
|
||||
|
||||
/**
|
||||
* Run the desk calculator.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Evaluator evaluator = new Evaluator(new Lexer(System.in));
|
||||
evaluator.run();
|
||||
}
|
||||
|
||||
private Lexer lexer; // providing a stream of tokens
|
||||
private LinkedList<Double> stack; // operands
|
||||
private HashMap<String, Double> symbols; // symbol table for variables
|
||||
private String target; // variable assigned the latest expression value
|
||||
|
||||
public Evaluator(Lexer lexer) {
|
||||
this.lexer = lexer;
|
||||
stack = new LinkedList<>();
|
||||
symbols = new HashMap<>();
|
||||
target = "it";
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a single line of input, which should be a complete expression
|
||||
* optionally assigned to a variable; if no variable is assigned to, then the
|
||||
* result is assigned to "it". In any case, return the value of the expression,
|
||||
* or "no value" if there was some sort of error.
|
||||
*/
|
||||
public Double evaluate() {
|
||||
|
||||
stack.clear();
|
||||
target = "it";
|
||||
|
||||
int q = 1;
|
||||
|
||||
while (q != 4) {
|
||||
int token = lexer.nextToken();
|
||||
|
||||
if (lexer.getText().equals("exit")) {
|
||||
System.out.println("Bye");
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
switch (q) {
|
||||
case 1:
|
||||
switch (token) {
|
||||
case Lexer.NUMBER -> {
|
||||
stack.push(Double.parseDouble(lexer.getText()));
|
||||
q = 3;
|
||||
}
|
||||
case Lexer.VARIABLE -> {
|
||||
target = lexer.getText();
|
||||
stack.push(symbols.getOrDefault(target, 0.0));
|
||||
q = 2;
|
||||
}
|
||||
default -> error("Invald token encountered in state q1");
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
switch (token) {
|
||||
case Lexer.ASSIGN_OP -> {
|
||||
stack.pop();
|
||||
q = 3;
|
||||
}
|
||||
case Lexer.MINUS_OP -> {
|
||||
target = "it";
|
||||
stack.push(-1 * stack.pop());
|
||||
q = 3;
|
||||
}
|
||||
case Lexer.NUMBER -> {
|
||||
target = "it";
|
||||
stack.push(Double.parseDouble(lexer.getText()));
|
||||
q = 3;
|
||||
}
|
||||
case Lexer.VARIABLE -> {
|
||||
target = "it";
|
||||
stack.push(symbols.getOrDefault(lexer.getText(), 0.0));
|
||||
q = 3;
|
||||
}
|
||||
case Lexer.EOL -> {
|
||||
target = "it";
|
||||
symbols.put(target, stack.pop());
|
||||
q = 4;
|
||||
}
|
||||
default -> error("Invald token encountered in state q2");
|
||||
}
|
||||
break;
|
||||
case 3:
|
||||
switch (token) {
|
||||
case Lexer.MINUS_OP -> stack.push(-1 * stack.pop());
|
||||
case Lexer.NUMBER -> stack.push(Double.parseDouble(lexer.getText()));
|
||||
case Lexer.VARIABLE -> stack.push(symbols.getOrDefault(lexer.getText(), 0.0));
|
||||
case Lexer.ADD_OP -> {
|
||||
double a1 = stack.pop();
|
||||
double a2 = stack.pop();
|
||||
stack.push(a2 + a1);
|
||||
}
|
||||
case Lexer.SUBTRACT_OP -> {
|
||||
double s1 = stack.pop();
|
||||
double s2 = stack.pop();
|
||||
stack.push(s2 - s1);
|
||||
}
|
||||
case Lexer.MULTIPLY_OP -> {
|
||||
double m1 = stack.pop();
|
||||
double m2 = stack.pop();
|
||||
stack.push(m2 * m1);
|
||||
}
|
||||
case Lexer.DIVIDE_OP -> {
|
||||
double d1 = stack.pop();
|
||||
double d2 = stack.pop();
|
||||
stack.push(d2 / d1);
|
||||
}
|
||||
case Lexer.EOL -> {
|
||||
symbols.put(target, stack.pop());
|
||||
q = 4;
|
||||
}
|
||||
default -> error("Invald token encountered in state q3");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return symbols.get(target);
|
||||
} // evaluate
|
||||
|
||||
/**
|
||||
* Run evaluate on each line of input and print the result forever.
|
||||
*/
|
||||
public void run() {
|
||||
while (true) {
|
||||
Double value = evaluate();
|
||||
if (value == null)
|
||||
System.out.println("no value");
|
||||
else
|
||||
System.out.println(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Print an error message, display the offending line with the current location
|
||||
* marked, and flush the lexer in preparation for the next line.
|
||||
*
|
||||
* @param msg what to print as an error indication
|
||||
*/
|
||||
private void error(String msg) {
|
||||
System.out.println(msg);
|
||||
String line = lexer.getCurrentLine();
|
||||
int index = lexer.getCurrentChar();
|
||||
System.out.print(line);
|
||||
for (int i = 1; i < index; i++)
|
||||
System.out.print(' ');
|
||||
System.out.println("^");
|
||||
lexer.flush();
|
||||
}
|
||||
|
||||
////////////////////////////////
|
||||
///////// Lexer Class //////////
|
||||
|
||||
/**
|
||||
* Read terminal input and convert it to a token type, and also record the text
|
||||
* of each token. Whitespace is skipped. The input comes from stdin, and each
|
||||
* line is prompted for.
|
||||
*/
|
||||
public static class Lexer {
|
||||
|
||||
// language token codes
|
||||
public static final int ADD_OP = 3;
|
||||
public static final int SUBTRACT_OP = 4;
|
||||
public static final int MULTIPLY_OP = 5;
|
||||
public static final int DIVIDE_OP = 6;
|
||||
public static final int MINUS_OP = 7;
|
||||
public static final int ASSIGN_OP = 8;
|
||||
public static final int EOL = 9;
|
||||
public static final int NUMBER = 11;
|
||||
public static final int VARIABLE = 12;
|
||||
public static final int BAD_TOKEN = 100;
|
||||
|
||||
private Scanner input; // for reading lines from stdin
|
||||
private String line; // next input line
|
||||
private int index; // current character in this line
|
||||
private String text; // text of the current token
|
||||
|
||||
public Lexer(InputStream in) {
|
||||
input = new Scanner(in);
|
||||
line = "";
|
||||
index = 0;
|
||||
text = "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the next character from the terminal. If the current line is exhausted,
|
||||
* then prompt the user and wait for input. If end-of-file occurs, then exit the
|
||||
* program.
|
||||
*/
|
||||
private char nextChar() {
|
||||
if (index == line.length()) {
|
||||
System.out.print(">> ");
|
||||
if (input.hasNextLine()) {
|
||||
line = input.nextLine() + "\n";
|
||||
index = 0;
|
||||
} else {
|
||||
System.out.println("\nBye");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
char ch = line.charAt(index);
|
||||
index++;
|
||||
return ch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the last character back on the input line.
|
||||
*/
|
||||
private void unread() {
|
||||
index -= 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the next token from the terminal.
|
||||
*/
|
||||
public int nextToken() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
char t;
|
||||
int q = 0;
|
||||
|
||||
while (true) {
|
||||
t = nextChar();
|
||||
|
||||
switch (q) {
|
||||
case 0 -> {
|
||||
if (Character.isWhitespace(t) && t != '\n') {
|
||||
continue;
|
||||
}
|
||||
|
||||
sb.append(t);
|
||||
|
||||
if (Character.isDigit(t)) {
|
||||
q = 1;
|
||||
continue;
|
||||
}
|
||||
if (Character.isLetter(t)) {
|
||||
q = 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
text = sb.toString();
|
||||
|
||||
return switch (t) {
|
||||
case '+' -> ADD_OP;
|
||||
case '-' -> SUBTRACT_OP;
|
||||
case '*' -> MULTIPLY_OP;
|
||||
case '/' -> DIVIDE_OP;
|
||||
case '~' -> MINUS_OP;
|
||||
case '=' -> ASSIGN_OP;
|
||||
case '\n' -> EOL;
|
||||
default -> BAD_TOKEN;
|
||||
};
|
||||
}
|
||||
|
||||
case 1 -> {
|
||||
if (Character.isDigit(t)) {
|
||||
sb.append(t);
|
||||
continue;
|
||||
} else if (t == '.') {
|
||||
sb.append(t);
|
||||
q = 10;
|
||||
continue;
|
||||
} else {
|
||||
unread();
|
||||
text = sb.toString();
|
||||
return NUMBER;
|
||||
}
|
||||
}
|
||||
|
||||
case 2 -> {
|
||||
if (Character.isLetterOrDigit(t)) {
|
||||
sb.append(t);
|
||||
continue;
|
||||
} else {
|
||||
unread();
|
||||
text = sb.toString();
|
||||
return VARIABLE;
|
||||
}
|
||||
}
|
||||
|
||||
case 10 -> {
|
||||
if (Character.isDigit(t)) {
|
||||
sb.append(t);
|
||||
continue;
|
||||
} else {
|
||||
unread();
|
||||
text = sb.toString();
|
||||
return NUMBER;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} // nextToken
|
||||
|
||||
/**
|
||||
* Return the current line for error messages.
|
||||
*/
|
||||
public String getCurrentLine() {
|
||||
return line;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current character index for error messages.
|
||||
*/
|
||||
public int getCurrentChar() {
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* /** Return the text of the current token.
|
||||
*/
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the current line after an error
|
||||
*/
|
||||
public void flush() {
|
||||
index = line.length();
|
||||
}
|
||||
|
||||
} // Lexer
|
||||
|
||||
} // Evaluator
|
||||
140
Desk-Calculator/EvaluatorTest.java
Normal file
140
Desk-Calculator/EvaluatorTest.java
Normal file
@@ -0,0 +1,140 @@
|
||||
package evaluator;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import evaluator.Evaluator.Lexer;
|
||||
|
||||
class EvaluatorTest {
|
||||
|
||||
@Test
|
||||
void lexerGoodInputTest() {
|
||||
InputStream input = new ByteArrayInputStream("x1x = 10.34 10 +\n".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Lexer lexer = new Lexer(input);
|
||||
|
||||
assertEquals(Lexer.VARIABLE, lexer.nextToken());
|
||||
assertEquals("x1x", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.ASSIGN_OP, lexer.nextToken());
|
||||
assertEquals("=", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("10.34", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("10", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.ADD_OP, lexer.nextToken());
|
||||
assertEquals("+", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.EOL, lexer.nextToken());
|
||||
assertEquals("\n", lexer.getText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lexerBadInputTest() {
|
||||
InputStream input = new ByteArrayInputStream("y,!g != 34.67 16! ".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Lexer lexer = new Lexer(input);
|
||||
|
||||
assertEquals(Lexer.VARIABLE, lexer.nextToken());
|
||||
assertEquals("y", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.BAD_TOKEN, lexer.nextToken());
|
||||
assertEquals(",", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.BAD_TOKEN, lexer.nextToken());
|
||||
assertEquals("!", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.VARIABLE, lexer.nextToken());
|
||||
assertEquals("g", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.BAD_TOKEN, lexer.nextToken());
|
||||
assertEquals("!", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.ASSIGN_OP, lexer.nextToken());
|
||||
assertEquals("=", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("34.67", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("16", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.BAD_TOKEN, lexer.nextToken());
|
||||
assertEquals("!", lexer.getText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lexerExtraWhiteSpaceTest() {
|
||||
InputStream input = new ByteArrayInputStream(" y = 17.5 + 34 * ".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Lexer lexer = new Lexer(input);
|
||||
|
||||
assertEquals(Lexer.VARIABLE, lexer.nextToken());
|
||||
assertEquals("y", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.ASSIGN_OP, lexer.nextToken());
|
||||
assertEquals("=", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("17.5", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.ADD_OP, lexer.nextToken());
|
||||
assertEquals("+", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("34", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.MULTIPLY_OP, lexer.nextToken());
|
||||
assertEquals("*", lexer.getText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lexerNoWhiteSpaceTest() {
|
||||
InputStream input = new ByteArrayInputStream("10+17=!13x78y*\n".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Lexer lexer = new Lexer(input);
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("10", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.ADD_OP, lexer.nextToken());
|
||||
assertEquals("+", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("17", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.ASSIGN_OP, lexer.nextToken());
|
||||
assertEquals("=", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.BAD_TOKEN, lexer.nextToken());
|
||||
assertEquals("!", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.NUMBER, lexer.nextToken());
|
||||
assertEquals("13", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.VARIABLE, lexer.nextToken());
|
||||
assertEquals("x78y", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.MULTIPLY_OP, lexer.nextToken());
|
||||
assertEquals("*", lexer.getText());
|
||||
|
||||
assertEquals(Lexer.EOL, lexer.nextToken());
|
||||
assertEquals("\n", lexer.getText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void evaluatorSimpleExpressionTest() {
|
||||
InputStream input = new ByteArrayInputStream("10 10 *\n".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Evaluator eval = new Evaluator(new Lexer(input));
|
||||
|
||||
assertEquals(100, eval.evaluate());
|
||||
}
|
||||
}
|
||||
158
Orbital-Bodies/Matrix.java
Normal file
158
Orbital-Bodies/Matrix.java
Normal file
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* A simple m x n matrix class.
|
||||
*
|
||||
* TODO All of the methods currently just return default values. You need to make them match the Javadoc comments.
|
||||
*
|
||||
* @author YOUR NAME HERE
|
||||
* @version Sept. 2017
|
||||
*/
|
||||
|
||||
public class Matrix {
|
||||
|
||||
private int m, n;
|
||||
private double[][] M;
|
||||
|
||||
public Matrix(double[][] array) {
|
||||
M = array;
|
||||
m = array.length;
|
||||
n = array[0].length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The number of columns in the matrix.
|
||||
*/
|
||||
public int nCols() { return n; }
|
||||
|
||||
/**
|
||||
* @return the number of rows.
|
||||
*/
|
||||
public int nRows() { return m; }
|
||||
|
||||
/**
|
||||
* @param i
|
||||
* @param j
|
||||
* @return The entry at row i column j.
|
||||
*/
|
||||
public double entry(int i, int j) {
|
||||
return M[i][j];
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the dot product of this matrix with the parameter that. (Return value is this . that)
|
||||
* Recall that the dot product is the typical matrix multiplication.
|
||||
* @param that The matrix to apply this matrix to.
|
||||
* @throws BadDimensionException If this.nCols() != that.nRows() because the dot product is not defined
|
||||
* @return The dot product of this matrix with that.
|
||||
*/
|
||||
public Matrix dot(Matrix that) throws UndefinedMatrixOpException {
|
||||
if (this.nCols() != that.nRows()) {
|
||||
throw new UndefinedMatrixOpException("Dot product not defined", this, that);
|
||||
}
|
||||
|
||||
double[][] result = new double[this.nRows()][that.nCols()];
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
for (int j = 0; j < result[i].length; j++) {
|
||||
double entry = 0;
|
||||
for (int k = 0; k < this.nCols(); k++) {
|
||||
entry += this.entry(i, k) * that.entry(k, j);
|
||||
}
|
||||
|
||||
result[i][j] = entry;
|
||||
}
|
||||
}
|
||||
|
||||
return new Matrix(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add this matrix to that and returns the result. (Return value is this + that)
|
||||
* @param that the matrix to add this matrix to.
|
||||
* @throws BadDimensionException If the dimension of the two matrices are not identical.
|
||||
* @return The sum of the this and that.
|
||||
*/
|
||||
public Matrix plus(Matrix that) throws UndefinedMatrixOpException {
|
||||
if (this.nRows() != that.nRows() || this.nCols() != this.nRows()) {
|
||||
throw new UndefinedMatrixOpException("Matrix dimensions are not identical", this, that);
|
||||
}
|
||||
|
||||
double[][] result = new double[this.nRows()][this.nCols()];
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
for (int j = 0; j < result[i].length; j++) {
|
||||
result[i][j] = this.entry(i, j) + that.entry(i, j);
|
||||
}
|
||||
}
|
||||
|
||||
return new Matrix(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param theta The rotation angle.
|
||||
* @return The homogeneous rotation matrix for a given value for theta.
|
||||
*/
|
||||
public static Matrix rotationH2D(double theta) {
|
||||
double[][] R = {{Math.cos(theta), -Math.sin(theta), 0}, {Math.sin(theta), Math.cos(theta), 0}, {0, 0, 1}};
|
||||
return new Matrix(R);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param tx The amount to translate in the x direction.
|
||||
* @param ty The amount to translate in the y direction.
|
||||
* @return The matrix representing a translation of tx, ty.
|
||||
*/
|
||||
public static Matrix translationH2D(double tx, double ty) {
|
||||
double[][] T = {{1, 0, tx}, {0, 1, ty}, {0, 0, 1}};
|
||||
return new Matrix(T);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param x The x coordinate
|
||||
* @param y The y coordinate
|
||||
* @return The column matrix representing in homogeneous coordinates the point (x, y).
|
||||
*/
|
||||
public static Matrix vectorH2D(double x, double y) {
|
||||
double[][] V = {{x}, {y}, {1}};
|
||||
return new Matrix(V);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param n The dimension of the matrix. Recall that the identity matrix has 1's for any entry that is in the same row index as its column index, 0's everywhere else.
|
||||
* @return the nxn identity matrix
|
||||
*/
|
||||
public static Matrix identity(int n) {
|
||||
return identity(n, n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the mxn identity matrix which has 1's for every entry at the same row and column index and
|
||||
* 0 for all other entries.
|
||||
* @param m
|
||||
* @param n
|
||||
* @return the mxn identity matrix.
|
||||
*/
|
||||
public static Matrix identity(int m, int n) {
|
||||
|
||||
double[][] result = new double[m][n];
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
result[i][j] = (i == j) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
return new Matrix(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* A little helpful toString() in case you want to print your matrix to System.out
|
||||
*/
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
sb.append(M[i][j]);
|
||||
sb.append('\t');
|
||||
}
|
||||
sb.append('\n');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
141
Orbital-Bodies/Orbit.pde
Normal file
141
Orbital-Bodies/Orbit.pde
Normal file
@@ -0,0 +1,141 @@
|
||||
import java.util.*;
|
||||
import java.awt.*;
|
||||
|
||||
Orbiter sun; // The root orbiter
|
||||
int lastMillis;
|
||||
double[][] originM = {{0},{0},{1}};
|
||||
Matrix origin = new Matrix(originM);
|
||||
|
||||
// A few fun parameters
|
||||
boolean clearBackground = true;
|
||||
double speedModifier = 1.0; // Set in some of the scenes to change the speed.
|
||||
|
||||
// One default scene (selected in the setup() function
|
||||
void setupScene1() {
|
||||
|
||||
sun = new Orbiter(null, 0, 0, 0, Orbiter.Type.CIRCLE, Color.yellow);
|
||||
|
||||
Orbiter earth = new Orbiter(sun, 50, 0, 1, Orbiter.Type.CIRCLE, Color.blue);
|
||||
Orbiter moon = new Orbiter(earth, 30, 0, 1, Orbiter.Type.CIRCLE, Color.gray);
|
||||
Orbiter moonSatellite = new Orbiter(moon, 20, 0, 1, Orbiter.Type.CIRCLE, Color.gray);
|
||||
|
||||
Orbiter jupiter = new Orbiter(sun, 200, 0, 0.5, Orbiter.Type.CIRCLE, Color.red);
|
||||
Orbiter jupiterMoon = new Orbiter(jupiter, 75, 0, 2, Orbiter.Type.CIRCLE, Color.green);
|
||||
Orbiter jupiterExplorer = new Orbiter(jupiterMoon, 40, 0, -1, Orbiter.Type.SQUARE, Color.orange);
|
||||
Orbiter jupiterExplorerRobot = new Orbiter(jupiterExplorer, 20, 0, -3, Orbiter.Type.TRIANGLE, Color.magenta);
|
||||
}
|
||||
|
||||
// A second default scene
|
||||
void setupScene2() {
|
||||
speedModifier = 0.25;
|
||||
sun = new Orbiter(null, 0, 0, 0, Orbiter.Type.TRIANGLE, Color.yellow);
|
||||
|
||||
Orbiter earth = new Orbiter(sun, 50, 0, 10, Orbiter.Type.TRIANGLE, Color.blue);
|
||||
Orbiter moon = new Orbiter(earth, 30, 0, 20, Orbiter.Type.TRIANGLE, Color.gray);
|
||||
Orbiter moonSatellite = new Orbiter(moon, 20, 0, 30, Orbiter.Type.TRIANGLE, Color.gray);
|
||||
|
||||
Orbiter jupiter = new Orbiter(sun, 200, 0, 5, Orbiter.Type.TRIANGLE, Color.red);
|
||||
Orbiter jupiterMoon = new Orbiter(jupiter, 75, 0, 2, Orbiter.Type.TRIANGLE, Color.green);
|
||||
Orbiter jupiterExplorer = new Orbiter(jupiterMoon, 40, 0, 8, Orbiter.Type.TRIANGLE, Color.orange);
|
||||
Orbiter jupiterExplorerRobot = new Orbiter(jupiterExplorer, 20, 0, -6, Orbiter.Type.TRIANGLE, Color.magenta);
|
||||
}
|
||||
|
||||
// The setup. You don't need to edit this other than to switch scenes by commenting out
|
||||
// the setupScene1() and uncommenting setupScene2().
|
||||
void setup() {
|
||||
size(800, 800);
|
||||
background(0);
|
||||
setupScene1();
|
||||
//setupScene2(); // Run this one with clearBackground set to false
|
||||
lastMillis = millis();
|
||||
}
|
||||
|
||||
// The draw function
|
||||
// DO NOT EDIT
|
||||
void draw() {
|
||||
if (clearBackground) background(0); // Make the background black.
|
||||
|
||||
int currentMillis = millis(); // Get the current number of milliseconds
|
||||
int elapsedMillis = currentMillis - lastMillis; // Get the number of milliseconds elapsed since last call
|
||||
double timeDelta = elapsedMillis / 1000.0;
|
||||
|
||||
updateOrbiters(timeDelta * speedModifier);
|
||||
pushMatrix();
|
||||
scale(1, -1);
|
||||
translate(width / 2, - height / 2);
|
||||
drawOrbiters();
|
||||
popMatrix();
|
||||
|
||||
lastMillis = currentMillis;
|
||||
}
|
||||
|
||||
void updateOrbiters(double timeDelta) {
|
||||
Queue<Orbiter> queue = new LinkedList<Orbiter>();
|
||||
queue.add(sun);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
Orbiter node = queue.remove();
|
||||
node.updateRotation(timeDelta);
|
||||
queue.addAll(node.getChildren());
|
||||
}
|
||||
// TODO
|
||||
// This code should traverse the orbiters (in BFS or DFS, but I used BFS)
|
||||
// order using a stack or a queue (your choice), and call updateRotation
|
||||
// on each one using the timeDelta parameter.
|
||||
//
|
||||
// Recall that Java has a Queue<T> data type and a Stack<T> interface
|
||||
|
||||
}
|
||||
|
||||
void drawOrbiters() {
|
||||
Queue<Orbiter> queue = new LinkedList<Orbiter>();
|
||||
queue.add(sun);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
Orbiter node = queue.remove();
|
||||
drawOrbiter(node);
|
||||
queue.addAll(node.getChildren());
|
||||
}
|
||||
|
||||
// TODO
|
||||
// This code should traverse the orbiters (in BFS or DFS order, i used BFS)
|
||||
// and call drawOrbiter on each orbiter.
|
||||
|
||||
}
|
||||
|
||||
// The code for drawing an orbiter. This is called from your drawOrbiters() method
|
||||
// but you should not have to edit it.
|
||||
void drawOrbiter(Orbiter orbiter) {
|
||||
try {
|
||||
Matrix position = orbiter.getMatrix().dot(origin);
|
||||
|
||||
int px = (int) Math.round(position.entry(0,0) / position.entry(2,0));
|
||||
int py = (int) Math.round(position.entry(1,0) / position.entry(2,0));
|
||||
|
||||
// Draw the orbiter
|
||||
noStroke();
|
||||
fill(orbiter.getFillColor().getRed(), orbiter.getFillColor().getGreen(), orbiter.getFillColor().getBlue());
|
||||
switch (orbiter.getType()) {
|
||||
case CIRCLE:
|
||||
ellipse(px, py, 16, 16);
|
||||
break;
|
||||
case SQUARE:
|
||||
rect(px-4, py-4, 8, 8);
|
||||
break;
|
||||
case TRIANGLE:
|
||||
triangle(px, py+3, px-2, py-1, px+2, py-1);
|
||||
break;
|
||||
}
|
||||
noFill();
|
||||
|
||||
// Draw the orbit path
|
||||
if (clearBackground) {
|
||||
stroke(60);
|
||||
for (Orbiter child : orbiter.getChildren()) {
|
||||
int radius = (int) (2*child.getOrbitRadius());
|
||||
ellipse(px, py, radius, radius);
|
||||
}
|
||||
}
|
||||
} catch (UndefinedMatrixOpException umoe) {
|
||||
}
|
||||
}
|
||||
69
Orbital-Bodies/Orbiter.java
Normal file
69
Orbital-Bodies/Orbiter.java
Normal file
@@ -0,0 +1,69 @@
|
||||
import java.awt.Color;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* An Orbiter is an object that orbits some other object, called its parent.
|
||||
* The center of an orbital system is an Orbiter with no parent.
|
||||
* Each Orbiter may have child Oribters that orbit it.
|
||||
*
|
||||
* An Orbiter stores its orbital radius and current orbit angle.
|
||||
*/
|
||||
|
||||
public class Orbiter {
|
||||
|
||||
public enum Type {
|
||||
CIRCLE, SQUARE, TRIANGLE
|
||||
}
|
||||
|
||||
private final double orbitRadius;
|
||||
private final Type type;
|
||||
private final Color fillColor;
|
||||
private double orbitAngle;
|
||||
private double orbitSpeed;
|
||||
|
||||
private final List<Orbiter> children = new LinkedList<Orbiter>();
|
||||
private final Orbiter parent;
|
||||
|
||||
public Orbiter(Orbiter parent, double orbitRadius, double orbitAngle, double orbitSpeed, Type type, Color fillColor) {
|
||||
this.orbitRadius = orbitRadius;
|
||||
this.orbitAngle = orbitAngle;
|
||||
this.type = type;
|
||||
this.fillColor = fillColor;
|
||||
this.parent = parent;
|
||||
this.orbitSpeed = orbitSpeed;
|
||||
if (parent != null) parent.children.add(this);
|
||||
}
|
||||
|
||||
public double getOrbitRadius() { return orbitRadius; }
|
||||
public double getOrbitAngle() { return orbitAngle; }
|
||||
public Color getFillColor() { return fillColor; }
|
||||
public Type getType() { return type; }
|
||||
public Orbiter getParent() { return parent; }
|
||||
public List<Orbiter> getChildren() { return children; }
|
||||
|
||||
/**
|
||||
* Updates the rotation of this orbiter by the amount specified in the deltaAngle parameter.
|
||||
* @param deltaAngle The amount of rotation angle to add the to the current rotation.
|
||||
*/
|
||||
public void updateRotation(double timeDelta) {
|
||||
orbitAngle += (timeDelta * orbitSpeed);
|
||||
}
|
||||
|
||||
public Matrix getMatrix() throws UndefinedMatrixOpException {
|
||||
if (parent == null) {
|
||||
return Matrix.identity(3);
|
||||
}
|
||||
|
||||
Matrix local = Matrix.rotationH2D(orbitAngle).dot(Matrix.translationH2D(orbitRadius, 0));
|
||||
|
||||
return this.parent.getMatrix().dot(local);
|
||||
|
||||
|
||||
// TODO
|
||||
// If this is the root node, then return the 3x3 identity matrix
|
||||
// If this is not the root node, should return the transformation
|
||||
// matrix for this orbiter (see the writeup for an idea of how to
|
||||
// do this). Make sure you've coded the Matrix class first.
|
||||
|
||||
}
|
||||
}
|
||||
14
Orbital-Bodies/UndefinedMatrixOpException.java
Normal file
14
Orbital-Bodies/UndefinedMatrixOpException.java
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Thrown when a matrix oepration is applied to matrices of the wrong size.
|
||||
*
|
||||
* You don't need to edit this.
|
||||
*/
|
||||
|
||||
public class UndefinedMatrixOpException extends Exception {
|
||||
|
||||
|
||||
public UndefinedMatrixOpException(String message, Matrix m1, Matrix m2) {
|
||||
super(message + "\nMatrix 1: " + m1 + "\n\nMatrix 2: " + m2);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user