├── .gitattributes
├── .gitignore
├── BankersAlgorithm
├── .idea
│ ├── compiler.xml
│ ├── copyright
│ │ └── profiles_settings.xml
│ ├── misc.xml
│ ├── modules.xml
│ └── workspace.xml
├── BankersAlgorithm.iml
├── README.md
├── inputFiles
│ ├── input1.txt
│ ├── input10.txt
│ ├── input11.txt
│ ├── input12.txt
│ ├── input13.txt
│ ├── input2.txt
│ ├── input3.txt
│ ├── input4.txt
│ ├── input5.txt
│ ├── input6.txt
│ ├── input7.txt
│ ├── input8.txt
│ └── input9.txt
└── src
│ └── bankersAlgorithm
│ ├── Activity.java
│ ├── BankersAlgorithm.java
│ └── Process.java
├── DemandPaging
├── Main.java
├── Page.java
├── Process.java
├── README
└── random-numbers.txt
├── DualPassLinker
├── .classpath
├── .project
├── .settings
│ └── org.eclipse.jdt.core.prefs
├── inputFiles
│ ├── input1.txt
│ ├── input2.txt
│ ├── input3.txt
│ ├── input4.txt
│ ├── input5.txt
│ ├── input6.txt
│ ├── input7.txt
│ └── input8.txt
└── src
│ └── linker
│ ├── Linker.java
│ ├── Module.java
│ ├── README.txt
│ ├── SymbolTable.java
│ ├── Variable.java
│ ├── input2.txt
│ ├── input3.txt
│ ├── input4.txt
│ ├── input5.txt
│ ├── input6.txt
│ ├── input7.txt
│ └── input8.txt
├── Homework1
├── .classpath
├── .project
└── .settings
│ └── org.eclipse.jdt.core.prefs
├── Homework2
├── .classpath
├── .project
├── .settings
│ └── org.eclipse.jdt.core.prefs
├── Homework 2.pdf
├── README.md
└── src
│ └── project2
│ ├── DirectorySize.java
│ └── FileOnDisk.java
├── Homework3
├── .classpath
├── .project
├── .settings
│ └── org.eclipse.jdt.core.prefs
├── Homework 3.pdf
├── README.md
└── src
│ └── project3
│ ├── Homework 3.pdf
│ ├── InsertionSort.java
│ ├── MergeSort.java
│ ├── QuickSort.java
│ ├── SelectionSort.java
│ ├── SortTester.java
│ └── Sorter.java
├── Homework4
├── .classpath
├── .project
├── .settings
│ └── org.eclipse.jdt.core.prefs
├── README.md
├── bin
│ ├── BW_Pattern.png
│ ├── CT_image.jpg
│ ├── ChessBoard.png
│ ├── Gray_Pattern.jpg
│ ├── Head_CT_scan.jpg
│ ├── Lighthouse.jpg
│ ├── brain_image_MRI.jpg
│ ├── cameraman.jpg
│ ├── hubble1.png
│ ├── lightning_bolt.jpg
│ └── pollen.jpg
└── src
│ ├── BW_Pattern.png
│ ├── CT_image.jpg
│ ├── ChessBoard.png
│ ├── Gray_Pattern.jpg
│ ├── Head_CT_scan.jpg
│ ├── Lighthouse.jpg
│ ├── brain_image_MRI.jpg
│ ├── cameraman.jpg
│ ├── hubble1.png
│ ├── lightning_bolt.jpg
│ ├── pollen.jpg
│ └── proj4
│ ├── Homework 4.pdf
│ ├── NewQueue.java
│ ├── NewStack.java
│ ├── Node.java
│ ├── RegionGrowing.java
│ └── Test.java
├── Homework5
├── .classpath
├── .project
├── .settings
│ └── org.eclipse.jdt.core.prefs
├── Homework 5.pdf
├── README.md
├── Tarzan.txt
├── bin
│ └── Tarzan.txt
├── output
└── src
│ ├── Tarzan.txt
│ └── project5
│ ├── BSTNode.java
│ ├── BinarySearchTree.java
│ ├── FileParser.java
│ ├── Homework 5.pdf
│ ├── MostFrequentWords.java
│ ├── SLLNode.java
│ └── SortedLinkedList.java
└── OSLab2Scheduler
├── .classpath
├── .project
├── .settings
└── org.eclipse.jdt.core.prefs
├── FCFS
├── input1.txt
├── input2.txt
├── input3.txt
├── input4.txt
├── input5.txt
├── input6.txt
└── input7.txt
├── random-numbers
└── src
└── scheduler
├── Process.java
├── README.txt
└── Scheduler.java
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 |
7 | # Standard to msysgit
8 | *.doc diff=astextplain
9 | *.DOC diff=astextplain
10 | *.docx diff=astextplain
11 | *.DOCX diff=astextplain
12 | *.dot diff=astextplain
13 | *.DOT diff=astextplain
14 | *.pdf diff=astextplain
15 | *.PDF diff=astextplain
16 | *.rtf diff=astextplain
17 | *.RTF diff=astextplain
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Mobile Tools for Java (J2ME)
4 | .mtj.tmp/
5 |
6 | # Package Files #
7 | *.jar
8 | *.war
9 | *.ear
10 |
11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12 | hs_err_pid*
13 |
14 | # =========================
15 | # Operating System Files
16 | # =========================
17 |
18 | # OSX
19 | # =========================
20 |
21 | .DS_Store
22 | .AppleDouble
23 | .LSOverride
24 |
25 | # Thumbnails
26 | ._*
27 |
28 | # Files that might appear in the root of a volume
29 | .DocumentRevisions-V100
30 | .fseventsd
31 | .Spotlight-V100
32 | .TemporaryItems
33 | .Trashes
34 | .VolumeIcon.icns
35 |
36 | # Directories potentially created on remote AFP share
37 | .AppleDB
38 | .AppleDesktop
39 | Network Trash Folder
40 | Temporary Items
41 | .apdisk
42 |
43 | # Windows
44 | # =========================
45 |
46 | # Windows image file caches
47 | Thumbs.db
48 | ehthumbs.db
49 |
50 | # Folder config file
51 | Desktop.ini
52 |
53 | # Recycle Bin used on file shares
54 | $RECYCLE.BIN/
55 |
56 | # Windows Installer files
57 | *.cab
58 | *.msi
59 | *.msm
60 | *.msp
61 |
62 | # Windows shortcuts
63 | *.lnk
64 |
--------------------------------------------------------------------------------
/BankersAlgorithm/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/BankersAlgorithm/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/BankersAlgorithm/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/BankersAlgorithm/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/BankersAlgorithm/BankersAlgorithm.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/BankersAlgorithm/README.md:
--------------------------------------------------------------------------------
1 | Kevin Naughton Jr.
2 | Operating Banker's Lab
3 |
4 |
5 | COMPILE
6 | In terminal, navigate to the directory that contains BankersAlgorithm.java, Process.java, Activity.java and the input files. Once you are in the correct directory, run the following command to compile the program:
7 | javac bankersAlgorithm/BankersAlgorithm.java
8 |
9 | RUN
10 | Run the following command where “ABSOLUTE_PATH_TO_INPUT_FILE” is the absolute path to the desired input file:
11 | java bankersAlgorithm.BankersAlgorithm ABSOLUTE_PATH_TO_INPUT_FILE
12 |
13 | EXAMPLE
14 |
15 | RUN
16 | javac bankersAlgorithm/BankersAlgorithm.java
17 | java bankersAlgorithm.BankersAlgorithm kdn251/input1.txt
18 |
19 | ARBITRARY LIMITS
20 | Tasks <= 10
21 | Activities <= 30
22 | Resource Types <= 10
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input1.txt:
--------------------------------------------------------------------------------
1 | 2 1 4
2 | initiate 1 1 4
3 | request 1 1 1
4 | release 1 1 1
5 | terminate 1 0 0
6 | initiate 2 1 4
7 | request 2 1 1
8 | release 2 1 1
9 | terminate 2 0 0
10 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input10.txt:
--------------------------------------------------------------------------------
1 | 2 2 2 2
2 | initiate 1 1 2
3 | initiate 1 2 2
4 | request 1 1 1
5 | request 1 1 1
6 | request 1 2 1
7 | release 1 1 2
8 | release 1 2 1
9 | terminate 1 0 0
10 |
11 | initiate 2 1 2
12 | initiate 2 2 2
13 | request 2 1 1
14 | request 2 1 1
15 | request 2 2 1
16 | release 2 1 2
17 | release 2 2 1
18 | terminate 2 0 0
19 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input11.txt:
--------------------------------------------------------------------------------
1 | 3 3 4 4 4
2 | initiate 1 1 4
3 | initiate 1 2 4
4 | initiate 1 3 4
5 | request 1 1 1
6 | release 1 1 1
7 | request 1 1 3
8 | request 1 2 1
9 | release 1 2 1
10 | release 1 1 3
11 | terminate 1 0 0
12 | initiate 2 1 4
13 | initiate 2 2 4
14 | initiate 2 3 4
15 | request 2 1 4
16 | request 2 2 1
17 | request 2 3 1
18 | release 2 1 4
19 | release 2 2 1
20 | release 2 3 1
21 | terminate 2 0 0
22 | initiate 3 1 4
23 | initiate 3 2 4
24 | initiate 3 3 4
25 | request 3 1 4
26 | request 3 3 1
27 | release 3 3 1
28 | release 3 1 4
29 | terminate 3 0 0
30 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input12.txt:
--------------------------------------------------------------------------------
1 | 2 1 4
2 | initiate 1 1 4
3 | request 1 1 1
4 | compute 1 3 0
5 | release 1 1 1
6 | compute 1 1 0
7 | terminate 1 0 0
8 | initiate 2 1 4
9 | compute 2 2 0
10 | request 2 1 1
11 | compute 2 1 0
12 | release 2 1 1
13 | terminate 2 0 0
14 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input13.txt:
--------------------------------------------------------------------------------
1 | 2 1 4
2 | initiate 1 1 4
3 | compute 1 5 0
4 | request 1 1 1
5 | compute 1 5 0
6 | release 1 1 1
7 | compute 1 5 0
8 | terminate 1 0 0
9 | initiate 2 1 4
10 | compute 2 5 0
11 | request 2 1 1
12 | compute 2 5 0
13 | release 2 1 1
14 | compute 2 5 0
15 | terminate 2 0 0
16 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input2.txt:
--------------------------------------------------------------------------------
1 | 2 1 4
2 |
3 | initiate 1 1 4
4 | request 1 1 1
5 | request 1 1 3
6 | release 1 1 4
7 | terminate 1 0 0
8 |
9 | initiate 2 1 4
10 | request 2 1 1
11 | request 2 1 3
12 | release 2 1 4
13 | terminate 2 0 0
14 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input3.txt:
--------------------------------------------------------------------------------
1 | 3 1 4
2 | initiate 1 1 4
3 | request 1 1 1
4 | request 1 1 3
5 | release 1 1 4
6 | terminate 1 0 0
7 |
8 | initiate 2 1 4
9 | request 2 1 1
10 | request 2 1 3
11 | release 2 1 4
12 | terminate 2 0 0
13 |
14 | initiate 3 1 4
15 | request 3 1 1
16 | request 3 1 3
17 | release 3 1 4
18 | terminate 3 0 0
19 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input4.txt:
--------------------------------------------------------------------------------
1 | 2 1 4
2 | initiate 1 1 4
3 | request 1 1 1
4 | request 1 1 3
5 | release 1 1 4
6 | request 1 1 2
7 | release 1 1 2
8 | terminate 1 0 0
9 | initiate 2 1 4
10 | request 2 1 1
11 | request 2 1 3
12 | release 2 1 4
13 | terminate 2 0 0
14 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input5.txt:
--------------------------------------------------------------------------------
1 | 3 1 4
2 | initiate 1 1 3
3 | request 1 1 1
4 | release 1 1 1
5 | request 1 1 3
6 | release 1 1 3
7 | terminate 1 0 0
8 | initiate 2 1 3
9 | request 2 1 1
10 | request 2 1 1
11 | release 2 1 2
12 | terminate 2 0 0
13 | initiate 3 1 3
14 | request 3 1 2
15 | request 3 1 1
16 | release 3 1 3
17 | terminate 3 0 0
18 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input6.txt:
--------------------------------------------------------------------------------
1 | 4 1 4
2 | initiate 1 1 3
3 | request 1 1 1
4 | release 1 1 1
5 | request 1 1 3
6 | release 1 1 3
7 | terminate 1 0 0
8 | initiate 2 1 3
9 | request 2 1 1
10 | request 2 1 1
11 | release 2 1 2
12 | terminate 2 0 0
13 | initiate 3 1 5
14 | request 3 1 2
15 | request 3 1 1
16 | release 3 1 3
17 | terminate 3 0 0
18 | initiate 4 1 3
19 | request 4 1 2
20 | request 4 1 1
21 | release 4 1 3
22 | terminate 4 0 0
23 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input7.txt:
--------------------------------------------------------------------------------
1 | 3 1 4
2 | initiate 1 1 3
3 | request 1 1 1
4 | release 1 1 1
5 | request 1 1 3
6 | release 1 1 3
7 | terminate 1 0 0
8 |
9 | initiate 2 1 3
10 | request 2 1 1
11 | request 2 1 1
12 | request 2 1 2
13 | release 2 1 2
14 | release 2 1 2
15 | terminate 2 0 0
16 |
17 | initiate 3 1 3
18 | request 3 1 2
19 | request 3 1 1
20 | release 3 1 3
21 | terminate 3 0 0
22 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input8.txt:
--------------------------------------------------------------------------------
1 | 2 1 4
2 | initiate 1 1 4
3 | request 1 1 1
4 | initiate 2 1 4
5 | request 2 1 1
6 | release 1 1 1
7 | release 2 1 1
8 | terminate 1 0 0
9 | terminate 2 0 0
10 |
--------------------------------------------------------------------------------
/BankersAlgorithm/inputFiles/input9.txt:
--------------------------------------------------------------------------------
1 | 2 2 4 4
2 |
3 | initiate 1 1 4
4 | initiate 1 2 4
5 | request 1 1 1
6 | request 1 2 1
7 | release 1 1 1
8 | release 1 2 1
9 | terminate 1 0 0
10 |
11 | initiate 2 1 4
12 | initiate 2 2 4
13 | request 2 1 1
14 | request 2 2 1
15 | release 2 1 1
16 | release 2 2 1
17 | terminate 2 0 0
18 |
--------------------------------------------------------------------------------
/BankersAlgorithm/src/bankersAlgorithm/Activity.java:
--------------------------------------------------------------------------------
1 | package bankersAlgorithm;
2 |
3 | public class Activity {
4 | // declare process number attribute
5 | protected int processNumber;
6 | // declare activity type attribute
7 | protected String activityType;
8 | //declare resource type attribute
9 | protected int resourceType;
10 | //declare info attribute
11 | protected int info;
12 |
13 | public Activity(String activityType, int processNumber, int resourceType, int info) {
14 | //initialize process number attribute
15 | this.processNumber = processNumber;
16 | //initialize resource type attribute
17 | this.resourceType = resourceType;
18 | //initialize info attribute
19 | this.info = info;
20 |
21 | //initialize activity object accordingly
22 | switch (activityType) {
23 | case "initiate":
24 | this.activityType = "initiate";
25 | break;
26 | case "request":
27 | this.activityType = "request";
28 | break;
29 | case "release":
30 | this.activityType = "release";
31 | break;
32 | case "compute":
33 | this.activityType = "compute";
34 | this.info = resourceType;
35 | break;
36 | case "terminate":
37 | this.activityType = "terminate";
38 | break;
39 | default:
40 | break;
41 | }
42 | }
43 |
44 | //getter for process number attribute
45 | public int getProcessNumber() {
46 | return this.processNumber;
47 | }
48 |
49 | //getter for activity attribute
50 | public String getActivityType() {
51 | return this.activityType;
52 | }
53 |
54 | //getter for info attribute
55 | public int getInfo() {
56 | return this.info;
57 | }
58 |
59 | //toString method used for debugging
60 | @Override
61 | public String toString(){
62 | switch (this.activityType){
63 | case "initiate":
64 | return this.activityType +" "+ this.processNumber +" "+ this.resourceType +" "+ this.info;
65 | case "request":
66 | return this.activityType +" "+ this.processNumber +" "+ this.resourceType +" "+ this.info;
67 | case "release":
68 | return this.activityType +" "+ this.processNumber +" "+ this.resourceType +" "+ this.info;
69 | case "compute":
70 | return this.activityType +" "+ this.processNumber +" "+ this.info;
71 | case "terminate":
72 | return this.activityType +" "+ this.processNumber ;
73 | default:
74 | return "";
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/BankersAlgorithm/src/bankersAlgorithm/BankersAlgorithm.java:
--------------------------------------------------------------------------------
1 | package bankersAlgorithm;
2 | import java.io.File;
3 | import java.util.ArrayList;
4 | import java.util.Scanner;
5 | import java.util.Stack;
6 |
7 | public class BankersAlgorithm {
8 | // declare global variables
9 | static int NUMBER_OF_TASKS;
10 | static int NUMBER_OF_RESOURCE_TYPES;
11 | static int[] resources;
12 | static ArrayList processes;
13 |
14 | public static void main(String[] args) {
15 | Scanner scanner = initializeScanner(args);
16 |
17 | // read input and initialize processes
18 | processes = readInput(scanner);
19 |
20 | // initialize optimistic processes array list
21 | ArrayList optimisticProcesses = new ArrayList();
22 |
23 | // print processes
24 | //printProcesses(processes);
25 |
26 | try {
27 | // run optimisti cc manager on all processes
28 | optimisticProcesses = optimisticManager(processes);
29 | }
30 |
31 | catch(Exception exception) {
32 | System.out.println();
33 | System.out.println("Please go easy on me. :)");
34 | System.out.println();
35 | }
36 |
37 | // print the result of running the optimistic manager
38 | printOptimisticManager(optimisticProcesses);
39 |
40 | // reinitialize scanner
41 | scanner = initializeScanner(args);
42 |
43 | // reread input
44 | processes = readInput(scanner);
45 |
46 | // store processes in bankers processes array list
47 | ArrayList bankersProcesses = new ArrayList();
48 |
49 | try {
50 | // run Dijkstra' banker's algorithm
51 | bankersProcesses = bankersAlgorithm(processes);
52 | }
53 |
54 | catch (Exception exception) {
55 | System.out.println();
56 | System.out.println("Please go easy on me. :)");
57 | System.out.println();
58 | }
59 |
60 | // print the results of running Dijkstra's banker's algorithm
61 | printBankersAlgorithm(bankersProcesses);
62 | }
63 |
64 | private static void printBankersAlgorithm(ArrayList bankersProcesses) {
65 | // print header
66 | System.out.println(String.format("%17s", "Banker's"));
67 |
68 | // initialize total run time to zero
69 | int totalRunTime = 0;
70 |
71 | // initialize total wait time to zero
72 | int totalWaitTime = 0;
73 |
74 | // iterate through all processes
75 | for (int i = 0; i < bankersProcesses.size(); i++) {
76 | // if the current process was aborted as a result of a deadlock...
77 | if (bankersProcesses.get(i).aborted) {
78 | System.out.println("Task " + (i + 1) + "\t\taborted");
79 | }
80 | // if the current process successfully terminated
81 | else {
82 | // increment total time taken
83 | totalRunTime += bankersProcesses.get(i).timeTaken;
84 |
85 | // increment total wait time
86 | totalWaitTime += bankersProcesses.get(i).waitTime;
87 |
88 | // print output for current task
89 | System.out.format("Task " + (bankersProcesses.get(i).number) + "\t\t%d\t%d\t%.0f%s",
90 | bankersProcesses.get(i).timeTaken, bankersProcesses.get(i).waitTime,
91 | ((float) bankersProcesses.get(i).waitTime / (float) bankersProcesses.get(i).timeTaken) * 100,
92 | "%");
93 | System.out.println();
94 | }
95 | }
96 |
97 | // print total runtime, total wait time, and overall percentage spent
98 | // waiting
99 | System.out.format("total \t\t%d\t%d\t%.0f%s", totalRunTime, totalWaitTime,
100 | ((float) totalWaitTime / (float) totalRunTime * 100), "%");
101 |
102 | // print line breaks
103 | System.out.println();
104 | System.out.println();
105 | }
106 |
107 | private static ArrayList bankersAlgorithm(ArrayList bankersProcesses) {
108 | // initialize array list of finished processes
109 | ArrayList finishedProcesses = new ArrayList();
110 |
111 | // iterate through all processes checking if any process' initial claims
112 | // exceeds the total number of any resource
113 | for (int i = 0; i < bankersProcesses.size(); i++) {
114 | // iterate through current process' claim array
115 | for (int j = 0; j < bankersProcesses.get(i).claim.length; j++) {
116 | // if the claim exceeds a specific resource...
117 | if (bankersProcesses.get(i).claim[j] > resources[j]) {
118 | // print informative error messages
119 | System.out.println("Banker aborts task " + bankersProcesses.get(i).number + " before run begins:");
120 | System.out.println(" claim for resource " + (j + 1) + " (" + bankersProcesses.get(i).claim[j]
121 | + ") exceeds number of units present " + "(" + resources[j] + ")");
122 |
123 | // abort the current process
124 | bankersProcesses.get(i).aborted = true;
125 |
126 | // remove current process from bankers processes
127 | bankersProcesses.remove(bankersProcesses.get(i));
128 |
129 | // add the current process to finished process list
130 | finishedProcesses.add(bankersProcesses.get(i));
131 |
132 | // decrement i
133 | i--;
134 | }
135 | }
136 | }
137 |
138 | // initialize cycle
139 | int cycle = 0;
140 |
141 | // initialize index variable
142 | int i = 0;
143 |
144 | // store initial size of processes
145 | int processesSize = bankersProcesses.size();
146 |
147 | // initialize wait queue for requests that cannot be processed at a
148 | // particular cycle
149 | ArrayList waitQueue = new ArrayList();
150 |
151 | // initialize buffer to hold resources released at cycle n to make them
152 | // available at cycle n + 1
153 | int[] resourceBuffer = new int[NUMBER_OF_RESOURCE_TYPES];
154 |
155 | // continue while all processes have not terminated or deadlock has not
156 | // occurred
157 | while (finishedProcesses.size() != processesSize) {
158 | // loop through all processes
159 | while (i < bankersProcesses.size()) {
160 | //if the process is computing...
161 | if (bankersProcesses.get(i).computing > 0) {
162 | // decrement current process' remaining computing time
163 | bankersProcesses.get(i).computing--;
164 |
165 | // increment i
166 | i++;
167 | }
168 | else {
169 | // store current activity
170 | Activity currentActivity = bankersProcesses.get(i).activities.get(0);
171 |
172 | // process the current activity based on its type
173 | switch (currentActivity.activityType) {
174 | case "initiate":
175 | // remove the current activity
176 | bankersProcesses.get(i).activities.remove(0);
177 | break;
178 | case "request":
179 | // add back resources that were released during the
180 | // previous cycle
181 | for (int k = 0; k < resourceBuffer.length; k++) {
182 | resources[k] += resourceBuffer[k];
183 | resourceBuffer[k] = 0;
184 | }
185 |
186 | if ((bankersProcesses.get(i).resources[currentActivity.resourceType - 1] + currentActivity.info) > bankersProcesses.get(i).claim[currentActivity.resourceType- 1]) {
187 | bankersProcesses.get(i).aborted = true;
188 | for (int k = 0; k < bankersProcesses.get(i).resources.length; k++) {
189 | System.out.println("During cycle " + cycle + "-" + (cycle + 1) + " of Banker's algorithm " + "Task " + bankersProcesses.get(i).number
190 | + "'s request exceeds its claim");
191 | resourceBuffer[k] += bankersProcesses.get(i).resources[k];
192 | bankersProcesses.get(i).resources[k] = 0;
193 | }
194 |
195 | finishedProcesses.add(bankersProcesses.get(i));
196 | bankersProcesses.remove(bankersProcesses.get(i));
197 | i--;
198 | }
199 | else {
200 | // check if the state would be safe if the current
201 | // request is granted
202 | boolean safe = isSafe(bankersProcesses.get(i), bankersProcesses, waitQueue, finishedProcesses);
203 |
204 | // if the state would be safe..
205 | if (safe) {
206 | // grant the request of the current process
207 | bankersProcesses.get(i).resources[currentActivity.resourceType
208 | - 1] += currentActivity.info;
209 | resources[currentActivity.resourceType - 1] -= currentActivity.info;
210 |
211 | // remove the current activity
212 | bankersProcesses.get(i).activities.remove(0);
213 | break;
214 | }
215 | // if the state would not be safe...
216 | else {
217 | // add the current process to the wait queue
218 | waitQueue.add(bankersProcesses.get(i));
219 | bankersProcesses.remove(bankersProcesses.get(i));
220 |
221 | //decrement i
222 | i--;
223 | break;
224 | }
225 | }
226 |
227 | case "release":
228 | // place resource to be released into the resource
229 | // buffer
230 | resourceBuffer[currentActivity.resourceType - 1] += currentActivity.info;
231 |
232 | // decrement the resource count of the resource that the
233 | // current process is releasing
234 | bankersProcesses.get(i).resources[currentActivity.resourceType - 1] -= currentActivity.info;
235 |
236 | // remove the current activity
237 | bankersProcesses.get(i).activities.remove(0);
238 | break;
239 | case "compute":
240 | // set current process' computing time
241 | bankersProcesses.get(i).computing = currentActivity.info - 1;
242 |
243 | // remove the current activity
244 | bankersProcesses.get(i).activities.remove(0);
245 | break;
246 | case "terminate":
247 | // set current process' time taken to the current cycle
248 | bankersProcesses.get(i).timeTaken = cycle;
249 |
250 | // update terminated processes count
251 | finishedProcesses.add(bankersProcesses.get(i));
252 |
253 | // release all of current process' resources
254 | for (int k = 0; k < bankersProcesses.get(i).resources.length; k++) {
255 | resourceBuffer[k] += bankersProcesses.get(i).resources[k];
256 | bankersProcesses.get(i).resources[k] = 0;
257 | }
258 |
259 | // remove the current activity
260 | bankersProcesses.get(i).activities.remove(0);
261 |
262 | // remove current process
263 | bankersProcesses.remove(i);
264 |
265 | // decrement i
266 | i--;
267 | break;
268 | }
269 |
270 | // increment i
271 | i++;
272 | }
273 | }
274 |
275 | // reset i to zero
276 | i = 0;
277 |
278 | // increment cycle
279 | cycle++;
280 |
281 | // increment wait time of all processes on wait queue
282 | incrementWaitTime(waitQueue);
283 |
284 | // check if any processes on the wait queue's requests can be
285 | // satisfied
286 | checkWaitQueueBankers(bankersProcesses, waitQueue);
287 | }
288 |
289 | // return the array list of finished processes
290 | return finishedProcesses;
291 | }
292 |
293 | private static boolean isSafe(Process currentProcess, ArrayList bankersProcesses,
294 | ArrayList waitQueue, ArrayList finishedProcesses) {
295 | // initialize bankers processes copy
296 | ArrayList bankersProcessesCopy = new ArrayList();
297 |
298 | // initialize resources copy
299 | int[] resourcesCopy = new int[NUMBER_OF_RESOURCE_TYPES];
300 |
301 | // initialize wait queue copy
302 | ArrayList waitQueueCopy = new ArrayList();
303 |
304 | // initialize finished processes copy
305 | ArrayList finishedProcessesCopy = new ArrayList();
306 |
307 | // copy each process from bankers processes and add them to bankers
308 | // processes copy
309 | for (int i = 0; i < bankersProcesses.size(); i++) {
310 | bankersProcessesCopy.add(new Process(bankersProcesses.get(i)));
311 | }
312 |
313 | // copy each resource to the resources copy
314 | for (int i = 0; i < resources.length; i++) {
315 | resourcesCopy[i] = resources[i];
316 | }
317 |
318 | // copy each process in the wait queue to wait queue copy
319 | for (int i = 0; i < waitQueue.size(); i++) {
320 | waitQueueCopy.add(waitQueue.get(i));
321 | }
322 |
323 | // copy each process to the finished processes copy
324 | for (int i = 0; i < finishedProcesses.size(); i++) {
325 | finishedProcessesCopy.add(finishedProcesses.get(i));
326 | }
327 |
328 | for (int i = 0; i < bankersProcessesCopy.size(); i++) {
329 | for (int j = 0; j < bankersProcessesCopy.get(i).resources.length; j++) {
330 | //System.out.println("Resources Copy: " + resourcesCopy[j]);
331 | int largestRequest = bankersProcesses.get(i).claim[j] - bankersProcesses.get(i).resources[j];
332 | if (resourcesCopy[j] - largestRequest < 0) {
333 | return false;
334 | }
335 | }
336 | }
337 |
338 | return true;
339 | }
340 |
341 | private static void checkWaitQueueBankers(ArrayList bankersProcesses, ArrayList waitQueue) {
342 | // initialize stack to hold all processes that are to be removed from
343 | // the wait queue
344 | Stack stack = new Stack();
345 |
346 | // iterate through wait queue pushing all processes on to the stack
347 | for (int i = 0; i < waitQueue.size(); i++) {
348 | stack.push(waitQueue.remove(0));
349 | }
350 |
351 | // add all processes from stack back to the processes list at index zero
352 | while (!stack.isEmpty()) {
353 | bankersProcesses.add(0, stack.pop());
354 | }
355 | }
356 |
357 | private static Scanner initializeScanner(String[] args) {
358 | // initialize scanner to null
359 | Scanner scanner = null;
360 |
361 | try {
362 | // attempt to reinitialize scanner to read first command line
363 | // argument
364 | scanner = new Scanner(new File(args[0]));
365 | }
366 |
367 | // catch all exceptions
368 | catch (Exception exception) {
369 | // print error message
370 | System.out.println("Please ensure that the file is entered as the first command line argument");
371 |
372 | // exit gracefully
373 | System.exit(-1);
374 | }
375 |
376 | //return scanner
377 | return scanner;
378 | }
379 |
380 | private static void printProcesses(ArrayList processes2) {
381 | // iterate through all processes
382 | for (int i = 0; i < processes.size(); i++) {
383 | // print information about the current process
384 | for (int j = 0; j < processes.get(i).getActivities().size(); j++) {
385 | System.out.print(processes.get(i).activities.get(j).activityType + " ");
386 | System.out.print(processes.get(i).activities.get(j).processNumber + " ");
387 | System.out.print(processes.get(i).activities.get(j).resourceType + " ");
388 | System.out.print(processes.get(i).activities.get(j).info);
389 | System.out.println();
390 | }
391 |
392 | // print line break
393 | System.out.println();
394 | }
395 | }
396 |
397 | private static ArrayList readInput(Scanner scanner) {
398 | // initialize array list to hold all processes
399 | ArrayList processes = new ArrayList();
400 |
401 | // initialize number of tasks
402 | NUMBER_OF_TASKS = Integer.parseInt(scanner.next());
403 |
404 | // initialize number of resource types
405 | NUMBER_OF_RESOURCE_TYPES = Integer.parseInt(scanner.next());
406 |
407 | // initialize process objects
408 | for (int i = 0; i < NUMBER_OF_TASKS; i++) {
409 | Process currentProcess = new Process(i + 1, NUMBER_OF_RESOURCE_TYPES);
410 | currentProcess.claim = new int[NUMBER_OF_RESOURCE_TYPES];
411 | processes.add(currentProcess);
412 | }
413 |
414 | // initialize size of resource's array
415 | resources = new int[NUMBER_OF_RESOURCE_TYPES];
416 |
417 | //check arbitrary limits
418 | if(NUMBER_OF_TASKS > 10 || NUMBER_OF_RESOURCE_TYPES > 10) {
419 | System.out.println("Input file does not adhere to the arbitrary limits.");
420 | System.exit(-1);
421 | }
422 |
423 | // initialize number of all resource types
424 | for (int i = 0; i < resources.length; i++) {
425 | resources[i] = Integer.parseInt(scanner.next());
426 | }
427 |
428 | //keep track of the number of activites
429 | int numberOfActivities = 0;
430 |
431 | // initialize each process object
432 | while (scanner.hasNext()) {
433 | // store attributes of the current activity object
434 | String activityType = scanner.next();
435 | int processNumber = Integer.parseInt(scanner.next());
436 | int resourceType = Integer.parseInt(scanner.next());
437 | int info = Integer.parseInt(scanner.next());
438 |
439 | // create new activity object and add it to the current process'
440 | // activities
441 | Activity currentActivity = new Activity(activityType, processNumber, resourceType, info);
442 |
443 | if (currentActivity.activityType.equals("initiate")) {
444 | processes.get(processNumber - 1).claim[currentActivity.resourceType - 1] = currentActivity.info;
445 | }
446 |
447 | processes.get(processNumber - 1).activities.add(currentActivity);
448 |
449 | //increment the number of activites
450 | numberOfActivities++;
451 | }
452 |
453 | //check arbitrary limits
454 | if(numberOfActivities > 30) {
455 | System.out.println("Input file does not adhere to arbitrary limits.");
456 | System.exit(-1);
457 | }
458 |
459 | // return initialize array list
460 | return processes;
461 | }
462 |
463 | private static ArrayList optimisticManager(ArrayList processes) {
464 | // initialize array list of finished processes
465 | ArrayList finishedProcesses = new ArrayList();
466 |
467 | // initialize cycle
468 | int cycle = 0;
469 |
470 | // initialize index variable
471 | int i = 0;
472 |
473 | // store initial size of processes
474 | int processesSize = processes.size();
475 |
476 | // initialize wait queue for requests that cannot be processed at a
477 | // particular cycle
478 | ArrayList waitQueue = new ArrayList();
479 |
480 | // initialize buffer to hold resources released at cycle n to make them
481 | // available at cycle n + 1
482 | int[] resourceBuffer = new int[NUMBER_OF_RESOURCE_TYPES];
483 |
484 | // continue while all processes have not terminated or deadlock has not
485 | // occurred
486 | while (finishedProcesses.size() != processesSize) {
487 | // loop through all processes
488 | while (i < processes.size()) {
489 | if (processes.get(i).computing > 0) {
490 | // decrement current process' remaining computing time
491 | processes.get(i).computing--;
492 |
493 | // increment i
494 | i++;
495 | }
496 | else {
497 | // store current activity
498 | Activity currentActivity = processes.get(i).activities.get(0);
499 |
500 | // process the current activity based on its type
501 | switch (currentActivity.activityType) {
502 | case "initiate":
503 | // remove the current activity
504 | processes.get(i).activities.remove(0);
505 | break;
506 | case "request":
507 | // if we are not able to satisfy the current process'
508 | // request...
509 | if (resources[currentActivity.resourceType - 1] < currentActivity.info) {
510 | // add current process to wait queue
511 | waitQueue.add(processes.get(i));
512 |
513 | // remove current process from list of processes
514 | processes.remove(i);
515 |
516 | // decrement i
517 | i--;
518 | break;
519 | }
520 | // we are able to satisfy the current process' request
521 | else {
522 | // redistribute resource
523 | processes.get(i).resources[currentActivity.resourceType - 1] += currentActivity.info;
524 | resources[currentActivity.resourceType - 1] -= currentActivity.info;
525 |
526 | // remove the current activity
527 | processes.get(i).activities.remove(0);
528 | break;
529 | }
530 | case "release":
531 | // place resource to be released into the resource
532 | // buffer
533 | resourceBuffer[currentActivity.resourceType - 1] += currentActivity.info;
534 |
535 | // decrement the resource count of the resource that the
536 | // current process is releasing
537 | processes.get(i).resources[currentActivity.resourceType - 1] -= currentActivity.info;
538 |
539 | // remove the current activity
540 | processes.get(i).activities.remove(0);
541 | break;
542 | case "compute":
543 | // set current process' computing time
544 | processes.get(i).computing = currentActivity.info - 1;
545 |
546 | // remove the current activity
547 | processes.get(i).activities.remove(0);
548 | break;
549 | case "terminate":
550 | // set current process' time taken to the current cycle
551 | processes.get(i).timeTaken = cycle;
552 |
553 | // update terminated processes count
554 | finishedProcesses.add(processes.get(i));
555 |
556 | // release all of current process' resources
557 | for (int k = 0; k < processes.get(i).resources.length; k++) {
558 | resourceBuffer[k] += processes.get(i).resources[k];
559 | processes.get(i).resources[k] = 0;
560 | }
561 |
562 | // remove the current activity
563 | processes.get(i).activities.remove(0);
564 |
565 | // remove current process
566 | processes.remove(i);
567 |
568 | // decrement i
569 | i--;
570 | break;
571 | }
572 |
573 | // increment i
574 | i++;
575 | }
576 | }
577 |
578 | // reset i to zero
579 | i = 0;
580 |
581 | // increment cycle
582 | cycle++;
583 |
584 | // increment wait time of all processes on wait queue
585 | incrementWaitTime(waitQueue);
586 |
587 | // add back resources that were released during the previous cycle
588 | for (int k = 0; k < resourceBuffer.length; k++) {
589 | resources[k] += resourceBuffer[k];
590 | resourceBuffer[k] = 0;
591 | }
592 |
593 | // check if any processes on the wait queue's requests can be
594 | // satisfied
595 | checkWaitQueue(waitQueue);
596 |
597 | // determine whether or not we are deadlocked
598 | boolean deadlocked = (finishedProcesses.size() != processesSize && processes.size() == 0) ? true : false;
599 |
600 | // if we are currently deadlocked...
601 | if (deadlocked) {
602 | // attempt to correct the current deadlock
603 | correctDeadlock(deadlocked, waitQueue, finishedProcesses, processesSize);
604 | }
605 | }
606 |
607 | // return the array list of finished processes
608 | return finishedProcesses;
609 | }
610 |
611 | private static void incrementWaitTime(ArrayList waitQueue) {
612 | // increment the wait time of all processes on the wait list by one
613 | for (int i = 0; i < waitQueue.size(); i++) {
614 | waitQueue.get(i).waitTime++;
615 | }
616 | }
617 |
618 | private static void checkWaitQueue(ArrayList waitQueue) {
619 | // initialize stack to hold all processes to be removed from the wait
620 | // queue
621 | Stack stack = new Stack();
622 |
623 | // iterate through all processes in wait queue checking if we can
624 | // satisfy each process' request
625 | for (int k = 0; k < waitQueue.size(); k++) {
626 | // store the desired index
627 | int currentIndex = waitQueue.get(k).activities.get(0).resourceType;
628 | // account for off by one error
629 | if (currentIndex > 0) {
630 | currentIndex--;
631 | }
632 | // if we can satisfy the current process' request
633 | if (resources[currentIndex] >= waitQueue.get(k).activities.get(0).info) {
634 | // remove current process from the wait queue and add it to the
635 | // stack
636 | stack.push(waitQueue.remove(k));
637 | }
638 | }
639 |
640 | // push all items from the stack back to the process list
641 | while (!stack.isEmpty()) {
642 | processes.add(0, stack.pop());
643 | }
644 | }
645 |
646 | private static void correctDeadlock(boolean deadlocked, ArrayList waitQueue,
647 | ArrayList finishedProcesses, int processesSize) {
648 | // while deadlocked continuously abort processes
649 | while (deadlocked) {
650 | // abort process with the lowest process number and release its
651 | // resources
652 | abortProcess(waitQueue, finishedProcesses);
653 |
654 | // now that a process has been aborted, check if any of the requests
655 | // on the wait queue can be satisfied
656 | checkWaitQueue(waitQueue);
657 |
658 | // reassign deadlock
659 | deadlocked = (finishedProcesses.size() != processesSize && processes.size() == 0) ? true : false;
660 | }
661 | }
662 |
663 | private static void abortProcess(ArrayList waitQueue, ArrayList finishedProcesses) {
664 | // keep track of minimum
665 | int min = 0;
666 |
667 | // iterate through processes finding the smallest process number
668 | for (int k = 0; k < waitQueue.size(); k++) {
669 | // reassign minimum index
670 | if (waitQueue.get(k).number < waitQueue.get(min).number) {
671 | min = k;
672 | }
673 | }
674 |
675 | // iterate through process with the lowest process number's resource
676 | // array
677 | for (int k = 0; k < waitQueue.get(min).resources.length; k++) {
678 | // redistribute resources
679 | resources[k] += waitQueue.get(min).resources[k];
680 | waitQueue.get(min).resources[k] = 0;
681 | }
682 |
683 | // mark current process as aborted
684 | waitQueue.get(min).aborted = true;
685 |
686 | // add aborted process to finished processes array list
687 | finishedProcesses.add(waitQueue.get(min));
688 |
689 | // remove current process from wait queue
690 | waitQueue.remove(min);
691 | }
692 |
693 | private static void printOptimisticManager(ArrayList optimisticProcesses) {
694 | // print header
695 | System.out.println(String.format("%17s", "FIFO"));
696 |
697 | // initialize total run time to zero
698 | int totalRunTime = 0;
699 |
700 | // initialize total wait time to zero
701 | int totalWaitTime = 0;
702 |
703 | // iterate through all processes
704 | for (int i = 0; i < optimisticProcesses.size(); i++) {
705 | // if the current process was aborted as a result of a deadlock...
706 | if (optimisticProcesses.get(i).aborted) {
707 | System.out.println("Task " + (i + 1) + "\t\taborted");
708 | }
709 |
710 | // if the current process successfully terminated
711 | else {
712 | // increment total time taken
713 | totalRunTime += optimisticProcesses.get(i).timeTaken;
714 |
715 | // increment total wait time
716 | totalWaitTime += optimisticProcesses.get(i).waitTime;
717 |
718 | // print output for current task
719 | System.out.format("Task " + (optimisticProcesses.get(i).number) + "\t\t%d\t%d\t%.0f%s",
720 | optimisticProcesses.get(i).timeTaken, optimisticProcesses.get(i).waitTime,
721 | ((float) optimisticProcesses.get(i).waitTime / (float) optimisticProcesses.get(i).timeTaken)
722 | * 100,
723 | "%");
724 | System.out.println();
725 | }
726 | }
727 |
728 | // print total runtime, total wait time, and overall percentage spent
729 | // waiting
730 | System.out.format("total \t\t%d\t%d\t%.0f%s", totalRunTime, totalWaitTime,
731 | ((float) totalWaitTime / (float) totalRunTime * 100), "%");
732 |
733 | // print line breaks
734 | System.out.println();
735 | System.out.println();
736 | }
737 | }
738 |
--------------------------------------------------------------------------------
/BankersAlgorithm/src/bankersAlgorithm/Process.java:
--------------------------------------------------------------------------------
1 | package bankersAlgorithm;
2 | import java.util.ArrayList;
3 |
4 | public class Process {
5 | //declare number attribute
6 | protected int number;
7 | //declare resources attribute
8 | protected int[] resources;
9 | //declare claim attribute
10 | protected int[] claim;
11 | //declare request made attribute
12 | protected int[] requestsMade;
13 | //declare time taken attribute
14 | protected int timeTaken;
15 | //declare wait time attribute
16 | protected int waitTime;
17 | //declare computing attribute
18 | protected int computing;
19 | //declare boolean aborted attribute
20 | protected boolean aborted = false;
21 | //declare activities attribute
22 | protected ArrayList activities = new ArrayList();
23 |
24 | //constructor for process
25 | public Process(int number, int resources) {
26 | this.number = number;
27 | this.resources = new int[resources];
28 | }
29 |
30 | //constructor to copy a process
31 | public Process(Process toCopy) {
32 | this.number = toCopy.number;
33 | this.resources = toCopy.resources;
34 | this.claim = toCopy.claim;
35 | this.timeTaken = toCopy.timeTaken;
36 | this.waitTime = toCopy.waitTime;
37 | this.computing = toCopy.computing;
38 | this.aborted = toCopy.aborted;
39 | this.activities = toCopy.activities;
40 | }
41 |
42 | //getter for number
43 | public int getNumber() {
44 | return this.number;
45 | }
46 |
47 | //getter for resources
48 | public int[] getResources() {
49 | return this.resources;
50 | }
51 |
52 | //getter for time taken
53 | public int getTimeTake() {
54 | return this.timeTaken;
55 | }
56 |
57 | //getter for activities
58 | public ArrayList getActivities() {
59 | return this.activities;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/DemandPaging/Main.java:
--------------------------------------------------------------------------------
1 |
2 | import java.io.File;
3 | import java.io.IOException;
4 | import java.util.*;
5 |
6 |
7 | /**
8 | * Created by kdn251 on 11/28/16.
9 | */
10 | public class Main {
11 | //initialize RAM to null
12 | static Page[] RAM = null;
13 | static HashMap map = null;
14 | static int QUANTUM = 3;
15 | static Scanner scanner = null;
16 |
17 | public static void main(String args[]) throws IOException {
18 | //store command line values
19 | int machineSize = Integer.parseInt(args[0]);
20 | int pageSize = Integer.parseInt(args[1]);
21 | int processSize = Integer.parseInt(args[2]);
22 | int jobMix = Integer.parseInt(args[3]);
23 | int references = Integer.parseInt(args[4]);
24 | String replacementAlgorithm = args[5];
25 |
26 | //initialize hash map to map integers to process objects
27 | map = new HashMap();
28 |
29 | //initialize scanner to read random numbers file
30 |
31 | //attempt to reinitialize scanner to read from random-number file
32 | try {
33 | scanner = new Scanner(new File("random-numbers.txt"));
34 | }
35 |
36 | //catch all exceptions...
37 | catch(Exception exception) {
38 | System.out.println("Please ensure that the random-number.txt file is within the same directory as main");
39 | System.exit(-1);
40 | }
41 |
42 | //initialize processes and place them into the hash map
43 | if(jobMix == 1) {
44 | for(int i = 1; i <= 1; i++) {
45 | map.put(i, new Process(i, 1, 0, 0, references));
46 | }
47 | }
48 | else if(jobMix == 2) {
49 | for(int i = 1; i <= 4; i++) {
50 | map.put(i, new Process(i, 1, 0, 0, references));
51 | }
52 | }
53 | else if(jobMix == 3) {
54 | for(int i = 1; i <= 4; i++) {
55 | map.put(i, new Process(i, 0, 0, 0, references));
56 | }
57 | }
58 | else {
59 | map.put(1, new Process(1, 0.75, 0.25, 0, references));
60 | map.put(2, new Process(2, 0.75, 0, 0.25, references));
61 | map.put(3, new Process(3, 0.75, 0.125, 0.125, references));
62 | map.put(4, new Process(4, 0.5, 0.125, 0.125, references));
63 | }
64 |
65 | //initialize RAM array to store pages
66 | RAM = new Page[machineSize / pageSize];
67 |
68 | //fill RAM with smallest possible value
69 | Arrays.fill(RAM, null);
70 |
71 | //echo intput to standar output
72 | echo(machineSize, pageSize, processSize, jobMix, references, replacementAlgorithm);
73 |
74 | //simulate demand paging
75 | paging(machineSize, pageSize, processSize, jobMix, references, replacementAlgorithm);
76 | }
77 |
78 | public static void echo(int machineSize, int pageSize, int processSize, int jobMix, int references, String replacementAlgorithm) {
79 | System.out.println("The machine size is " + machineSize);
80 | System.out.println("The page size is " + pageSize);
81 | System.out.println("The process size is " + processSize);
82 | System.out.println("The job mix number is " + jobMix);
83 | System.out.println("The number of references per page is " + references);
84 | System.out.println("The replacement algorithm is " + replacementAlgorithm);
85 | System.out.println();
86 | }
87 |
88 | public static void paging(int machineSize, int pageSize, int processSize, int jobMix, int references, String replacementAlgorithm) {
89 | //initialize queue for LRU replacement algorithm
90 | Queue pageQueue = new LinkedList();
91 |
92 | //initialize stack for FIFO replacement algorithm
93 | Stack pageStack = new Stack();
94 |
95 | int time = 1;
96 |
97 | while(time <= (map.size() * references)) {
98 | Iterator it = map.entrySet().iterator();
99 | while(it.hasNext()) {
100 | Map.Entry pair = (Map.Entry)it.next();
101 | Process currentProcess = (Process)pair.getValue();
102 | for(int i = 0; i < QUANTUM && currentProcess.numberOfReferences > 0; i++) {
103 | int word = 0;
104 | if(currentProcess.firstReference) {
105 | //System.out.println("PROCESSSIZE" + processSize);
106 | word = (111 * currentProcess.number) % processSize;
107 | currentProcess.nextWord = word;
108 | currentProcess.firstReference = false;
109 | }
110 | else {
111 | word = (currentProcess.nextWord + processSize) % processSize;
112 | }
113 |
114 | int pageNumber = word / pageSize;
115 |
116 | Page currentPage = new Page(pageNumber, currentProcess.number);
117 |
118 | int frameIndex = contains(RAM, currentPage);
119 |
120 | //if the page table contains the current page...
121 | if(frameIndex >= 0) {
122 | //System.out.println(currentProcess.number + " references word " + word + " at time " + time + " Frame index: " + frameIndex);
123 | //if replacement algorithm is LRU...
124 | if(replacementAlgorithm.equalsIgnoreCase("LRU")) {
125 | Iterator iterator = pageQueue.iterator();
126 | //check if the queue already contains the current page, if it does, remove it
127 | while (iterator.hasNext()) {
128 | Page page = iterator.next();
129 | if (currentPage.equals(page)) {
130 | iterator.remove();
131 | }
132 | }
133 |
134 | //add current page back to queue so that it is not the LRU
135 | pageQueue.add(currentPage);
136 | }
137 | }
138 | else {
139 | int possiblyEvictedFrame = add(RAM, currentPage, pageQueue, pageStack, replacementAlgorithm, time);
140 | //UNCOMMENT FOR DEBUGGING
141 | //System.out.println(currentProcess.number + " references word " + word + " at time " + time + ": Evicted frame: " + possiblyEvictedFrame);
142 | }
143 |
144 | //determine next word based on a, b, c
145 | int nextRandom = scanner.nextInt();
146 |
147 | //UNCOMMENT FOR DEBUGGING
148 | // System.out.println("Random: " + nextRandom);
149 |
150 | double y = nextRandom / (Integer.MAX_VALUE + 1d);
151 |
152 | if(y < currentProcess.a) {
153 | currentProcess.nextWord = (currentProcess.nextWord + 1) % processSize;
154 | }
155 | else if(y < currentProcess.a + currentProcess.b) {
156 | currentProcess.nextWord = (currentProcess.nextWord - 5) % processSize;
157 | }
158 | else if(y < currentProcess.a + currentProcess.b + currentProcess.c) {
159 | currentProcess.nextWord = (currentProcess.nextWord + 4) % processSize;
160 | }
161 | else {
162 | int nextRandomInt = scanner.nextInt();
163 | currentProcess.nextWord = nextRandomInt % processSize;
164 | }
165 |
166 | //decrement number of references remaining for the current process
167 | currentProcess.numberOfReferences--;
168 |
169 | //increment time
170 | time++;
171 | }
172 | }
173 | }
174 |
175 | //initialize values for final calculations
176 | int totalPageFaults = 0;
177 | float totalEvictions = 0;
178 | float averageResidencyTime = 0;
179 |
180 | //iterate through hash map and increment values for final calculations
181 | for(Map.Entry entry : map.entrySet()) {
182 | totalPageFaults += entry.getValue().numberOfPageFaults;
183 | totalEvictions += entry.getValue().numberOfEvictions;
184 | averageResidencyTime += entry.getValue().residencyTime;
185 | //print results
186 | if(entry.getValue().numberOfEvictions == 0) {
187 | System.out.println("Process " + entry.getValue().number + " had " + entry.getValue().numberOfPageFaults + " faults. With no evictions, the average residence is undefined.");
188 | }
189 | //print results
190 | else {
191 | System.out.println("Process " + entry.getValue().number + " had " + entry.getValue().numberOfPageFaults + " faults and " + (entry.getValue().residencyTime / entry.getValue().numberOfEvictions) + " average residency");
192 | }
193 | }
194 |
195 | //print results
196 | if(totalEvictions == 0) {
197 | System.out.printf("\nThe total number of faults is %d. With no evictions, the overage average residency is undefined\n", totalPageFaults);
198 | }
199 | //print results
200 | else {
201 | averageResidencyTime = averageResidencyTime / totalEvictions;
202 | System.out.printf("\nThe total number of faults is %d and the overage average residency is %f\n", totalPageFaults, averageResidencyTime);
203 | }
204 | }
205 |
206 | public static int contains(Page[] RAM, Page currentPage) {
207 | //iterate through RAM searching for current page
208 | for(int i = 0; i < RAM.length; i++) {
209 | if(RAM[i] == null) continue;
210 | //if the page is found
211 | if(RAM[i].processNumber == currentPage.processNumber && RAM[i].pageNumber == currentPage.pageNumber) {
212 | currentPage.loadTime = RAM[i].loadTime;
213 | return i;
214 | }
215 | }
216 |
217 | map.get(currentPage.processNumber).numberOfPageFaults++;
218 |
219 | //page was not found
220 | return -1;
221 | }
222 |
223 | public static int add(Page[] RAM, Page currentPage, Queue pageQueue, Stack pageStack, String replacementAlgorithm, int time) {
224 | //iterate through RAM looking for a free frame
225 | for(int i = RAM.length - 1; i >= 0; i--) {
226 | //if the current space in RAM is available
227 | if(RAM[i] == null) {
228 | RAM[i] = currentPage;
229 | if(replacementAlgorithm.equalsIgnoreCase("LRU")) {
230 | pageQueue.add(currentPage);
231 | }
232 | if(replacementAlgorithm.equalsIgnoreCase("LIFO")) {
233 | pageStack.add(currentPage);
234 | }
235 | currentPage.loadTime = time;
236 | return i;
237 | }
238 | }
239 |
240 | return evict(RAM, currentPage, pageQueue, pageStack, replacementAlgorithm, time);
241 | }
242 |
243 | public static int evict(Page[] RAM, Page currentPage, Queue pageQueue, Stack pageStack, String replacementAlgorithm, int time) {
244 | //check if the replacement algorithm is LRU
245 | if(replacementAlgorithm.equalsIgnoreCase("LRU")) {
246 | //find the page to remove from RAM
247 | Page pageToRemove = pageQueue.poll();
248 | //iterate through RAM to find the page to remove
249 | for(int i = 0; i < RAM.length; i++) {
250 | //place current page in the victim's index
251 | if(RAM[i].processNumber == pageToRemove.processNumber && RAM[i].pageNumber == pageToRemove.pageNumber) {
252 | //System.out.println("process number: " + pageToRemove.processNumber);
253 | map.get(pageToRemove.processNumber).numberOfEvictions++;
254 | RAM[i] = currentPage;
255 | currentPage.loadTime = time;
256 | map.get(pageToRemove.processNumber).residencyTime += (time - pageToRemove.loadTime);
257 | pageQueue.add(currentPage);
258 | return i;
259 | }
260 | }
261 |
262 | //error
263 | return -1;
264 | }
265 | //check if the replacement algorithm is LIFO
266 | else if(replacementAlgorithm.equalsIgnoreCase("LIFO")) {
267 | Page pageToRemove = pageStack.pop();
268 | for(int i = 0; i < RAM.length; i++) {
269 | if(RAM[i].processNumber == pageToRemove.processNumber && RAM[i].pageNumber == pageToRemove.pageNumber) {
270 | map.get(pageToRemove.processNumber).numberOfEvictions++;
271 | RAM[i] = currentPage;
272 | currentPage.loadTime = time;
273 | map.get(pageToRemove.processNumber).residencyTime += (time - pageToRemove.loadTime);
274 | pageStack.add(currentPage);
275 | return i;
276 | }
277 | }
278 |
279 | //error
280 | return -1;
281 | }
282 |
283 | //check if the replacement algorithm is Random
284 | else if(replacementAlgorithm.equalsIgnoreCase("Random")) {
285 | int randomVictim = scanner.nextInt() % RAM.length;
286 | Page pageToRemove = RAM[randomVictim];
287 | map.get(pageToRemove.processNumber).numberOfEvictions++;
288 | map.get(pageToRemove.processNumber).residencyTime += (time - pageToRemove.loadTime);
289 | RAM[randomVictim] = currentPage;
290 | currentPage.loadTime = time;
291 | return randomVictim;
292 | }
293 |
294 | //otherwise, return -1 (error)
295 | return -1;
296 | }
297 | }
298 |
--------------------------------------------------------------------------------
/DemandPaging/Page.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * Created by kdn251 on 11/30/16.
4 | */
5 | public class Page {
6 | protected int pageNumber;
7 | protected int processNumber;
8 | protected int loadTime;
9 |
10 | public Page() {
11 | //default constructor
12 | }
13 |
14 | public Page(int pageNumber, int processNumber) {
15 | this.pageNumber = pageNumber;
16 | this.processNumber = processNumber;
17 | }
18 |
19 | @Override
20 | public boolean equals(Object object) {
21 | //cast object to page object
22 | Page otherPage = (Page)object;
23 |
24 | //check if the current page and other page are equal
25 | if(this.processNumber == otherPage.processNumber && this.pageNumber == otherPage.pageNumber) {
26 | return true;
27 | }
28 |
29 | //current page and other page are not equal
30 | return false;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/DemandPaging/Process.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * Created by kdn251 on 11/28/16.
4 | */
5 | public class Process {
6 | protected int number;
7 | protected int size;
8 | protected int references;
9 | protected float numberOfEvictions;
10 | protected int numberOfPageFaults;
11 | protected float residencyTime;
12 | protected int numberOfReferences;
13 | protected int nextWord;
14 | protected double a;
15 | protected double b;
16 | protected double c;
17 | protected boolean firstReference = true;
18 | protected String algorithm;
19 |
20 | public Process() {
21 | //defualt contructor
22 | }
23 |
24 | public Process(int number, double a, double b, double c, int numberOfReferences){
25 | this.number = number;
26 | this.a = a;
27 | this.b = b;
28 | this.c = c;
29 | this.numberOfReferences = numberOfReferences;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/DemandPaging/README:
--------------------------------------------------------------------------------
1 | Kevin Naughton Jr. Operating System's Demand Paging Lab
2 |
3 |
4 | COMPILE
5 | to compile, navigate to the directory that holds all java files and random-numbers.txt and run the following command
6 | javac *.java
7 |
8 |
9 | RUN
10 | to run, run the following command with 5 command line arguments: machine size, page size, process size, job mix, number of references, and replacement algorithm (in that order).
11 | java Main MACHINE_SIZE PAGE_SIZE PROCESS_SIZE JOB_MIX NUMBER_OF_REFERENCES REPLACEMENT_ALGORITHM
12 |
13 |
14 | EXAMPLE
15 | javac *.java
16 | java Main 1000 40 400 4 5000 lifo 0
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/DualPassLinker/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/DualPassLinker/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | OSLab1Linker
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/DualPassLinker/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/DualPassLinker/inputFiles/input1.txt:
--------------------------------------------------------------------------------
1 | 4
2 | 1 xy 2
3 | 2 z xy
4 | 5 10043 56781 20004 80023 70014
5 | 0
6 | 1 z
7 | 6 80013 10004 10004 30004 10023 10102
8 | 0
9 | 1 z
10 | 2 50013 40004
11 | 1 z 2
12 | 2 xy z
13 | 3 80002 10014 20004
14 |
--------------------------------------------------------------------------------
/DualPassLinker/inputFiles/input2.txt:
--------------------------------------------------------------------------------
1 | 4
2 | 1
3 | xy
4 |
5 | 2
6 | 2 z
7 | xy
8 | 5 10043 56781
9 |
10 | 20004 80023 70014 0
11 | 1 z 6 80013
12 | 10004 10004 30004 10023 10102
13 |
14 | 0
15 | 1 z
16 | 2
17 | 50013
18 | 40004
19 | 1
20 | z 2
21 | 2
22 | xy z
23 | 3
24 | 80002
25 |
26 | 10014 20004
27 |
--------------------------------------------------------------------------------
/DualPassLinker/inputFiles/input3.txt:
--------------------------------------------------------------------------------
1 | 6
2 |
3 | 3 X11 6 X12 8 X13 9
4 | 2 X22 X31
5 | 10 10003 10014 10004 10014 10004 10004 10062 10073 10082 10093
6 |
7 | 3 X21 0 X22 2 X23 5
8 | 3 X11 X13 X31
9 | 8 20014 20004 20023 20004 20014 20053 20014 20024
10 |
11 | 1 X31 2
12 | 0
13 | 3 30002 37011 30022
14 |
15 | 0
16 | 3 X31 X11 X22
17 | 6 40003 40004 40014 40033 40043 40024
18 |
19 | 00
20 | 00
21 | 3 50003 59871 50023
22 |
23 | 1 X61 2
24 | 1 X31
25 | 6 60003 60004 60022 60032 60043 60051
26 |
--------------------------------------------------------------------------------
/DualPassLinker/inputFiles/input4.txt:
--------------------------------------------------------------------------------
1 | 3
2 |
3 | 0
4 | 1 X21
5 | 3 10004 10004 10004
6 |
7 | 1 X21 0
8 | 0
9 | 1 29562
10 |
11 | 1 X21 1
12 | 0
13 | 1 34561
14 |
--------------------------------------------------------------------------------
/DualPassLinker/inputFiles/input5.txt:
--------------------------------------------------------------------------------
1 | 3
2 |
3 | 0
4 | 1 X21
5 | 3 10004 10004 10004
6 |
7 | 0
8 | 0
9 | 1 29562
10 |
11 | 1 X31 0
12 | 0
13 | 1 34561
14 |
--------------------------------------------------------------------------------
/DualPassLinker/inputFiles/input6.txt:
--------------------------------------------------------------------------------
1 | 3
2 |
3 | 0
4 | 1 X21
5 | 3 10004 10004 10004
6 |
7 | 1 X21 0
8 | 0
9 | 1 29562
10 |
11 | 0
12 | 0
13 | 1 30563
14 |
--------------------------------------------------------------------------------
/DualPassLinker/inputFiles/input7.txt:
--------------------------------------------------------------------------------
1 | 3
2 |
3 | 0
4 | 1 X21
5 | 3 10004 10044 12224
6 |
7 | 1 X21 0
8 | 1 X31
9 | 1 20004
10 |
11 | 1 X31 0
12 | 0
13 | 1 32562
14 |
--------------------------------------------------------------------------------
/DualPassLinker/inputFiles/input8.txt:
--------------------------------------------------------------------------------
1 | 4
2 |
3 | 0
4 | 1 X11
5 | 1 12341
6 |
7 | 1 X11 0
8 | 1 X41
9 | 1 20004
10 |
11 | 0
12 | 1 X11
13 | 2 30004
14 |
15 | 1 X41 6
16 | 0
17 | 1 41231
18 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/Linker.java:
--------------------------------------------------------------------------------
1 | /* @author: Kevin Naughton Jr. */
2 |
3 | package linker;
4 |
5 | import java.io.File;
6 | import java.util.ArrayList;
7 | import java.util.Scanner;
8 |
9 | public class Linker {
10 | public static void main(String[] args) {
11 | //declare scanner
12 | Scanner scanner;
13 | try {
14 | //initialize scanner to try and read file
15 | scanner = new Scanner(new File(args[0]));
16 | }
17 | catch (Exception allExceptions) {
18 | //catch except and exit gracefully
19 | scanner = null;
20 | System.out.println("Please enter a file name via the command line.");
21 | System.exit(-1);
22 | }
23 |
24 | //initialize an array list of Modules
25 | ArrayList entireFile = new ArrayList();
26 |
27 | //add all tokens of the file to entire file variable
28 | while(scanner.hasNext()) {
29 | entireFile.add(scanner.next());
30 | }
31 |
32 | //create array to hold all modules
33 | Module[] allModules = new Module[Integer.parseInt(entireFile.get(0))];
34 | for(int i = 0; i < allModules.length; i++) {
35 | //create new module object
36 | Module newModule = new Module();
37 |
38 | //assign new module to ith index of all modules array
39 | allModules[i] = newModule;
40 | }
41 |
42 | SymbolTable symbolTable = new SymbolTable();
43 |
44 | //call first pass function
45 | firstPass(entireFile, allModules, symbolTable);
46 |
47 | //print symbol table
48 | printSymbolTable(allModules);
49 |
50 | System.out.println();
51 |
52 | //print memory map
53 | secondPass(allModules, symbolTable);
54 |
55 | for(int i = 0; i < symbolTable.absoluteAddresses.size(); i++) {
56 | System.out.println(i + ":" + " " + symbolTable.absoluteAddresses.get(i));
57 | }
58 |
59 | System.out.println();
60 | for(int i = 0; i < symbolTable.warningMessages.size(); i++) {
61 | System.out.println(symbolTable.warningMessages.get(i));
62 | }
63 |
64 | System.out.println();
65 | for(int i = 0; i < symbolTable.errorMessages.size(); i++) {
66 | System.out.println(symbolTable.errorMessages.get(i));
67 | }
68 | }
69 |
70 | private static void firstPass(ArrayList entireFile, Module[] allModules, SymbolTable symbolTable) {
71 | //track line number of file
72 | int lineNumber = 0;
73 |
74 | //track index of all modules' definition lines
75 | int allModulesDefIndex = 0;
76 |
77 | //track index of all modules' use lines
78 | int allModulesUseIndex = 0;
79 |
80 | //track index of all modules' program lines
81 | int allModulesProgramIndex = 0;
82 |
83 | //keep track of base address while iterating through modules
84 | int baseAddress = 0;
85 |
86 | //iterate through entire file
87 | for(int i = 1; i < entireFile.size() - 1; i ++) {
88 | if(Integer.parseInt(entireFile.get(i)) == 0) {
89 | //if i is 0 continue to next non zero element
90 | while(Integer.parseInt(entireFile.get(i)) == 0) {
91 | i++;
92 | if(lineNumber % 3 == 0) {
93 | allModulesDefIndex++;
94 | }
95 | else if(lineNumber % 3 == 1) {
96 | allModulesUseIndex++;
97 | }
98 | else {
99 | allModulesProgramIndex++;
100 | }
101 |
102 | lineNumber++;
103 | }
104 | }
105 |
106 | if(Integer.parseInt(entireFile.get(i)) != 0) {
107 | if(lineNumber % 3 == 0) {
108 | int iterationLength = Integer.parseInt(entireFile.get(i)) * 2;
109 | for(int l = 0; l < iterationLength / 2; l++) {
110 | Variable variable = new Variable();
111 | allModules[allModulesDefIndex].allVariables.add(variable);
112 | }
113 |
114 | int count = 0;
115 | int currentVariable = 0;
116 | for(int k = 0; k < iterationLength; k++) {
117 | if(k % 2 == 0) {
118 | i++;
119 | boolean multiplyDefined = false;
120 | String multiplyDefinedVariable = null;
121 | //check if the current variable has been previously defined
122 | for(int checkDefined = 0; checkDefined <= allModulesDefIndex; checkDefined++) {
123 | for(int duplicate = 0; duplicate < allModules[checkDefined].allVariables.size(); duplicate++) {
124 | if(entireFile.get(i).equals(allModules[checkDefined].allVariables.get(duplicate).symbol)) {
125 | multiplyDefined = true;
126 | multiplyDefinedVariable = entireFile.get(i);
127 | symbolTable.errorMessages.add("Error: " + multiplyDefinedVariable + " is multiply defined; first value used");
128 | }
129 | }
130 | }
131 |
132 | //if the current variable has not previously been defined add it to the symbol table
133 | if(multiplyDefined == false) {
134 | //add current variable to symbol table's array list of variable names
135 | symbolTable.variableNames.add(entireFile.get(i));
136 | allModules[allModulesDefIndex].allVariables.get(currentVariable).symbol = entireFile.get(i);
137 | count++;
138 | }
139 | //if the current variable is not multiply defined
140 | else {
141 | i+=2;
142 | count = 0;
143 | }
144 | }
145 |
146 | if(k % 2 == 1) {
147 | i++;
148 | allModules[allModulesDefIndex].allVariables.get(currentVariable).symbolLocation = Integer.parseInt(entireFile.get(i)) + baseAddress;
149 | count++;
150 | }
151 | if(count == 2) {
152 | currentVariable++;
153 | count = 0;
154 | }
155 | }
156 |
157 | //increment module index
158 | allModulesDefIndex++;
159 |
160 | //increment line number
161 | lineNumber++;
162 | }
163 | //current line is a use line of a module
164 | else if((lineNumber % 3) == 1) {
165 | int numberOfUses = Integer.parseInt(entireFile.get(i));
166 | for(int j = 0; j < numberOfUses; j++) {
167 | i++;
168 | allModules[allModulesUseIndex].uses.add(entireFile.get(i));
169 | }
170 |
171 | //increment index to next module
172 | allModulesUseIndex++;
173 |
174 | //increment line number
175 | lineNumber++;
176 | }
177 |
178 | //process the program line of the current module
179 | else {
180 | allModules[allModulesProgramIndex].setBaseAddress(baseAddress);
181 |
182 | baseAddress = Integer.parseInt(entireFile.get(i)) + baseAddress;
183 |
184 | //set the current module's length
185 | allModules[allModulesProgramIndex].length = Integer.parseInt(entireFile.get(i));
186 |
187 | int lengthOfWord = 5;
188 |
189 | //if module length is 1 add the word and move to next line
190 | if(Integer.parseInt(entireFile.get(i)) == 1) {;
191 | i++;
192 | if(entireFile.get(i).length() != lengthOfWord) {
193 | //continue
194 | }
195 | else {
196 | allModules[allModulesProgramIndex].words.add(Integer.parseInt(entireFile.get(i)));
197 | }
198 | }
199 |
200 | //module has multiple words
201 | else {
202 | int numberOfSkips = Integer.parseInt(entireFile.get(i)) - 1;
203 | for(int j = 0; j < numberOfSkips + 1; j++) {
204 | //do not iterate outside of file bounds
205 | if(i <= entireFile.size() - 2) {
206 | i++;
207 | //add current word to current module's word array list
208 | if(entireFile.get(i).length() == lengthOfWord) {
209 | allModules[allModulesProgramIndex].words.add(Integer.parseInt(entireFile.get(i)));
210 | }
211 | else {
212 | j = numberOfSkips + 1;
213 | i--;
214 |
215 | }
216 | }
217 | }
218 | }
219 |
220 | //increment index to next module
221 | allModulesProgramIndex++;
222 |
223 | //increment current line number
224 | lineNumber++;
225 | }
226 | }
227 | }
228 |
229 | //check if the current use has been previously defined
230 | for(int i = allModules.length - 1; i > 0; i--) {
231 | for(int j = allModules[i].uses.size() - 1; j > 0; j--) {
232 | String currentSymbolUsed = allModules[i].uses.get(j);
233 | int useCount = 0;
234 | for(int k = 0; k < allModules.length; k++) {
235 | for(int l = 0; l < allModules[k].allVariables.size(); l++) {
236 | if(currentSymbolUsed.equals(allModules[k].allVariables.get(l).symbol)) {
237 | useCount++;
238 | }
239 | }
240 | }
241 |
242 | if(useCount == 0) {
243 | symbolTable.warningMessages.add("Error: " + currentSymbolUsed + " is not defined; zero used.");
244 | }
245 | }
246 | }
247 |
248 | //check if any variables are defined but not used
249 | for(int i = 0; i < allModules.length; i++) {
250 | for(int j = 0; j < allModules[i].allVariables.size(); j++) {
251 | Variable currentSymbol = allModules[i].allVariables.get(j);
252 | int useCount = 0;
253 | for(int k = 0; k < allModules.length; k++) {
254 | for(int l = 0; l < allModules[k].uses.size(); l++) {
255 | if(currentSymbol.symbol.equals(allModules[k].uses.get(l))) {
256 | useCount++;
257 | }
258 | }
259 | }
260 |
261 | if(useCount == 0) {
262 | symbolTable.warningMessages.add("Warning: " + currentSymbol.symbol + " was defined in module " + i + " but was never used.");
263 |
264 | }
265 | }
266 | }
267 | }
268 |
269 |
270 | private static void printSymbolTable(Module[] allModules) {
271 | System.out.println("Symbol Table");
272 | for(int i = 0; i < allModules.length; i++) {
273 | for(int j = 0; j < allModules[i].allVariables.size(); j++) {
274 | if(allModules[i].allVariables.get(j).symbol != "") {
275 | System.out.println(allModules[i].allVariables.get(j).symbol + " = " + allModules[i].allVariables.get(j).symbolLocation);
276 | }
277 | }
278 | }
279 | }
280 |
281 | private static SymbolTable secondPass(Module[] allModules, SymbolTable symbolTable) {
282 | System.out.println("Memory Map");
283 | //check any a variable location exceeds the size of its respective module
284 | for(int i = 0; i < allModules.length; i++) {
285 | for(int j = 0; j < allModules[i].allVariables.size(); j++) {
286 | if(allModules[i].allVariables.get(j).symbolLocation - allModules[i].getBaseAddress() > allModules[i].length) {
287 | //System.out.println("Current module's length is: " + allModules[i].length + " current symbol's location is: " + (allModules[i].allVariables.get(j).symbolLocation - allModules[i].getBaseAddress()));
288 | symbolTable.errorMessages.add("Error: " + allModules[i].allVariables.get(j).symbol + " exceeds the size of the module; address given as 0 (relative).");
289 | allModules[i].allVariables.get(j).symbolLocation = allModules[i].getBaseAddress();
290 |
291 | }
292 | }
293 | }
294 |
295 | //length of machine
296 | int lengthOfMachine = 600;
297 |
298 | //length of absolute address
299 | int lengthOfAddress = 4;
300 |
301 | //length of address of word
302 | int lengthOfAddressOfWord = 4;
303 |
304 | //for every module
305 | for(int i = 0; i < allModules.length; i++) {
306 | //for every word in current module
307 | for(int j = 0; j < allModules[i].words.size(); j++) {
308 | String currentWord = Integer.toString(allModules[i].words.get(j));
309 | char lastDigit = currentWord.charAt(currentWord.length() - 1);
310 | //if address is an immediate address or absolute address
311 | if(lastDigit == '1' || lastDigit == '2') {
312 | //System.out.println("AFTER IF WORD IS " + currentWord);
313 | String absoluteAddressString = "";
314 | String relativeAddressString = "";
315 | String correctedAbsoluteAddressString = "";
316 | //calculate address
317 | for(int k = 0; k < lengthOfAddress; k++) {
318 | absoluteAddressString += currentWord.charAt(k);
319 | if(k == 0) {
320 | correctedAbsoluteAddressString += currentWord.charAt(k);
321 | }
322 | if(k != 0) {
323 | relativeAddressString += currentWord.charAt(k);
324 | }
325 | }
326 |
327 | //If an absolute address exceeds the size of the machine, print an error message and use the value zero
328 | if(lastDigit == '2' && Integer.parseInt(relativeAddressString) > 600) {
329 | //add error message to symbol table
330 | symbolTable.errorMessages.add("Error: Absolute address exceeds machine size; zero used.");
331 |
332 | //add corrected absolute address to symbol table
333 | symbolTable.absoluteAddresses.add(Integer.parseInt(correctedAbsoluteAddressString + "000"));
334 | }
335 | else {
336 | int absoluteAddressInteger = Integer.parseInt(absoluteAddressString);
337 | symbolTable.absoluteAddresses.add(absoluteAddressInteger);
338 | }
339 | }
340 |
341 | //if address is a relative address
342 | else if(lastDigit == '3') {
343 | String absoluteAddressString = "";
344 | String relativeAddressString = "";
345 | String correctedAbsoluteAddressString = "";
346 |
347 | //calculate address
348 | for(int k = 0; k < lengthOfAddress; k++) {
349 | absoluteAddressString += currentWord.charAt(k);
350 | if(k == 0) {
351 | correctedAbsoluteAddressString += currentWord.charAt(k);
352 | }
353 | if(k != 0) {
354 | relativeAddressString += currentWord.charAt(k);
355 | }
356 | }
357 |
358 | //If a relative address exceeds the size of the module, print an error message and use the value zero
359 | if(Integer.parseInt(relativeAddressString) > allModules[i].length) {
360 | //add error message to symbol table
361 | symbolTable.errorMessages.add("Error: Relative address exceeds module size; zero used.");
362 |
363 | //add corrected absolute address to symbol table
364 | symbolTable.absoluteAddresses.add(Integer.parseInt(correctedAbsoluteAddressString + "000"));
365 | }
366 | else {
367 | int absoluteAddressInteger = Integer.parseInt(absoluteAddressString) + allModules[i].getBaseAddress();
368 | symbolTable.absoluteAddresses.add(absoluteAddressInteger);
369 | }
370 | }
371 |
372 | //address is an external address
373 | else {
374 | String index = "";
375 | String address = "";
376 | String correctedAbsoluteAddressString = "";
377 | String largerThanUseListString = "";
378 | String externalReference = "";
379 | boolean found = false;
380 | boolean largerThanUseLength = false;
381 |
382 | for(int k = 1; k < lengthOfAddressOfWord; k++) {
383 | index += currentWord.charAt(k);
384 | largerThanUseListString += currentWord.charAt(k);
385 | }
386 |
387 | if(Integer.parseInt(index) > allModules[i].uses.size()) {
388 | //add error message to symbol table
389 | symbolTable.errorMessages.add("Error: External address exceeds length of use list; treated as immediate.");
390 | symbolTable.absoluteAddresses.add(Integer.parseInt(currentWord.charAt(0) + largerThanUseListString));
391 | largerThanUseLength = true;
392 | }
393 |
394 | //if the current index does not exhaust the current module's use length
395 | if(!largerThanUseLength) {
396 | int absoluteAddress;
397 | externalReference = allModules[i].uses.get(Integer.parseInt(index));
398 | for(int l = 0; l < allModules.length; l++) {
399 | for(int m = 0; m < allModules[l].allVariables.size(); m++) {
400 | if(allModules[l].allVariables.get(m).symbol.equals(externalReference)) {
401 | absoluteAddress = allModules[l].allVariables.get(m).symbolLocation;
402 | String absoluteAddressString = String.valueOf(absoluteAddress);
403 | int numberOfDigits = absoluteAddressString.length();
404 | int fullAddress = numberOfDigits;
405 | int currentWordIndex = 0;
406 |
407 | //calculate the last remainder of the address
408 | while(fullAddress < lengthOfAddress) {
409 | address += currentWord.charAt(currentWordIndex);
410 | currentWordIndex++;
411 | fullAddress++;
412 | }
413 |
414 | //add absolute address to the symbol table
415 | symbolTable.absoluteAddresses.add(Integer.parseInt(address + absoluteAddress));
416 |
417 | //increment number of uses in use list
418 | allModules[i].entireUseListUsed++;
419 |
420 | //mark that current variable was referenced in current module
421 | found = true;
422 | }
423 | }
424 | }
425 | }
426 |
427 | //if the external address was never defined and index in current module's use line is valid
428 | if((found == false) && (largerThanUseLength == false)) {
429 | //add error message to symbol table
430 | symbolTable.errorMessages.add("Error: " + externalReference + " is not defined; zero used.");
431 |
432 | //add first digit of word to corrected absolute address
433 | correctedAbsoluteAddressString += currentWord.charAt(0);
434 |
435 | //add corrected absolute address to symbol table
436 | symbolTable.absoluteAddresses.add(Integer.parseInt(correctedAbsoluteAddressString + "000"));
437 | }
438 | }
439 | }
440 |
441 | //check if all variables in the use list have been used
442 | if(allModules[i].entireUseListUsed < allModules[i].uses.size()) {
443 | symbolTable.warningMessages.add("Warning: In module " + i + " not all variables in the use list are used.");
444 | }
445 | }
446 |
447 | return symbolTable;
448 | }
449 | }
450 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/Module.java:
--------------------------------------------------------------------------------
1 | /* @author: Kevin Naughton Jr. */
2 |
3 | package linker;
4 |
5 | import java.util.ArrayList;
6 |
7 | public class Module {
8 | //store array list of variable objects
9 | protected ArrayList allVariables = new ArrayList();
10 |
11 | //store uses of current module
12 | protected ArrayList uses = new ArrayList();
13 |
14 | //store boolean values to check if all elements in module's uses array list were referenced
15 | protected ArrayList usesReferenced = new ArrayList();
16 |
17 | //if all variables in list list are used
18 | protected int entireUseListUsed = 0;
19 |
20 | //store words of current module
21 | protected ArrayList words = new ArrayList();
22 |
23 | //store current module's length
24 | protected int length;
25 |
26 | //store the module's base address
27 | private int baseAddress = 0;
28 |
29 | public Module() {
30 | //default constructor
31 | }
32 |
33 | public ArrayList getUses() {
34 | return this.uses;
35 | }
36 |
37 | public void setBaseAddress(int baseAddress){
38 | this.baseAddress = baseAddress;
39 | }
40 |
41 | public int getBaseAddress(){
42 | return this.baseAddress;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/README.txt:
--------------------------------------------------------------------------------
1 | Kevin Naughton Jr.
2 | Operating Systems Linker Lab
3 |
4 | Provided with an input file as the first command line argument the program will print its output to the console
5 |
6 | COMPILE
7 | In terminal, navigate to the directory that contains the linker package
8 | and run the following command:
9 | javac linker/Linker.java
10 |
11 |
12 | RUN
13 | Run the following command where "input/file" is
14 | the path to the input file (ensure that input file is within the same directory as the source code):
15 | java linker.Linker input/file
16 |
17 | EXAMPLE
18 | javac linker/Linker.java
19 | java linker.Linker linker/input3.txt
20 |
21 | the commands above run the program on the input file input3.txt
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/SymbolTable.java:
--------------------------------------------------------------------------------
1 | /* @author: Kevin Naughton Jr. */
2 | package linker;
3 | import java.util.ArrayList;
4 |
5 | public class SymbolTable {
6 | //Store every variable name in the symbol table
7 | protected ArrayList variableNames = new ArrayList();
8 |
9 | //Store every absolute addresses of all modules
10 | protected ArrayList absoluteAddresses = new ArrayList();
11 |
12 | //Store possible error messages for absolute addresses corresponding to index
13 | protected ArrayList errorMessages = new ArrayList();
14 |
15 | //store possible warning messages for absolute addresses corresponding to index
16 | protected ArrayList warningMessages = new ArrayList();
17 |
18 | public SymbolTable() {
19 | //default constructor
20 | }
21 | }
22 |
23 |
24 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/Variable.java:
--------------------------------------------------------------------------------
1 | /* @author: Kevin Naughton Jr. */
2 | package linker;
3 |
4 | public class Variable {
5 | //store the module's symbol
6 | protected String symbol = "";
7 |
8 | //store the module's symbol location
9 | protected int symbolLocation = 0; //MAYBE CHANGE THIS BACK TO NO symbolLocation; IF IT CAUSES PROBLEMS/BUGS
10 |
11 | //store boolean as to whether this is the first definition of a specific variable
12 | protected boolean firstDefinition = true;
13 |
14 | //handles error where current variable is used but not defined
15 | protected boolean usedButNotDefined = false;
16 |
17 | //handles error where current variable is defined but not used
18 | protected boolean definedButNotUsed = false;
19 |
20 | public Variable() {
21 | //default constructor
22 | }
23 |
24 | public Variable(String symbol, int symbolLocation) {
25 | this.symbol = symbol;
26 | this.symbolLocation = symbolLocation;
27 | }
28 |
29 | public String getSymbol() {
30 | return this.symbol;
31 | }
32 |
33 | public int getSymbolLocation() {
34 | return this.symbolLocation;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/input2.txt:
--------------------------------------------------------------------------------
1 | 4
2 | 1
3 | xy
4 |
5 | 2
6 | 2 z
7 | xy
8 | 5 10043 56781
9 |
10 | 20004 80023 70014 0
11 | 1 z 6 80013
12 | 10004 10004 30004 10023 10102
13 |
14 | 0
15 | 1 z
16 | 2
17 | 50013
18 | 40004
19 | 1
20 | z 2
21 | 2
22 | xy z
23 | 3
24 | 80002
25 |
26 | 10014 20004
27 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/input3.txt:
--------------------------------------------------------------------------------
1 | 6
2 |
3 | 3 X11 6 X12 8 X13 9
4 | 2 X22 X31
5 | 10 10003 10014 10004 10014 10004 10004 10062 10073 10082 10093
6 |
7 | 3 X21 0 X22 2 X23 5
8 | 3 X11 X13 X31
9 | 8 20014 20004 20023 20004 20014 20053 20014 20024
10 |
11 | 1 X31 2
12 | 0
13 | 3 30002 37011 30022
14 |
15 | 0
16 | 3 X31 X11 X22
17 | 6 40003 40004 40014 40033 40043 40024
18 |
19 | 00
20 | 00
21 | 3 50003 59871 50023
22 |
23 | 1 X61 2
24 | 1 X31
25 | 6 60003 60004 60022 60032 60043 60051
26 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/input4.txt:
--------------------------------------------------------------------------------
1 | 3
2 |
3 | 0
4 | 1 X21
5 | 3 10004 10004 10004
6 |
7 | 1 X21 0
8 | 0
9 | 1 29562
10 |
11 | 1 X21 1
12 | 0
13 | 1 34561
14 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/input5.txt:
--------------------------------------------------------------------------------
1 | 3
2 |
3 | 0
4 | 1 X21
5 | 3 10004 10004 10004
6 |
7 | 0
8 | 0
9 | 1 29562
10 |
11 | 1 X31 0
12 | 0
13 | 1 34561
14 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/input6.txt:
--------------------------------------------------------------------------------
1 | 3
2 |
3 | 0
4 | 1 X21
5 | 3 10004 10004 10004
6 |
7 | 1 X21 0
8 | 0
9 | 1 29562
10 |
11 | 0
12 | 0
13 | 1 30563
14 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/input7.txt:
--------------------------------------------------------------------------------
1 | 3
2 |
3 | 0
4 | 1 X21
5 | 3 10004 10044 12224
6 |
7 | 1 X21 0
8 | 1 X31
9 | 1 20004
10 |
11 | 1 X31 0
12 | 0
13 | 1 32562
14 |
--------------------------------------------------------------------------------
/DualPassLinker/src/linker/input8.txt:
--------------------------------------------------------------------------------
1 | 4
2 |
3 | 0
4 | 1 X11
5 | 1 12341
6 |
7 | 1 X11 0
8 | 1 X41
9 | 1 20004
10 |
11 | 0
12 | 1 X11
13 | 2 30004
14 |
15 | 1 X41 6
16 | 0
17 | 1 41231
18 |
--------------------------------------------------------------------------------
/Homework1/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Homework1/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Homework1
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Homework1/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/Homework2/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Homework2/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Homework2
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Homework2/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/Homework2/Homework 2.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework2/Homework 2.pdf
--------------------------------------------------------------------------------
/Homework2/README.md:
--------------------------------------------------------------------------------
1 | Description:
2 |
3 | Input The program should take two command line arguments.
4 | First one is a directory name. If the directory is omitted from the command line, it is an error. The program should display an
5 | error message and terminate. The error message should indicate what went wrong. If the directory name is provided, but it is
6 | not a name of a valid directory, the program should display an error message and terminate. The error message should indicate
7 | what went wrong.
8 | The second one is the maximum number of largest files found in the directory provided as the first argument. If the number is
9 | missing, the default value of 20 should be used.
10 | Output Your program should determine and print to standard output the total space used by the directory in question (that
11 | includes the sizes or all the files and subdirectories contained in it). The program should also print the sizes and pathnames of
12 | the largest files. (See Homework 2.pdf for more info)
13 |
--------------------------------------------------------------------------------
/Homework2/src/project2/DirectorySize.java:
--------------------------------------------------------------------------------
1 | package project2;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.util.ArrayList;
6 | import java.util.Collections;
7 | import java.util.LinkedList;
8 | import java.util.List;
9 |
10 | /**
11 | * This program provides a tool that given a name of a directory,
12 | * explores all its sub-directories and files and does two things:
13 | * - computes the total size of all the files and sub-directories,
14 | * - prints a list of n largest files (their sizes and absolute paths.
15 | *
16 | * @author Joanna Klukowska & Kevin Naughton Jr.
17 | *
18 | */
19 | public class DirectorySize {
20 |
21 | /**list of files found in the directory structure */
22 | static List listOfFiles ;
23 | /**list of visited directories (kept to avoid
24 | * circular links and infinite recursion) */
25 | static List listOfVisitedDirs;
26 |
27 |
28 | /**
29 | * This method expects one or two arguments.
30 | * @param args Array of arguments passed to the program. The first one
31 | * is the name of the directory to be explored. The second (optional) is the
32 | * max number of largest files to be printed to the screen.
33 | * @throws IOException
34 | */
35 | public static void main(String[] args) throws IOException{
36 |
37 | //TODO:
38 | //check the number of command line arguments
39 | //terminate if not sufficient
40 | if(args.length == 1 || args.length == 2) {
41 | if(args[0] == null){
42 | //exit program gracefully
43 | System.out.println("Please provide a directory to be searched.");
44 | System.exit(1);
45 | }
46 | }
47 | else {
48 | System.out.println("Erro: please enter the correct amount of arguments (1 or 2).");
49 | }
50 |
51 |
52 |
53 | //TODO:
54 | // use directory name entered from the command line
55 | // verify if the directory is valid, terminate if not
56 | String directory = args[0];
57 | File dir = new File(directory);
58 | // verification goes here
59 | if(dir.exists()) { //check if directory exists
60 | System.out.println("The provided directory has been found.");
61 | }
62 | else {
63 | System.out.println("The provided directory could not be found.");
64 | System.exit(1);
65 | }
66 |
67 |
68 |
69 |
70 |
71 | //create an empty list of files
72 | listOfFiles = new LinkedList ();
73 | //create an empty list of directories
74 | listOfVisitedDirs = new ArrayList ();
75 |
76 | // Display the total size of the directory/file
77 | long size = getSize( dir );
78 | if (size < 1024 ) //print bytes
79 | System.out.printf("Total space used: %7.2f bytes",
80 | (float) size );
81 | else if (size/1024 < 1024 )//print kilobytes
82 | System.out.printf("Total space used: %7.2f KB\n",
83 | (float) size / 1024.0 );
84 | else if (size/1024/1024 < 1024 )//print megabytes
85 | System.out.printf("Total space used: %7.2f MB\n",
86 | (float) size / (1024.0 * 1024));
87 | else //print gigabytes
88 | System.out.printf("Total space used: %7.2f GB\n",
89 | (float) size / (1024.0 * 1024*1024));
90 |
91 |
92 | // Display the largest files in the directory
93 | int numOfFiles = 20; //default value
94 | try {
95 | if (args.length == 2 ) {
96 | numOfFiles = Integer.parseInt(args[1]);
97 | }
98 | }
99 | catch (NumberFormatException ex) {
100 | System.err.printf("ERROR: Invalid number of files provided." +
101 | "The second argument should be an integer. \n");
102 | System.exit(1);
103 | }
104 |
105 | Collections.sort(listOfFiles);
106 |
107 |
108 |
109 |
110 |
111 | for (int i = 0; i < listOfFiles.size() && i < numOfFiles; i++)
112 | //print from the back so that the largest files are printed
113 | System.out.println(listOfFiles.get(listOfFiles.size() - i - 1));
114 |
115 | }
116 |
117 |
118 | /**
119 | * Recursively determines the size of a directory or file represented
120 | * by the abstract parameter object file.
121 | * This method populates the listOfFiles with all the files contained in the
122 | * explored directory.
123 | * This method populates the listOfVisitedDirs with canonical path names of
124 | * all the visited directories.
125 | * @param file directory/file name whose size should be determined
126 | * @return number of bytes used for storage on disk
127 | * @throws IOException
128 | */
129 | public static long getSize (File file) throws IOException {
130 | long size = 0; // Store the total size of all files
131 |
132 | try {
133 |
134 | //TODO: implement this method
135 | //check if file parameter is a directory and if it has not yet been visited
136 | if(file.isDirectory() && (!listOfVisitedDirs.contains(file))) {
137 | //string array to store files within directory
138 | File[] allFiles = file.listFiles();
139 | //loop through files within directory
140 | for(int i = 0; i < allFiles.length; i++) {
141 | //add the size of the directory to the variable size
142 | size += getSize(allFiles[i]);
143 | //add current file to listOfVisitedDirs
144 | listOfVisitedDirs.add(allFiles[i].getCanonicalPath());
145 | //recursive call
146 | getSize(allFiles[i]);
147 |
148 | }
149 | }
150 | else { //the parameter file is a file
151 | size += file.length(); //METHOD TO USE MIGHT BE .length()
152 | //change current file object to FileOnDisk object
153 | FileOnDisk fileInElseBlock = new FileOnDisk(file.getCanonicalPath(), file.length());
154 | //add the new FileOnDisk object to listOfFiles
155 | listOfFiles.add(fileInElseBlock);
156 |
157 | }
158 |
159 | } catch (IOException e) {
160 | //DEAL WITH IOEXCEPTION
161 | System.out.println("Can't access given directory.");
162 | }
163 |
164 | return size;
165 |
166 | }
167 |
168 | }
--------------------------------------------------------------------------------
/Homework2/src/project2/FileOnDisk.java:
--------------------------------------------------------------------------------
1 | package project2;
2 |
3 | import java.io.File;
4 |
5 | /**
6 | * An abstract representation of file on disk.
7 | * @author Kevin Naughton Jr.
8 | *
9 | */
10 |
11 | public class FileOnDisk implements Comparable {
12 | //data fields for a FileOnDisk object
13 | private String directory;
14 | private long numberOfFiles;
15 | private String filePath;
16 | private long size;
17 |
18 | /**
19 | * Creates a new FileOnDisk object
20 | * @param pathName - directory name
21 | * @param size - number of largest files within the directory to return
22 | */
23 | public FileOnDisk(String enteredDirectory, long size) {
24 | this.directory = enteredDirectory;
25 | this.size = size;
26 |
27 | }
28 |
29 | /**
30 | * Compares two FileOnDisk objects based on their size.
31 | * if files are same size order is alphabetical
32 | * @param arg0 - file to compare
33 | * @return -1 - if current file's size < arg0 size
34 | * @return 1 - if current file's size > arg0 size
35 | */
36 | @Override
37 | public int compareTo(FileOnDisk arg0) {
38 | if(this.size > arg0.size) {
39 | return 1;
40 | }
41 | else if(this.size < arg0.size) {
42 | return -1;
43 | }
44 | else if(this.size == arg0.size) {
45 | if(this.directory.compareTo(arg0.directory) == 1) {
46 | return 1;
47 | }
48 | else {
49 | return -1;
50 | }
51 | }
52 | return 0;
53 | }
54 |
55 | /**
56 | * Returns the absolute path for the file represented by this object.
57 | * @return Returns the size for the file represented by this object
58 | */
59 | public String getAbsPath() {
60 | return this.filePath;
61 | }
62 |
63 | /**
64 | * Returns the size for the file represented by this object
65 | * @return Returns the size for the file represented by this object
66 | */
67 | public long getSize() {
68 | return this.numberOfFiles;
69 |
70 | }
71 |
72 | /**
73 | * Produces string representation of the object.
74 | * @return file's size and file's full path name
75 | */
76 | @Override
77 | public String toString() {
78 | // Display the total size of the directory/file
79 | if (size < 1024 ) //print bytes
80 | return String.format("%7.2f bytes",
81 | (float) size ) + " " + this.directory;
82 | else if (size/1024 < 1024 )//print kilobytes
83 | return String.format("%7.2f KB",
84 | (float) size / 1024.0 ) + " " + this.directory;
85 | else if (size/1024/1024 < 1024 )//print megabytes
86 | return String.format("%7.2f MB",
87 | (float) size / (1024.0 * 1024)) + " " + this.directory;
88 | else //print gigabytes
89 | return String.format("%7.2f GB",
90 | (float) size / (1024.0 * 1024*1024)) + " " + this.directory;
91 | }
92 |
93 |
94 |
95 | }
96 |
--------------------------------------------------------------------------------
/Homework3/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Homework3/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Homework3
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Homework3/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/Homework3/Homework 3.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework3/Homework 3.pdf
--------------------------------------------------------------------------------
/Homework3/README.md:
--------------------------------------------------------------------------------
1 | Description:
2 |
3 | We spent some time discussing performance of the algorithms, but in practice what one often wants to test is how a given
4 | implementation performs on a given machine. You will write code for several implementations of the sort algorithms and evaluate
5 | their performance. (See Homework 3.pdf for more info)
6 |
--------------------------------------------------------------------------------
/Homework3/src/project3/Homework 3.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework3/src/project3/Homework 3.pdf
--------------------------------------------------------------------------------
/Homework3/src/project3/InsertionSort.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | */
4 | package project3;
5 |
6 | /**
7 | * @author Joanna Klukowska
8 | *
9 | */
10 | public class InsertionSort > implements Sorter {
11 |
12 | /**
13 | * Sorts the given array using insertion sort algorithm.
14 | * @param list array to sort.
15 | */
16 | public void sort(E[] list) {
17 | for (int i = 1; i < list.length; i++) {
18 | /*
19 | * insert list[i] into a sorted sublist list[0..i-1] so that
20 | * list[0..i] is sorted.
21 | */
22 | E currentElement = list[i];
23 | int k;
24 | for (k = i - 1; k >= 0 && list[k].compareTo(currentElement) > 0; k--) {
25 | list[k + 1] = list[k];
26 | }
27 |
28 | // Insert the current element into list[k+1]
29 | list[k + 1] = currentElement;
30 | }
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/Homework3/src/project3/MergeSort.java:
--------------------------------------------------------------------------------
1 | package project3;
2 |
3 | public class MergeSort > implements Sorter {
4 | //holds copy of array to sort
5 | private E[] listCopy;
6 | //stores length of arary to sort
7 | private int length;
8 | //stores sorted elements of the array to sort
9 | private E[] mergeArray;
10 |
11 | /**
12 | * Sorts the given array using the merge sort algorithm.
13 | * @param list array to sort.
14 | */
15 | public void sort(E[] list) {
16 | //copy the array to be sorted
17 | listCopy = list;
18 | //store the length of the array
19 | length = list.length;
20 | //copy the array to be sorted
21 | mergeArray = list;
22 |
23 | //initiate merge sort
24 | sort(0, length - 1);
25 | }
26 |
27 | /*
28 | * sorts array by continuously splitting array into sorted subarrays
29 | * @param low - lower bound of array to be sorted
30 | * @param high - upper bound of array to be sorted
31 | */
32 | private void sort(int low, int high) {
33 | if(low < high) {
34 | //store the middle element of the array
35 | int middleIndex = low + (high - low) / 2;
36 |
37 | //sort the left side of the array
38 | sort(low, middleIndex);
39 |
40 | //sort the right side of the array
41 | sort(middleIndex + 1, high);
42 |
43 | //combine the two sorted sides of the array
44 | combine(low, middleIndex, high);
45 | }
46 | }
47 |
48 | /*
49 | * combines to the now two sorted halves of the array
50 | * @param low - start of array to combine
51 | * @param middleIndex - middle index of array to combine
52 | * @param high - end of array to combine
53 | */
54 | private void combine(int low, int middleIndex, int high) {
55 | //copy elements from listCopy to mergeArray
56 | for(int i = low; i <= high; i++) {
57 | mergeArray[i] = listCopy[i]; //populates mergeArray
58 | }
59 | //store values
60 | int i = low;
61 | int j = middleIndex + 1;
62 | int k = low;
63 |
64 |
65 | while(i <= middleIndex && j <= high) {
66 | if(mergeArray[i].compareTo(mergeArray[j]) < 0) {
67 | //copy lower element to listCopy if current index < middle index
68 | listCopy[k] = mergeArray[i];
69 | }
70 | else {
71 | //otherwise set start of array to the middle index
72 | listCopy[k] = mergeArray[j];
73 | j++; //increment j
74 | }
75 | k++; //increment k
76 | }
77 |
78 | //copy sorted elements to listCopy
79 | while(i <= middleIndex) {
80 | listCopy[k] = mergeArray[i];
81 | k++; //increment k
82 | i++; //increment i
83 | }
84 | }
85 |
86 |
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/Homework3/src/project3/QuickSort.java:
--------------------------------------------------------------------------------
1 | package project3;
2 |
3 | public class QuickSort > implements Sorter {
4 |
5 | private E copyArray[];
6 | private int length;
7 |
8 | /**
9 | * Sorts the given array using the quick sort algorithm.
10 | * @param list array to sort.
11 | */
12 | public void sort(E[] list) {
13 | //copy list
14 | copyArray = list;
15 | //store length of list
16 | length = list.length;
17 |
18 | //start quick sort
19 | sort(0, length - 1);
20 | }
21 | /*
22 | * performs selection sort
23 | * @param low - starting point of the array to sort
24 | * @param high - ending point of the array to sort
25 | */
26 | private void sort(int low, int high ) {
27 | int i = low; //store starting point
28 | int k = high; //store ending point
29 |
30 | //select pivot
31 | //E pivot = copyArray[low];
32 |
33 | //IMPROVEMENT: set pivot to middle element of array
34 | E pivot = copyArray[low + (high - low) / 2];
35 |
36 |
37 | while (i <= k) {
38 | //increment i while i < pivot
39 | while (copyArray[i].compareTo(pivot) < 0) {
40 | i++;
41 | }
42 | //decrement k while k > pivot
43 | while (copyArray[k].compareTo(pivot) > 0) {
44 | k--;
45 | }
46 | //place number on the correct side of the pivot
47 | if (i <= k) {
48 | swap(i, k);
49 | i++; //advance pointer to next index
50 | k--; //advance pointer to next index
51 | }
52 | }
53 |
54 | //call sort method again (recursive call)
55 | if (low < k) {
56 | sort(low, k);
57 | }
58 | if (i < high) {
59 | sort(i, high);
60 | }
61 |
62 | }
63 | /*
64 | * swaps index positions i and k
65 | * @param i - number to swap with k
66 | * @param k - number to swap with i
67 | */
68 | private void swap(int i, int k) {
69 | E temp = copyArray[i];
70 | copyArray[i] = copyArray[k];
71 | copyArray[k] = temp;
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/Homework3/src/project3/SelectionSort.java:
--------------------------------------------------------------------------------
1 | package project3;
2 |
3 | public class SelectionSort > implements Sorter {
4 |
5 | /**
6 | * Sorts the given array using the selection sort algorithm.
7 | * @param list array to sort.
8 | */
9 | public void sort(E[] list) {
10 | //loop through list
11 | for(int i = 0; i < list.length - 1; i++) {
12 | //maintain current index within first loop
13 | int currentPosition = i;
14 | //loop through list again to compare k to currentPosition
15 | for(int k = i + 1; k < list.length; k++) {
16 | //check if k is less than currentPosition
17 | if(list[k].compareTo(list[currentPosition]) < 0) {
18 | //switch currentPosition to point to k
19 | currentPosition = k;
20 | }
21 | }
22 | //swap smaller element with larger element
23 | E smaller = list[currentPosition];
24 |
25 | list[currentPosition] = list[i];
26 |
27 | list[i] = smaller;
28 |
29 | }
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/Homework3/src/project3/SortTester.java:
--------------------------------------------------------------------------------
1 | package project3;
2 |
3 | import java.util.Arrays;
4 | import java.util.Random;
5 |
6 | /**
7 | * The benchmark used for evaluation of sorting method.
8 | *
9 | * When RUN_ALL is set to false, it runs the merge sort, quick sort and
10 | * selection sort on an array of 10,000 integers and displays the time it took
11 | * for each to complete. Times displayed in microseconds.
12 | *
13 | * When RUN_ALL is set to true, it performs two "experiments":
14 | * 1) runs merge sort, quick sort and selection sort on arrays of integers
15 | * ranging in size from 10,000 to 100,000 in increments of 10,000
16 | * 2) runs merge sort and quick sort on arrays of integers ranging in size
17 | * from 50,000 to 1,000,000 in increments of 50,000.
18 | * Times are displayed in microseconds.
19 | *
20 | * @author Joanna Klukowska
21 | *
22 | */
23 | public class SortTester {
24 | static private Random rand = new Random(0);
25 |
26 | //TODO: set this to false before submitting your code
27 | //set it to true to collect the results
28 | private static final boolean RUN_ALL = false;
29 |
30 | public static void main(String[] args) {
31 |
32 | //////////////////////////////////////////////
33 | //run initial short runs
34 | //////////////////////////////////////////////
35 | int arraySize = 10000;
36 |
37 | Integer[] list = generateRandomIntegerArray(arraySize);
38 | Sorter arrayIntSorter;
39 | System.out.printf("\nArray size: %d", arraySize);
40 |
41 | System.out.printf("\nRunning merge sort: ");
42 | arrayIntSorter = new MergeSort();
43 | runTest(arrayIntSorter, list);
44 |
45 | System.out.printf("\nRunning quick sort: ");
46 | arrayIntSorter = new QuickSort();
47 | runTest(arrayIntSorter, list);
48 |
49 | System.out.printf("\nRunning selection sort: ");
50 | arrayIntSorter = new SelectionSort();
51 | runTest(arrayIntSorter, list);
52 |
53 |
54 | if ( !RUN_ALL ) {
55 | System.exit(0);
56 | }
57 | ////////////////////////////////////////////////
58 | //run all three algorithms
59 | ////////////////////////////////////////////////
60 | System.out.printf("\n\n%15s\t%15s\t%15s\t%15s", "N ", "Merge", "Quick", "Selection");
61 | for ( arraySize = 10000; arraySize <= 100000; arraySize = arraySize + 10000) {
62 |
63 | list = generateRandomIntegerArray(arraySize);
64 | System.out.printf("\n%15d", arraySize);
65 |
66 | arrayIntSorter = new MergeSort();
67 | runTest(arrayIntSorter, list);
68 |
69 | arrayIntSorter = new QuickSort();
70 | runTest(arrayIntSorter, list);
71 |
72 | arrayIntSorter = new SelectionSort();
73 | runTest(arrayIntSorter, list);
74 | }
75 |
76 |
77 | ////////////////////////////////////////////////
78 | //run two "fast" algorithms
79 | ////////////////////////////////////////////////
80 | System.out.printf("\n\n%15s\t%15s\t%15s", "N ", "Merge", "Quick" );
81 | for ( arraySize = 50000; arraySize <= 1000000; arraySize = arraySize + 50000) {
82 |
83 | list = generateRandomIntegerArray(arraySize);
84 | System.out.printf("\n%15d", arraySize);
85 |
86 | arrayIntSorter = new MergeSort();
87 | runTest(arrayIntSorter, list);
88 |
89 | arrayIntSorter = new QuickSort();
90 | runTest(arrayIntSorter, list);
91 | }
92 |
93 | }
94 |
95 | /**
96 | * Run a particular sort algorithm on the given list.
97 | * @param sorter an object representing one of the sort methods for arrays
98 | * @param list array to be used for sort timing, the array is not modified
99 | */
100 | public static > void runTest(Sorter sorter, E[] list) {
101 |
102 | long start, end;
103 |
104 | // create a copy of the array to be sorted
105 | E listCopy[] = Arrays.copyOf(list, list.length);
106 |
107 | //invoke the garbage collector
108 | System.gc();
109 | // start the timer
110 | start = System.nanoTime();
111 | sorter.sort(listCopy);
112 | end = System.nanoTime();
113 | // verify that the array is sorted
114 | if (!isSorted(listCopy))
115 | System.err.printf("Not sorted - problems in %s", sorter.getClass() );
116 | System.out.printf("\t%15d", (end - start) / 1000);
117 |
118 | }
119 |
120 | /**
121 | * Determines if a given list is sorted.
122 | * @param list array containing data
123 | * @return true, if list is in a sorted order (according to the natural ordering of its elements),
124 | * false, otherwise
125 | */
126 | public static > boolean isSorted(E[] list) {
127 | for (int i = 1; i < list.length; i++) {
128 | if (list[i - 1].compareTo(list[i]) > 0) {
129 | return false;
130 | }
131 | }
132 | return true;
133 | }
134 |
135 | /** Generates an array of random integers in the range of valid integer values.
136 | * @param size size of the array to generate
137 | * @return an array of random integers
138 | */
139 | public static Integer[] generateRandomIntegerArray(int size) {
140 | Integer list[] = new Integer[size];
141 |
142 | for (int i = 0; i < list.length; i++)
143 | list[i] = rand.nextInt();
144 | return list;
145 | }
146 |
147 |
148 | }
149 |
--------------------------------------------------------------------------------
/Homework3/src/project3/Sorter.java:
--------------------------------------------------------------------------------
1 | package project3;
2 |
3 | /**
4 | * The interface for the implementation of different sort algorithms.
5 | *
6 | * @author Joanna Klukowska
7 | *
8 | * @param The type of objects that this Sorter objects expects in
9 | * the list to be sorted.
10 | */
11 | interface Sorter >{
12 |
13 | /**
14 | * Sorts the list according to the natural ordering of its elements
15 | * from smallest to largest. The list is modified.
16 | * @param list array of elements to be sorted
17 | */
18 | public void sort( E[] list );
19 | }
20 |
--------------------------------------------------------------------------------
/Homework4/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Homework4/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Homework4
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Homework4/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/Homework4/README.md:
--------------------------------------------------------------------------------
1 | Description:
2 |
3 | You are given the program that performs image segmentation. The implemented algorithm is based on the depth first search
4 | approach to region growing. This solution needs to use a stack to keep track of the pixels that need to be visited and evaluated.
5 | Currently it is using the stack implementation from the Java API. (See Homework 4.pdf for more info)
6 |
--------------------------------------------------------------------------------
/Homework4/bin/BW_Pattern.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/BW_Pattern.png
--------------------------------------------------------------------------------
/Homework4/bin/CT_image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/CT_image.jpg
--------------------------------------------------------------------------------
/Homework4/bin/ChessBoard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/ChessBoard.png
--------------------------------------------------------------------------------
/Homework4/bin/Gray_Pattern.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/Gray_Pattern.jpg
--------------------------------------------------------------------------------
/Homework4/bin/Head_CT_scan.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/Head_CT_scan.jpg
--------------------------------------------------------------------------------
/Homework4/bin/Lighthouse.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/Lighthouse.jpg
--------------------------------------------------------------------------------
/Homework4/bin/brain_image_MRI.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/brain_image_MRI.jpg
--------------------------------------------------------------------------------
/Homework4/bin/cameraman.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/cameraman.jpg
--------------------------------------------------------------------------------
/Homework4/bin/hubble1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/hubble1.png
--------------------------------------------------------------------------------
/Homework4/bin/lightning_bolt.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/lightning_bolt.jpg
--------------------------------------------------------------------------------
/Homework4/bin/pollen.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/bin/pollen.jpg
--------------------------------------------------------------------------------
/Homework4/src/BW_Pattern.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/BW_Pattern.png
--------------------------------------------------------------------------------
/Homework4/src/CT_image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/CT_image.jpg
--------------------------------------------------------------------------------
/Homework4/src/ChessBoard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/ChessBoard.png
--------------------------------------------------------------------------------
/Homework4/src/Gray_Pattern.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/Gray_Pattern.jpg
--------------------------------------------------------------------------------
/Homework4/src/Head_CT_scan.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/Head_CT_scan.jpg
--------------------------------------------------------------------------------
/Homework4/src/Lighthouse.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/Lighthouse.jpg
--------------------------------------------------------------------------------
/Homework4/src/brain_image_MRI.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/brain_image_MRI.jpg
--------------------------------------------------------------------------------
/Homework4/src/cameraman.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/cameraman.jpg
--------------------------------------------------------------------------------
/Homework4/src/hubble1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/hubble1.png
--------------------------------------------------------------------------------
/Homework4/src/lightning_bolt.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/lightning_bolt.jpg
--------------------------------------------------------------------------------
/Homework4/src/pollen.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/pollen.jpg
--------------------------------------------------------------------------------
/Homework4/src/proj4/Homework 4.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework4/src/proj4/Homework 4.pdf
--------------------------------------------------------------------------------
/Homework4/src/proj4/NewQueue.java:
--------------------------------------------------------------------------------
1 | package proj4;
2 |
3 | /**
4 | *
5 | * @author Kevin Naughton Jr.
6 | * Represents a queue and a queue's methods by implementing a Node class
7 | * @param Generic type - represents a generic type
8 | */
9 | public class NewQueue {
10 | //create data fields for the queue
11 | private Node head; //points to the front of the queue
12 | private Node tail; //points to the back of the queue
13 | private int size; //stores the size of the queue
14 |
15 | /**
16 | * Constructor for queues, creates a new queue object
17 | */
18 | public NewQueue() {
19 | this.head = null; //sets the head of the queue to null
20 | this.tail = null; //sets the tail of the queue to null
21 | int size = 0; //sets the size of the queue to null
22 | }
23 |
24 | /**
25 | * Tests if this queue is empty
26 | * @return true if this queue object is empty or false if this queue object is not empty
27 | */
28 | public boolean empty() {
29 | if(head == null) { //checks if this queue is empty
30 | return true; //this queue is empty
31 | }
32 | return false; //this queue is not empty
33 | }
34 |
35 | /**
36 | * Returns the element at the front of this queue without removing it from the queue
37 | * @return returnData - the information that the head (front) of the queue holds or null if this queue is empty
38 | */
39 | public E peek() {
40 | if(head == null) { //checks if this queue is empty
41 | return null;
42 | }
43 | E returnData = (E)head.getData(); //store head (front) of this queue's value in returnData
44 | return returnData;
45 | }
46 |
47 | /**
48 | * Removes the element at the front of this queue and returns that element as the value of this function
49 | * @return returnData - the information that the head (front) of the queue holds or null if this queue is empty
50 | */
51 | public E dequeue() {
52 | if(head == null) { //checks if this queue is empty
53 | return null; //this queue is empty
54 | }
55 | E returnData = (E)head.getData(); //store data to return
56 | head = head.getNext(); //advance the head of the queue to the next element
57 | size--; //decrement size of queue
58 |
59 | return returnData; //return front element's value
60 | }
61 |
62 | /**
63 | * Adds an item to the back of this queue. Returns the item itself
64 | * @param item - item to be enqueued to the queue
65 | * @return the item that was enqueued to the queue
66 | */
67 | public E enqueue(E item) {
68 | Node addedItem = new Node(item); //create new node and store the item to add to the queue within it
69 | if(head == null) { //checks if this queue is empty
70 | head = addedItem; //sets item to be enqueued to the head of the queue
71 | tail = addedItem; //sets item to be enqueued to the tail of the queue
72 | size++; //increment size of the queue
73 | }
74 | else {
75 | tail.setNext(addedItem); //sets the item to be enqueued to the reference of the tail of the queue
76 | size++; //increment size of the queue
77 | tail = addedItem; //set tail to the item added to the queue
78 |
79 | }
80 |
81 | return item; //return item that was enqueued to the queue
82 |
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/Homework4/src/proj4/NewStack.java:
--------------------------------------------------------------------------------
1 | package proj4;
2 |
3 | /**
4 | *
5 | * @author Kevin Naughton Jr.
6 | *Represents a stack and a stack's methods by implementing a Node class
7 | * @param Generic type - represents a generic type
8 | */
9 | public class NewStack {
10 | //create data fields for stack
11 | private Node head; //points to the top of the stack
12 | private int size; // stores the size of the stack
13 |
14 | /**
15 | * Constructor for stacks, creates a new stack object
16 | */
17 | public NewStack() {
18 | this.head = null; //sets the head of the stack to null
19 | this.size = 0; //sets the size of the stack to zero
20 | }
21 |
22 | /**
23 | * Tests if this stack is empty
24 | * @return true if this stack object is empty or false if this stack object is not empty
25 | */
26 | public boolean empty() {
27 | if(this.head == null) { //checks if this stack is empty
28 | return true; //this stack is empty
29 | }
30 | return false; //this stack is not empty
31 | }
32 |
33 | /**
34 | * Removes the element at the top of this stack and returns that element as the value of this function
35 | * @return the top element's value or null if the stack object is empty
36 | */
37 | public E pop() {
38 | Node current = head; //sets current to head
39 | if(head == null) { //checks if this stack is empty
40 | return null; //this stack is empty
41 | }
42 | E returnData; //create variable to store top element's value in
43 | returnData = (E) head.getData(); //stores data to return
44 |
45 | head = head.getNext(); //advance head of the stack to the next element
46 | size--; //decrement size of stack
47 |
48 | return returnData; //return top element's value
49 |
50 |
51 | }
52 |
53 | /**
54 | * Pushes an item onto the top of this stack. Returns the item itself
55 | * @param item - item to be pushed onto the top of this stack
56 | * @return the item that was pushed onto the top of this stack
57 | */
58 | public E push(E item) {
59 | Node newItem = new Node(item); //create new node and store the item to add to the stack within it
60 | newItem.setNext(head); //set reference of the new node to the head (top) of this stack
61 | head = newItem; //point head (top) of this stack to the new item
62 | size++; //increment size because we are adding a new item to this stack
63 | return item; //return the item that was added to this stack
64 |
65 | }
66 |
67 | /**
68 | * Returns the element at the top of this stack without removing it from the stack
69 | * @return returnData - the information that the head (top) of the stack holds or null if this stack is empty
70 | */
71 | public E peek() {
72 | if(head == null) { //checks if this stack is empty
73 | return null; //this stack is empty
74 | }
75 | else {
76 | E returnData = (E)head.getData(); //store head (top) of this stack's value in returnData
77 | return returnData;
78 |
79 | }
80 |
81 | }
82 |
83 |
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/Homework4/src/proj4/Node.java:
--------------------------------------------------------------------------------
1 | package proj4;
2 |
3 | /**
4 | *
5 | * @author Kevin Naughton Jr.
6 | * Used to implement abstract data types, specifically, stacks and queues
7 | * @param Generic type - represents a generic type
8 | */
9 | public class Node {
10 | //create data fields for Node
11 | private E data; //used to store data in the node
12 | private Node next; //used to point to the next node
13 |
14 | /**
15 | * Constructor for nodes, creates a node object
16 | * @param item - item to store in a specific node
17 | */
18 | public Node(E item) {
19 | this.data = item; //set current node's data data field to item
20 | }
21 |
22 | /**
23 | * Gets the data associated with a specific node
24 | * @return returns the data of a specific node
25 | */
26 | public E getData() {
27 | return this.data;
28 | }
29 |
30 | /**
31 | * Gets the reference to the next node
32 | * @return returns the reference to the next node
33 | */
34 | public Node getNext() {
35 | return this.next;
36 | }
37 |
38 | /**
39 | * Stores given information in the data data field of a specific node
40 | * @param newData - represents the data to store inside the specific node
41 | */
42 | public void setData(E newData) {
43 | this.data = newData; //sets current node's data data field to newData
44 | }
45 |
46 | /**
47 | * Stores a new given reference to another node in the next data field of a specific node
48 | * @param newNext - represents the new reference to the next node to store
49 | */
50 | public void setNext(Node newNext) {
51 | this.next = newNext; //sets current node's next data field to newNext
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/Homework4/src/proj4/RegionGrowing.java:
--------------------------------------------------------------------------------
1 | package proj4;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Stack;
5 |
6 | import processing.core.PApplet;
7 | import processing.core.PImage;
8 |
9 | /**
10 | * This program performs image segmentation using a simple
11 | * region growing algorithm. The user needs to select seed points
12 | * in each region that should be detected (at least one seed point
13 | * required in the region). A region is defined as the adjacent pixels
14 | * with very similar grayscale values.
15 | *
16 | * Once the algorithm is run each region is shown in a grayscale value
17 | * corresponding to the seed that originated that region. All pixels
18 | * that do not belong to any of the regions are shown in dark red color.
19 | *
20 | * The user selects the seeds by clicking on the image with a mouse.
21 | * The program responds to the following key strokes
22 | * r - resets the image to the original
23 | * x - select random seed points
24 | * d - run the region growing algorithm (using depth first search) and show the results
25 | * b - run the region growing algorithm (using breadth first search) and show the results
26 | *
27 | *
28 | * @author Joanna Klukowska & Kevin Naughton Jr.
29 | *
30 | */
31 | @SuppressWarnings("serial")
32 | public class RegionGrowing extends PApplet {
33 | //image objects
34 | private PImage img;
35 | private PImage imgCopy;
36 | //x and y coordinates of pixels, used in various loops
37 | private int x, y;
38 | //array to store original copy of the "pixels" of the image being segmented
39 | private int[] imagePixelsCopy;
40 | //color used for
41 | private int back = color(100,0,0);
42 | //arrays list used for storing the locations of seeds
43 | ArrayList seeds;
44 | //list of all the image file names (FEEL FREE TO MODIFY THIS ARRAY)
45 | private String [] allFileNames = {"ChessBoard.png", "BW_Pattern.png",
46 | "Gray_Pattern.jpg", "Lighthouse.jpg", "brain_image_MRI.jpg",
47 | "Head_CT_scan.jpg", "CT_image.jpg", "hubble1.png",
48 | "cameraman.jpg", "lightning_bolt.jpg", "pollen.jpg"};
49 | //list of the image files used for testing - DO NOT MODIFY
50 | String [] testFileNames = {"ChessBoard.png", "BW_Pattern.png",
51 | "Gray_Pattern.jpg", "Lighthouse.jpg", "brain_image_MRI.jpg",
52 | "cameraman.jpg"};
53 | //list of the seeds corresponding to testFileNames - DO NOT MODIFY
54 | int [][] testSeeds = { {3821, 54226, 55445, 3617, 26029, 26060, 33014, 33466},
55 | {7684, 19715, 24973, 42713, 31122},
56 | {78291, 68464, 83523, 76846, 55080, 46308, 37577, 45298},
57 | {42923, 81143, 185800},
58 | {127635, 183592, 264109, 157737, 188793, 323983, 382185, 387104, 368337, 395943},
59 | {23117, 42804, 12913, 29300, 50288, 47533, 40326, 24217, 32092, 27795}
60 | };
61 |
62 | //name of the image file to be used in the interactive run
63 | String fileName = allFileNames[3];
64 |
65 | //flags controlling the mode of the program
66 | // if false, run in interactive mode
67 | // if either is true, run in the corresponding test mode
68 | public static boolean RUN_TESTS_DFS = false;
69 | public static boolean RUN_TESTS_BFS = false;
70 |
71 |
72 | /**
73 | * This method is ignored when the program is run as an applet.
74 | * It is provided to allow for command line runs as an application.
75 | * @param args
76 | */
77 | public static void main(String args[]) {
78 | if (args.length > 0) {
79 | System.out.println("Running in test mode. Running both tests. ");
80 | RUN_TESTS_DFS = true;
81 | RUN_TESTS_BFS = true;
82 | }
83 | PApplet.main(new String[] { "RegionGrowing" });
84 | }
85 |
86 |
87 |
88 | /**
89 | * Setup to program to either run in the interactive mode or
90 | * in the test mode.
91 | * This method is run once to setup the window and initialize
92 | * the data fields.
93 | */
94 | public void setup() {
95 | if( RUN_TESTS_DFS )
96 | runTestsDFS();
97 | if (RUN_TESTS_BFS )
98 | runTestsBFS();
99 | if (!RUN_TESTS_DFS && !RUN_TESTS_BFS)
100 | runInteractive();
101 |
102 | }
103 |
104 | /**
105 | * Runs the actual applications. The method is runs in a continuous
106 | * loop (loop provided in other code). It provides the graphical
107 | * user interface for the interactive mode of the program.
108 | */
109 | public void draw() {
110 |
111 | //display seeds in the image
112 | fill(250,0,0);
113 | stroke(250,0,0);
114 | for (int i =0; i < seeds.size(); i++){
115 | int seed = seeds.get(i);
116 | ellipse(seed%img.width, seed/img.width, 2,2);
117 | }
118 |
119 | //reset the image to original and remove the seeds
120 | if (keyPressed == true && key == 'r') {
121 | imageReset(pixels, imagePixelsCopy);
122 | seeds = new ArrayList();
123 | }
124 |
125 | //generate 10 random seeds within the image
126 | if (keyPressed == true && key == 'x'&&seeds.size() < 10) {
127 | for (int i = 0; i < 10; i++) {
128 | seeds.add( (int)random( pixels.length));
129 | }
130 | }
131 |
132 | //apply region growing algorithm ( depth first search)
133 | if (keyPressed == true && key == 'd') {
134 | //set all the pixels to the background color
135 | imageBlank(pixels);
136 | //grow a region around each seed
137 | while (!seeds.isEmpty() ) {
138 | int seed = seeds.remove(seeds.size()-1);
139 | int value = (int) red(imagePixelsCopy[seed]);
140 | getRegionDFS( seed%img.width, seed/img.width, value, pixels, imagePixelsCopy);
141 | updatePixels();
142 | }
143 | }
144 |
145 | //apply region growing algorithm ( breadth first search)
146 | if (keyPressed == true && key == 'b') {
147 | //set all the pixels to the background color
148 | imageBlank(pixels);
149 | //grow a region around each seed
150 | while (!seeds.isEmpty() ) {
151 | int seed = seeds.remove(seeds.size()-1);
152 | int value = (int) red(imagePixelsCopy[seed]);
153 | getRegionBFS( seed%img.width, seed/img.width, value, pixels, imagePixelsCopy);
154 | updatePixels();
155 | }
156 | }
157 | } //end draw()
158 |
159 | /**
160 | * Handles mouse click event by adding a seed corresponding to the
161 | * x and y coordinates of the cursor.
162 | */
163 | public void mouseClicked() {
164 | int index = mouseY * img.width + mouseX;
165 | seeds.add(index);
166 | }
167 |
168 | /**
169 | * Resets the current image to the original.
170 | * @param pixels the current pixels array
171 | * @param imagePixelsCopy the original pixels array
172 | */
173 | public void imageReset ( int [] pixels, int [] imagePixelsCopy ) {
174 | for (int w = 0; w < img.width; w++) {
175 | for (int h = 0; h < img.height; h++) {
176 | pixels[h*img.width + w] = imagePixelsCopy[h*img.width + w];
177 | }
178 | }
179 | updatePixels();
180 | }
181 |
182 | /**
183 | * Sets all the pixels in the current image to the background color.
184 | * @param pixels the pixels of the current image
185 | */
186 | public void imageBlank ( int [] pixels ) {
187 | for (int h = 0; h < img.height; h++) {
188 | for (int w = 0; w < img.width; w++) {
189 | pixels[h*img.width + w] = back ;
190 | }
191 | }
192 | }
193 |
194 | /**
195 | * Sets a pixel in a pixels array to a particular gray level value
196 | * @param x coordinate of the pixel to be set
197 | * @param y y coordinate of the pixel to be set
198 | * @param grayLevel gray level to be assigned to the pixel
199 | * @param pixels array of pixels in which a pixel is modified
200 | */
201 | public void setPixelColor( int x, int y, float grayLevel, int [] pixels ) {
202 | pixels[y*img.width + x] = color ( grayLevel, grayLevel, grayLevel);
203 | }
204 |
205 | /**
206 | * Retrieves the value of a specified pixel from the pixels array.
207 | * Assumes that all three channels (R, G, B) have the same values.
208 | * @param x x coordinate of the pixel
209 | * @param y y coordinate of the pixel
210 | * @return the gray level of the pixel
211 | */
212 | public float getPixelColor( int x, int y, int [] pixels ) {
213 | return red(pixels[y*img.width + x]);
214 | }
215 |
216 |
217 | /**
218 | * Uses a depth first search approach to grow a region around a specified seed. All pixels
219 | * added to the region have gray level values that fall within a +/- threshold of the
220 | * gray level value of the seed. The threshold is computed as a standard deviation
221 | * of the pixels in the 11x11 neighborhood of the seed.
222 | * @param x x coordinate of the seed
223 | * @param y y coordinate of the seed
224 | * @param value gray level to assign to the pixels in the generated region
225 | * @param pixels array of current pixels to which the region is added
226 | * @param imagePixelsCopy array of original pixels based on which the region is
227 | * calculated
228 | */
229 | public void getRegionDFS( int x, int y, int value, int [] pixels, int [] imagePixelsCopy ) {
230 | int px, py, index;
231 | //compute the threshold based on the standard deviation of the grayscale values
232 | //of the pixels in the 11x11 neighborhood of the seed
233 | float threshold = 0;
234 | for (int nx = x - 5; nx < x + 5; nx++) {
235 | for (int ny = y - 5; ny < y + 5; ny++) {
236 | if (ny < 0 || ny >= img.height || nx < 0 || nx >= img.width) continue;
237 | threshold += red(imagePixelsCopy[ny*img.width+nx]);
238 | }
239 | }
240 | threshold = 2 * (float) Math.sqrt(threshold/121);
241 |
242 | //apply the depth first search algorithm for region growing
243 |
244 | NewStack pixelLocations = new NewStack();
245 |
246 | float pixDifference;
247 | pixelLocations.push(y*img.width + x );
248 | while (!pixelLocations.empty()) {
249 | index = pixelLocations.pop();
250 | px = index % img.width;
251 | py = index / img.width;
252 | pixels[index] = color(value,value,value);
253 |
254 | if (px!=0 && px!=img.width-1 && py!=0 && py!=img.height-1) {
255 | for (int nx = px-1; nx <= px+1; nx++) {
256 | for (int ny = py-1; ny <= py+1; ny++) {
257 | pixDifference = Math.abs( red(imagePixelsCopy[y*img.width+x]) - red(imagePixelsCopy[ny*img.width+nx]));
258 | if ( pixDifference <= threshold && pixels[ny*img.width+nx] == back ) {
259 | pixelLocations.push(ny*img.width+nx);
260 | }
261 | }
262 | }
263 | }
264 | }
265 | } //end getRegionDFS
266 |
267 | /**
268 | * Uses a breadth first search approach to grow a region around a specified seed. All pixels
269 | * added to the region have gray level values that fall within a +/- threshold of the
270 | * gray level value of the seed. The threshold is computed as a standard deviation
271 | * of the pixels in the 11x11 neighborhood of the seed.
272 | * @param x x coordinate of the seed
273 | * @param y y coordinate of the seed
274 | * @param value gray level to assign to the pixels in the generated region
275 | * @param pixels array of current pixels to which the region is added
276 | * @param imagePixelsCopy array of original pixels based on which the region is calculated
277 | */
278 | public void getRegionBFS( int x, int y, int value, int [] pixels, int [] imagePixelsCopy ) {
279 | /**
280 | * @author Kevin Naughton Jr.
281 | */
282 |
283 | //declare variables px, py, and index
284 | int px, py, index;
285 |
286 | //create a queue
287 | NewQueue pixelLocations = new NewQueue(); //stores pixel locations
288 |
289 | //compute the threshold based on the standard deviation of the grayscale values
290 | //of the pixels in the 11x11 neighborhood of the seed
291 | float threshold = 0;
292 | for (int nx = x - 5; nx < x + 5; nx++) {
293 | for (int ny = y - 5; ny < y + 5; ny++) {
294 | if (ny < 0 || ny >= img.height || nx < 0 || nx >= img.width) continue;
295 | threshold += red(imagePixelsCopy[ny*img.width+nx]);
296 | }
297 | }
298 | threshold = 2 * (float) Math.sqrt(threshold/121);
299 |
300 | //apply the breadth first search algorithm for region growing
301 |
302 | pixelLocations.enqueue(y*img.width + x );
303 | float pixDifference;
304 | while(!pixelLocations.empty()) {
305 | index = pixelLocations.dequeue();
306 | px = index % img.width;
307 | py = index / img.width;
308 | if (px!=0 && px!=img.width-1 && py!=0 && py!=img.height-1) {
309 | for (int nx = px-1; nx <= px+1; nx++) {
310 | for (int ny = py-1; ny <= py+1; ny++) {
311 | pixDifference = Math.abs( red(imagePixelsCopy[y*img.width+x]) - red(imagePixelsCopy[ny*img.width+nx]));
312 | if ( pixDifference <= threshold && pixels[ny*img.width+nx] == back ) {
313 | pixelLocations.enqueue(ny*img.width+nx);
314 | pixels[ny*img.width+nx] = color(value,value,value);
315 | }
316 | }
317 | }
318 | }
319 | }
320 | }
321 |
322 | /**
323 | * Setup the interactive run of the program.
324 | */
325 | public void runInteractive() {
326 | // load the image from file
327 | img = loadImage(fileName);
328 |
329 | // set the canvas size to match the image size
330 | size(img.width, img.height);
331 |
332 | //print an error message if image was not loaded correctly and terminate
333 | if (img == null) {
334 | System.err.print("The image you are trying to use is inaccessible.\n" +
335 | "If using Eclipse, put your image in the src directory, \n" +
336 | "or specify the full path.\n\n") ;
337 | exit();
338 | }
339 |
340 | //if image is too large for the screen, resize it
341 | float resizeFactor;
342 | if (img.height > 0.8*displayHeight ) {
343 | resizeFactor = (0.8f*displayHeight) / img.height;
344 | img.resize((int)(img.width * resizeFactor),
345 | (int)(img.height*resizeFactor) );
346 | }
347 | if (img.width > 0.8*displayWidth ) {
348 | resizeFactor = (0.8f*displayWidth) / img.width;
349 | img.resize((int)(img.width * resizeFactor),
350 | (int)(img.height*resizeFactor) );
351 | }
352 |
353 | //convert image to grayscale
354 | img.filter(GRAY);
355 |
356 | // get the pixels from the image into a pixels[] array of colors
357 | loadPixels();
358 |
359 | //copy the image pixels to a duplicate array for manipulation
360 | imagePixelsCopy = new int [img.pixels.length];
361 | for (int i =0; i < img.pixels.length; i++){
362 | imagePixelsCopy[i] = img.pixels[i];
363 | }
364 | //instantiate array of seeds
365 | seeds = new ArrayList();
366 |
367 | //display image in the canvas
368 | image(img, 0, 0);
369 |
370 | } //end runInteractive
371 |
372 |
373 | /**
374 | * Setup and run the test mode of the program. The depth first search approach to
375 | * region growing is applied to several predefined images (testFileNames array) using
376 | * the predefined seeds (testSeeds array). The resulting images are saved to the
377 | * disk with names matching the input files, followed by "_DFS_output" followed by the
378 | * original file extension.
379 | */
380 | public void runTestsDFS() {
381 | //generate the directory name to which the files are saved
382 | String outDir = (System.getProperty("user.dir")).replace("bin", "src") +
383 | System.getProperty("file.separator");
384 |
385 | //run the test for all images in the testFileNames array
386 | for (int im = 0; im < testFileNames.length; im++) {
387 |
388 | String file = testFileNames[im];
389 | img = loadImage(file);
390 |
391 | // set the canvas size to match the image size
392 | size(img.width, img.height);
393 |
394 | if (img == null) {
395 | System.err.printf("The image %s is inaccessible.\n", file) ;
396 | }
397 | //convert image to grayscale
398 | img.filter(GRAY);
399 | // get the pixels from the image into a pixels[] array of colors
400 | loadPixels();
401 | //copy the image pixels to a duplicate array for manipulation
402 | imagePixelsCopy = new int [img.pixels.length];
403 | for (int i =0; i < pixels.length; i++){
404 | imagePixelsCopy[i] = img.pixels[i];
405 | }
406 | //get the seeds to be used for the image
407 | seeds = new ArrayList();
408 | for (int i =0; i < testSeeds[im].length; i++)
409 | seeds.add(testSeeds[im][i]);
410 |
411 | //set image to the background (non-region) color
412 | imageBlank(img.pixels);
413 | //generate a region for each seed
414 | while (!seeds.isEmpty() ) {
415 | int seed = seeds.remove(seeds.size()-1);
416 | int value = (int) red(imagePixelsCopy[seed]);
417 | getRegionDFS( seed%img.width, seed/img.width, value, img.pixels, imagePixelsCopy);
418 | }
419 | //generate the name of the output file
420 | String outFile = outDir + file.replace(".", "_DFS_output.");
421 | //save the output file
422 | img.updatePixels();
423 | img.save(outFile);
424 |
425 | }
426 | //terminate the program
427 | exit();
428 | } //end runTestsDFS()
429 |
430 | /**
431 | * Setup and run the test mode of the program. The breadth first search approach to
432 | * region growing is applied to several predefined images (testFileNames array) using
433 | * the predefined seeds (testSeeds array). The resulting images are saved to the
434 | * disk with names matching the input files, followed by "_BFS_output" followed by the
435 | * original file extension.
436 | */
437 | public void runTestsBFS() {
438 | //generate the directory name to which the files are saved
439 | String outDir = (System.getProperty("user.dir")).replace("bin", "src") +
440 | System.getProperty("file.separator");
441 |
442 | //run the test for all images in the testFileNames array
443 | for (int im = 0; im < testFileNames.length; im++) {
444 |
445 | String file = testFileNames[im];
446 | img = loadImage(file);
447 |
448 | // set the canvas size to match the image size
449 | size(img.width, img.height);
450 |
451 | if (img == null) {
452 | System.err.printf("The image %s is inaccessible.\n", file) ;
453 | }
454 | //convert image to grayscale
455 | img.filter(GRAY);
456 | // get the pixels from the image into a pixels[] array of colors
457 | loadPixels();
458 | //copy the image pixels to a duplicate array for manipulation
459 | imagePixelsCopy = new int [img.pixels.length];
460 | for (int i =0; i < pixels.length; i++){
461 | imagePixelsCopy[i] = img.pixels[i];
462 | }
463 | //get the seeds to be used for the image
464 | seeds = new ArrayList();
465 | for (int i =0; i < testSeeds[im].length; i++)
466 | seeds.add(testSeeds[im][i]);
467 |
468 | //set image to the background (non-region) color
469 | imageBlank(img.pixels);
470 | //generate a region for each seed
471 | while (!seeds.isEmpty() ) {
472 | int seed = seeds.remove(seeds.size()-1);
473 | int value = (int) red(imagePixelsCopy[seed]);
474 | getRegionBFS( seed%img.width, seed/img.width, value, img.pixels, imagePixelsCopy);
475 | }
476 | //generate the name of the output file
477 | String outFile = outDir + file.replace(".", "_BFS_output.");
478 | //save the output file
479 | img.updatePixels();
480 | img.save(outFile);
481 |
482 | }
483 | //terminate the program
484 | exit();
485 | } //end runTestsDFS()
486 |
487 | }//end class
488 |
--------------------------------------------------------------------------------
/Homework4/src/proj4/Test.java:
--------------------------------------------------------------------------------
1 | package proj4;
2 |
3 | public class Test {
4 |
5 |
6 | public static void main(String args[]) {
7 | NewQueue test = new NewQueue<>();
8 |
9 | test.enqueue(1);
10 | test.enqueue(2);
11 | test.enqueue(3);
12 |
13 | while(!test.empty()) {
14 | System.out.println(test.peek());
15 | System.out.println(test.dequeue());
16 | }
17 |
18 | }
19 |
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/Homework5/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Homework5/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | Homework5
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Homework5/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/Homework5/Homework 5.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework5/Homework 5.pdf
--------------------------------------------------------------------------------
/Homework5/README.md:
--------------------------------------------------------------------------------
1 | Description:
2 |
3 | Given an input text file compute a list of all unique words and count how many times they occur. Repeat this with linked list and
4 | binary search tree as the choice of the data structure for storing words to compare their relative performance.
5 | The program running time and word count information are written to the standard output (console). The user specified number
6 | of words together with their counts are written to the output file whose name should be provided on the command line.
7 | (see Homework 5.pdf for more info)
8 |
--------------------------------------------------------------------------------
/Homework5/output:
--------------------------------------------------------------------------------
1 | 1803 a
2 | 2859 and
3 | 1742 he
4 | 2980 of
5 | 6529 the
6 | 2126 to
7 |
8 |
--------------------------------------------------------------------------------
/Homework5/src/project5/BSTNode.java:
--------------------------------------------------------------------------------
1 | package project5;
2 |
3 | /**
4 | * Used to implement a binary search tree
5 | * @author Kevin Naughton Jr.
6 | *
7 | */
8 | public class BSTNode implements Comparable {
9 |
10 | //data fields for each individual BSTNode
11 | private String data; //store the data of the BSTNode
12 | private BSTNode left; //store the left reference of the BSTNode
13 | private BSTNode right; //store the right reference of the BSTNode
14 | private int count = 0; //store the count of the BSTNode
15 |
16 | /**
17 | * Creates a BSTNode given a String
18 | * @param item - item to store in BSTNode
19 | */
20 | public BSTNode(String item) {
21 | this.data = item; //set BSTNode's data to item
22 | this.left = null; //set BSTNode's left to null
23 | this.right = null; //set BSTNode's right to null
24 | count++; //increment count
25 | }
26 |
27 | /**
28 | * returns current BSTNode's data
29 | * @return data - current BSTNode's data
30 | */
31 | public String getData() {
32 | return this.data; //return data
33 | }
34 |
35 | /**
36 | * returns current BSTNode's left reference
37 | * @return left - current BSTNode's left reference
38 | */
39 | public BSTNode getLeft() {
40 | return this.left; //return left
41 | }
42 |
43 | /**
44 | * returns current BSTNode's right reference
45 | * @return right - current BSTNode's right reference
46 | */
47 | public BSTNode getRight() {
48 | return this.right; //return right
49 | }
50 |
51 | /**
52 | * Sets current BSTNode's data to newData
53 | * @param newData - data to set to current BSTNode's data
54 | */
55 | public void setData(String newData) {
56 | this.data = newData; //set current BSTNodes data to newData
57 | }
58 |
59 | /**
60 | * Sets current BSTNode's left to newLeft
61 | * @param newLeft - new left reference to set to current BSTNode's left
62 | */
63 | public void setLeft(BSTNode newLeft) {
64 | this.left = newLeft; //set current BSTNode's left reference to newLeft
65 | }
66 |
67 | /**
68 | * Sets current BSTNode's right to newRight
69 | * @param newLeft - new right reference to set to current BSTNode's right
70 | */
71 | public void setRight(BSTNode newRight) {
72 | this.right = newRight; //set current BSTNode's right reference to newRight
73 | }
74 |
75 | /**
76 | * returns current BSTNode's count
77 | * @return count - current BSTNode's count
78 | */
79 | public int getCount() {
80 | return this.count; //return count
81 | }
82 |
83 | /**
84 | * sets current BSTNode's count to newCount
85 | * @param newCount - new count to be assigned to current BSTNode's count
86 | */
87 | public void setCount(int newCount) {
88 | this.count = newCount; //sets current BSTNode's count to newCount
89 | }
90 |
91 | @Override
92 | /**
93 | * overrides default toString method
94 | * compares nodes based on their data
95 | */
96 | public int compareTo(BSTNode o) {
97 | // TODO Auto-generated method stub
98 | return 0;
99 | }
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/Homework5/src/project5/BinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package project5;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Queue;
5 |
6 | /**
7 | * Represents a binary search tree using BSTNodes
8 | * @author Kevin Naughton Jr.
9 | *
10 | */
11 |
12 | public class BinarySearchTree {
13 |
14 | //data fields for BST
15 | private BSTNode root; //store the root of the BST
16 | private int size; //store size of the BST
17 | private ArrayList allWordsInOrder = new ArrayList(); //store all words within text file
18 |
19 |
20 | /**
21 | * Creates a BST by assigning given node to root of BST
22 | * @param node - node to assign to root of BST
23 | */
24 | BinarySearchTree(BSTNode node) {
25 | this.root = node; //set root of BST to given node
26 | size++; //increment size of BST
27 | }
28 |
29 | /**
30 | * Creates an empty BinarySearchTree
31 | */
32 | public BinarySearchTree() {
33 | this.root = null; //set root of BST to null
34 | size = 0; //set size
35 | }
36 |
37 | /**
38 | * returns the size of the BST
39 | * @return size - size of the BST
40 | */
41 | public int getSize() {
42 | return this.size; //return size
43 | }
44 |
45 | /**
46 | * returns the allWordsInOrder data field of the specific BST
47 | * @return allWordsInOrder - ArrayList that when populated holds all words from text file
48 | */
49 | public ArrayList getArraryList() {
50 | return this.allWordsInOrder; //return allWordsInOrder
51 | }
52 |
53 | /**
54 | * @author Joanna Klukowska
55 | * Add an item to this BST.
56 | * @param item a new element to be added to the tree (ignored if null)
57 | */
58 | public void insert(String itemToAdd) {
59 | if (itemToAdd != null) //check if itemToAdd is null
60 | root = recInsert(itemToAdd, root); //if the itemToAdd is not null call recInsert
61 | }
62 |
63 | /*
64 | * @author Joanna Klukowska modified by Kevin Naughton Jr.
65 | * Recursively add an item to this BST.
66 | * @param item item to be added
67 | * @param tree root of the subtree into which the node will be added
68 | * @return reference to this BST after the item was inserted
69 | */
70 | private BSTNode recInsert(String itemToAdd, BSTNode tree) {
71 | if (tree == null) {
72 | // Addition place found
73 | tree = new BSTNode(itemToAdd); //create new node storing itemToAdd
74 | size++; //increment size
75 | } else if (itemToAdd.compareTo(tree.getData()) < 0) //check if itemToAdd comes before current node's data alphabetically
76 | tree.setLeft(recInsert(itemToAdd, tree.getLeft())); // Add in left
77 | // subtree
78 | else if(itemToAdd.compareTo(tree.getData()) > 0) //check if itemToAdd comes before current node's data alphabetically
79 | tree.setRight(recInsert(itemToAdd, tree.getRight())); // Add in right
80 | // subtree
81 | else
82 | tree.setCount(tree.getCount() + 1); //word already exists in BST so increment the count of the node
83 |
84 | return tree;
85 | }
86 |
87 | /**
88 | * @author Joanna Klukowska modified by Kevin Naughton Jr.
89 | * Remove the given item from this BST. If item is null or is not found
90 | * in this BST, the three does not change.
91 | * @param item an element to be removed.
92 | */
93 | public void remove(String itemToRemove) {
94 | if (itemToRemove != null) //check if the itemToRemove is null
95 | root = recRemove(itemToRemove, root); //if the itemToRemove is not null call recRemove
96 | }
97 |
98 | /*
99 | * @author Joanna Klukowska modified by Kevin Naughton Jr.
100 | * Recursively remove an item from this BST.
101 | * @param item item to be removed
102 | * @param tree root of the subtree from which the item will be removed
103 | * @param cutoffValue number to compare each node's count to
104 | * @return reference to this BST after the item was removed
105 | */
106 | private BSTNode recRemove(String itemToRemove, BSTNode tree) {
107 |
108 | if (tree == null)
109 | ; // do nothing, item not found
110 | else if (itemToRemove.compareTo(tree.getData()) < 0) //check if itemToRemove comes before current node's data alphabetically
111 | tree.setLeft(recRemove(itemToRemove, tree.getLeft())); //recursive call on current node's left subtree
112 | else if (itemToRemove.compareTo(tree.getData()) > 0) //check if itemToRemove comes after current node's data alphabetically
113 | tree.setRight(recRemove(itemToRemove, tree.getRight())); //recursive call on current node's right subtree
114 | else {
115 | tree = removeNode(tree); //remove the node whose data is equal to itemToRemove
116 | }
117 | return tree;
118 | }
119 |
120 | /*
121 | * @author Joanna Klukowska modified by Kevin Naughton Jr.
122 | * Remove a particular node - the actual action depends on number of
123 | * childred that the node has.
124 | * @param tree the node to be removed
125 | * @return reference to this BST after node was removed
126 | */
127 | private BSTNode removeNode(BSTNode tree) {
128 | String data = tree.getData(); //store node's data
129 |
130 | //check is left subtree is null
131 | if (tree.getLeft() == null) {
132 | size--; //decrement size of BST
133 | return tree.getRight(); //return node's right subtree
134 | }
135 | //check if right subtree is null
136 | else if (tree.getRight() == null) {
137 | size--; //decrement size of BST
138 | return tree.getLeft(); //return node's left subtree
139 | }
140 | else {
141 | data = getPredecessor(tree.getLeft()); //find predecessor (biggest number in BST that is still < current root)
142 | tree.setData(data); //set current node equal to predecessor
143 | tree.setLeft(recRemove(data, tree.getLeft())); //recursive call of current node's left subtree
144 | return tree;
145 | }
146 | }
147 |
148 | /**
149 | * @author Joanna Klukowska
150 | * Obtains the predecessor of a node (according to BST ordering).
151 | * @param tree node whose predecessor we are after
152 | * @return the data contained in the predecessor node
153 | */
154 | private String getPredecessor(BSTNode tree) {
155 | while (tree.getRight() != null) //traverse down right subtree as far as possible
156 | tree = tree.getRight(); //set current node to current node's right child
157 | return tree.getData(); //return data associated with rightmost node
158 | }
159 |
160 | /**
161 | *
162 | * @param root - node to remove
163 | * @param cutoffValue - lower bound for deciding whether or not a word should be removed
164 | */
165 | private void removeWords(BSTNode root, int cutoffValue) {
166 | if(root != null) { //check if current node is null
167 | removeWords(root.getLeft(), cutoffValue); //recursive call on current node's left subtree
168 | removeWords(root.getRight(), cutoffValue); //recursive call on current node's right subtree
169 | if(root.getCount() < cutoffValue) { //check if current node's count is less than cutoffValue
170 | remove(root.getData()); //remove current node
171 | }
172 | }
173 | }
174 |
175 | /**
176 | * helper method to call callRemoveWords
177 | * @param cutoffValue - lower bound for deciding whether or not a word should be removed
178 | */
179 | public void callRemoveWords(int cutoffValue) {
180 | removeWords(root, cutoffValue); //calls removeWords
181 | }
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 | }
190 |
--------------------------------------------------------------------------------
/Homework5/src/project5/FileParser.java:
--------------------------------------------------------------------------------
1 | package project5;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.util.ArrayList;
6 | import java.util.Scanner;
7 |
8 | /**
9 | * FileParser class is used for parsing text files and retrieving
10 | * lists of alphabetic words stored in such file.
11 | *
12 | * @author Joanna Klukowska
13 | * @version Mar 28, 2014
14 | *
15 | */
16 | public class FileParser {
17 |
18 | private Scanner input;
19 |
20 | /**
21 | * Creates FileParser object given a string containing the name of
22 | * the input file to be parsed.
23 | * @param fileName
24 | * name of the input file to be parsed
25 | * @throws IOException
26 | * if the input file cannot be opened for reading
27 | */
28 | public FileParser ( String fileName ) throws IOException {
29 | File f = new File ( fileName );
30 | //if file does not exist, throw an exception
31 | if ( !f.exists() )
32 | throw new IOException (String.format("File: %s does not exist.", fileName));
33 | //if file cannot be read
34 | if ( !f.canRead() )
35 | throw new IOException (String.format("File: %s cannot be accessed for reading.", fileName));
36 | //connect to the file using Scanner
37 | input = new Scanner( f );
38 |
39 | }
40 |
41 | /**
42 | * Retrieves list of all words from the input file.
43 | * @return
44 | * an array list containing all words from the input file with which the
45 | * File Parser object has been created
46 | * only alphabetic characters are included in the words
47 | */
48 | public ArrayList getAllWords ( ) {
49 | //create a new list to store all the words
50 | ArrayList < String > listOfWords = new ArrayList (5000);
51 |
52 | while ( input.hasNext() ) {
53 | String nextWord = input.next();
54 | nextWord = stripNonLetters( nextWord.toLowerCase() ) ;
55 | if (nextWord.length() != 0 )
56 | listOfWords.add( nextWord );
57 | }
58 | return listOfWords;
59 | }
60 |
61 | /*
62 | * Removes any non-alphabetic characters from token word and
63 | * returns a modified word.
64 | * @param word
65 | * token representing a potential word
66 | * @return
67 | * "pure" words that contain only alphabetic characters
68 | */
69 | private String stripNonLetters (String word ) {
70 | StringBuilder cleanWord = new StringBuilder() ;
71 | char current;
72 | for (int i = 0; i < word.length(); i++) {
73 | current = word.charAt(i);
74 | if (Character.isAlphabetic( current ) )
75 | cleanWord.append( current );
76 | if (current == '\'') break;
77 | }
78 | return cleanWord.toString();
79 | }
80 |
81 |
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/Homework5/src/project5/Homework 5.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kdn251/java-projects/c46cb4a8a43a43cb3028ead7c473b527e5667492/Homework5/src/project5/Homework 5.pdf
--------------------------------------------------------------------------------
/Homework5/src/project5/MostFrequentWords.java:
--------------------------------------------------------------------------------
1 | package project5;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.io.PrintWriter;
6 | import java.util.ArrayList;
7 |
8 | /**
9 | * Computes a list of unique words given a text file
10 | * stores words in both a SortedLinkedList and a BinarySearchTree
11 | * Prunes both structures with a user based cutoff value
12 | * compares relative performance of each structure
13 | * and prints remaining elements of LinkedList after pruning to an output file
14 | * @author Kevin Naughton Jr.
15 | */
16 | public class MostFrequentWords {
17 |
18 | /**
19 | * driver of the program
20 | * @param args - 3 command line arguments
21 | */
22 | public static void main(String[] args) {
23 | //check if three arguments are provided on the command line
24 | if(args.length != 3) {
25 | System.out.println("3 arguments are required for this program to run."); //print error message
26 | System.exit(1); //exit program gracefully
27 | }
28 |
29 | //create file based on first command line argument
30 | File fileToRead = new File(args[0]);
31 |
32 | //check if file given by first command line argument exists
33 | if(!fileToRead.exists()) {
34 | System.out.println("Could not find the specified input file."); //print error message
35 | System.exit(1); //exit program gracefully
36 | }
37 |
38 | //check if program can read from the file given by the first command line argument
39 | if(!fileToRead.canRead()) {
40 | System.out.println("Cannot read specified input file."); //print error message
41 | System.exit(1); //exit program gracefully
42 | }
43 |
44 | //initialize cutoffValue
45 | int cutoffValue = 0;
46 |
47 | //validate the second command line argument
48 | try {
49 | //convert second command line argument to integer
50 | cutoffValue = Integer.parseInt(args[1]); //stores cutoff value of the words that should be printed to the output file
51 | //Ensure the second command line argument is greater than or equal to zero
52 | if(cutoffValue < 0) {
53 | System.out.println("Second command line argument must be an integer greater than or equal to zero."); //print error message
54 | System.exit(1); //exit program gracefully
55 | }
56 | }
57 | //catch any exception an invalid second command argument may cause
58 | catch(Exception E) {
59 | System.out.println("Second argument on the command line must be a positive integer."); //print error message
60 | System.exit(1); //exit program gracefully
61 | }
62 |
63 | //create output file based on third command line argument
64 | File outputFile = new File(args[2]);
65 |
66 | //initialize writer
67 | PrintWriter writer = null;
68 |
69 | //validate the third command line argument
70 | try {
71 | //create PrintWriter object to write to output file
72 | writer = new PrintWriter(outputFile);
73 | }
74 | //catch any exception an invalid third command line argument may cause
75 | catch(Exception e) {
76 | System.out.println("Output file could not be found."); //print error message
77 | System.exit(1); //exit program gracefully
78 | }
79 |
80 | //read in file from first command line argument
81 |
82 | //instantiate FileParser object
83 | FileParser textFile;
84 |
85 | //create ArrayList to hold all words from text file given by the first command line argument
86 | ArrayList allWords = new ArrayList();
87 |
88 | //start time variable for reading file
89 | long startReadTime = System.nanoTime();
90 |
91 | //try to create FileParser object
92 | try {
93 | textFile = new FileParser(args[0]); //set textFile equal to the first command line argument
94 | allWords = textFile.getAllWords(); //populate allWords with all words in given text file
95 | }
96 | //catch IOException
97 | catch (IOException e) {
98 | System.out.println(e); //print error message to user
99 | System.exit(1); //exit program gracefully
100 | }
101 |
102 | //end time variable for reading file
103 | long endReadTime = System.nanoTime();
104 |
105 | //create a linked list to store all words in text file
106 | SortedLinkedList linkedList = new SortedLinkedList();
107 |
108 | //start time variable for linked list
109 | long startTimeLinkedList = System.nanoTime();
110 |
111 | //iterate through allWords
112 | for(int i = 0; i < allWords.size(); i++) {
113 | //create new node to add to linked list
114 | SLLNode node = new SLLNode(allWords.get(i));
115 | //add new node to linked list
116 | linkedList.enqueue(node.getData());
117 | }
118 |
119 | //end time variable for linked list
120 | long endTimeLinkedList = System.nanoTime();
121 |
122 | //store number of words in linked list before pruning
123 | int sizeBeforePruningLL = linkedList.getSize();
124 |
125 | //start time variable for linked list pruning
126 | long startTimeLinkedListPruning = System.nanoTime();
127 |
128 | //prune linked list to remove all words with count lower than cutoffValue
129 | linkedList.remove(cutoffValue);
130 |
131 | //end time variable for linked list pruning
132 | long endTimeLinkedListPruning = System.nanoTime();
133 |
134 | //create a binary search tree to store all words in text file
135 | BinarySearchTree BST = new BinarySearchTree();
136 |
137 | //start time variable for binary search tree
138 | long startTimeBinarySearchTree = System.nanoTime();
139 |
140 | for(int i = 0; i < allWords.size(); i++) {
141 | //create a new BSTNode to add to binary search tree
142 | BSTNode bstNode = new BSTNode(allWords.get(i));
143 | //add new BSTNode to binary search tree
144 | BST.insert(bstNode.getData());
145 | }
146 |
147 | //end time variable binary search tree
148 | long endTimeBinarySearchTree = System.nanoTime();
149 |
150 | //store number of words in binary search tree before pruning
151 | int sizeBeforePruningBST = BST.getSize();
152 |
153 | //start time variable for binary search tree pruning
154 | long startTimeBinarySearchTreePruning = System.nanoTime();
155 |
156 | //prune binary search tree
157 | BST.callRemoveWords(cutoffValue);
158 |
159 | //end time variable for binary search tree pruning
160 | long endTimeBinarySearchTreePruning = System.nanoTime();
161 |
162 | //processing information for reading file
163 | System.out.println("INFO: Reading file took " + (endReadTime - startReadTime) + " ms " + "(~ " + ((endReadTime - startReadTime) / 1000000000) + " seconds).");
164 | System.out.println("INFO: " + allWords.size() + " words read.");
165 |
166 | //print line break in between processing information of reading file and processing information of linked list
167 | System.out.println();
168 |
169 | //processing information for linked list
170 | System.out.println("Processing using Sorted Linked List");
171 | System.out.println("INFO: Creating index took " + (endTimeLinkedList - startTimeLinkedList) + " ms " + "(~ " + ((endTimeLinkedList - startTimeLinkedList) / 1000000000) + " seconds).");
172 | System.out.println("INFO: " + sizeBeforePruningLL + " words stored in the index.");
173 | System.out.println("INFO: Pruning index took " + (endTimeLinkedListPruning - startTimeLinkedListPruning) + " ms " + "(~ " + ((endTimeLinkedListPruning - startTimeLinkedListPruning) / 1000000000) + " seconds).");
174 | System.out.println("INFO: " + linkedList.getSize() + " words remaining after pruning.");
175 |
176 | //print line break in between the processing information for each data structure
177 | System.out.println();
178 |
179 | //processing information for binary search tree
180 | System.out.println("Processing using Recursive BST");
181 | System.out.println("INFO: Creating index took " + (endTimeBinarySearchTree - startTimeBinarySearchTree) + " ms " + "(~ " + ((endTimeBinarySearchTree - startTimeBinarySearchTree) / 1000000000) + " seconds).");
182 | System.out.println("INFO: " + sizeBeforePruningBST + " words stored in index.");
183 | System.out.println("INFO: Pruning index took " + (endTimeBinarySearchTreePruning - startTimeBinarySearchTreePruning) + " ms " + "(~ " + ((endTimeBinarySearchTreePruning - startTimeBinarySearchTreePruning) / 1000000000) + " seconds).");
184 | System.out.println("INFO: " + BST.getSize() + " words remaining after pruning.");
185 |
186 | writer.println(linkedList.printList()); //print all words remaining in linked list after pruning to output file
187 | writer.close(); //close writer
188 |
189 | }
190 |
191 | }
192 |
--------------------------------------------------------------------------------
/Homework5/src/project5/SLLNode.java:
--------------------------------------------------------------------------------
1 | package project5;
2 |
3 | /**
4 | * Used to implement a sorted linked list
5 | * @author Kevin Naughton Jr.
6 | *
7 | */
8 | public class SLLNode implements Comparable {
9 | //data fields for each individual SLLNode
10 | private String data; //store the data of the SLLNode
11 | private SLLNode next; //store the next reference of the SLLNode
12 | private int count = 0; //store the count of the SLLNode
13 |
14 | /**
15 | * SLLNode constructor - creates SLLNode given a string
16 | * @param item - data to store in current SLLNode's data
17 | */
18 | public SLLNode(String item) {
19 | this.data = item; //set current SLLNode's data to item
20 | count++; //increment count
21 | }
22 |
23 | /**
24 | * returns current SLLNode's data
25 | * @return current SLLNode's data
26 | */
27 | public String getData() {
28 | return this.data; //return data
29 | }
30 |
31 | /**
32 | * returns current SLLNode's next reference
33 | * @return current SLLNode's next reference
34 | */
35 | public SLLNode getNext() {
36 | return this.next; //return next
37 | }
38 |
39 | /**
40 | * sets current SLLNode's data to newData
41 | * @param newData - new String to store in current SLLNode's data
42 | */
43 | public void setData(String newData) {
44 | this.data = newData; //set current SLLNode's data to newData
45 | }
46 |
47 | /**
48 | * points current SLLNode's next reference to a new SLLnode
49 | * @param newNext - new next reference to store in current SLLNode's next
50 | */
51 | public void setNext(SLLNode newNext) {
52 | this.next = newNext; //set current SLLNode's next to newNext
53 | }
54 |
55 | /**
56 | * returns current SLLNode's count
57 | * @return count of current SLLNode
58 | */
59 | public int getCount() {
60 | return this.count; //return count
61 | }
62 |
63 | /**
64 | * sets current SLLNode's count to newCount
65 | * @param newCount - new count to assign to current SLLNode's count
66 | */
67 | public void setCount(int newCount) {
68 | this.count = newCount; //set current SLLNode's count to newCount
69 | }
70 |
71 | @Override
72 | /**
73 | * overrides default to string method
74 | * compares SLLNodes based on their data
75 | */
76 | public int compareTo(SLLNode arg0) {
77 | // TODO Auto-generated method stub
78 | return 0;
79 | }
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/Homework5/src/project5/SortedLinkedList.java:
--------------------------------------------------------------------------------
1 | package project5;
2 |
3 | /**
4 | * Represents a sorted linked list using SLLNodes
5 | * @author Kevin Naughton Jr.
6 | *
7 | */
8 | public class SortedLinkedList {
9 |
10 | //DONT FORGET TO READ PROJECT 4 COMMENTS TO NOT LOSE POINTS!
11 |
12 |
13 |
14 | //data fields
15 | private SLLNode head; //points to front of list
16 | private int size; //stores size of list
17 |
18 | /**
19 | * default constructor for SortedLinkedList
20 | */
21 | SortedLinkedList() {
22 | //default constructor
23 | }
24 |
25 | /**
26 | * constructor for SortedLinkedList
27 | * @param node - node to set to head of SortedLinkedList
28 | */
29 | SortedLinkedList(SLLNode node) {
30 | this.head = node; //set head to node
31 | size++; //increment size of SortedLinkedList
32 | }
33 |
34 | /**
35 | * returns the size of the SortedLinkedList
36 | * @return size - size of SortedLinkedList
37 | */
38 | public int getSize() {
39 | return this.size; //return size
40 | }
41 |
42 | /**
43 | * returns the reference to a node that stores a specific piece of data
44 | * @param stringToFind - data to find
45 | * @return current - references node that stores stringToFind
46 | */
47 | public SLLNode get(String stringToFind) {
48 |
49 | SLLNode current = head; //set current to head
50 | while(current.getData().compareTo(stringToFind) != 0) { //continue while current node's data does not equal stringToFind
51 | if(current.getNext() == null) { //account for last node in the SortedLinkedList
52 | if(current.getData().compareTo(stringToFind) != 0) { //check if last node in SortedLinkedList's data is equal to stringToFind
53 | return null; //return
54 | }
55 | }
56 | current = current.getNext(); //set current equal to the next node in the SortedLinkedList
57 |
58 | }
59 | return current; //return the node that stores stringToFind
60 | }
61 |
62 | /**
63 | * adds an item to the SortedLinkedList if it does not already exist
64 | * @param itemToAdd - item to add to SortedLinkedList
65 | */
66 | public void enqueue(String itemToAdd) {
67 | //check if list is empty
68 | if(this.head == null) {
69 | this.head = new SLLNode(itemToAdd); //point head of list to new item
70 | size++; //increment size of the list
71 | }
72 | //store what is returned by get method in nodeToIncrement
73 | SLLNode nodeToIncrement = get(itemToAdd);
74 |
75 | //check if nodeToIncrement is not null
76 | if(nodeToIncrement != null) {
77 | nodeToIncrement.setCount(nodeToIncrement.getCount() + 1); //increment the count of nodeToIncrement by 1
78 | }
79 | //check if nodeToIncrement is null
80 | if(nodeToIncrement == null) {
81 | //create node to add to list
82 | SLLNode newNode = new SLLNode(itemToAdd);
83 |
84 | //create current node to loop through list
85 | SLLNode current = head;
86 |
87 | //instantiate pointToCurrent
88 | SLLNode oneNodeBehindCurrent = null;
89 |
90 | //continue along the list while data of newNode > data of current node
91 | while(!(newNode.getData().compareTo(current.getData()) < 0)) {
92 | //keep pointToCurrent one node behind current
93 | oneNodeBehindCurrent = current;
94 | //point current to next node in the list
95 | current = current.getNext();
96 | }
97 | if(oneNodeBehindCurrent == null) { //check if oneNodeBehindCurrent is null
98 | newNode.setNext(head); //point newNode to head of SortedLinkedList
99 | head = newNode; //set head to newNode
100 | size++; //increment size
101 | }
102 | else {//set oneNodeBehindCurrent's next to newNode
103 | oneNodeBehindCurrent.setNext(newNode);
104 | //point newNode to node after current
105 | newNode.setNext(current);
106 |
107 | //increment size of list
108 | size++;
109 | }
110 | }
111 | }
112 |
113 | /**
114 | * prints all elements in SortedLinkedList
115 | */
116 | public String printList() {
117 | String data = "";
118 | SLLNode current = head; //set current equal to head
119 | while(current != null) { //continue while current node is not null
120 | data = data + current.getCount() + " " + current.getData() + "\n"; //print out current node's count and data
121 | current = current.getNext(); //advance current to next node in SortedLinkedList
122 | }
123 | return data;
124 | }
125 |
126 | /**
127 | * Removes a node from the SortedLinkedList if its count is less than cutoffValue
128 | * @param cutoffValue - lower bound for deciding whether or not a node should be removed from SortedLinkedList
129 | */
130 | public void remove(int cutoffValue) {
131 | //check if the linked list is empty
132 | if(this.head == null) {
133 | return;
134 | }
135 | SLLNode current = head; //point current to front of list
136 |
137 | SLLNode oneNodeBehindCurrent = null; //point oneNodeBehindCurrent to null
138 |
139 | //check if head's count < cutoffValue and the linked list has more than 1 element
140 | if(current.getCount() < cutoffValue && current.getNext() != null) {
141 | head = head.getNext(); //point head to next node in linked list
142 | current = head; //point current to the new head reference
143 | size--;
144 | }
145 | //check if head's count < cutoffValue and linked list only has 1 element (head)
146 | else if(current.getCount() < cutoffValue && current.getNext() == null) {
147 | this.head = null; //remove linked list
148 | }
149 | while(current.getNext() != null) { //continue while there is another node past the current node
150 | oneNodeBehindCurrent = current;
151 | current = current.getNext();
152 | //check if current node's count < cutoffValue
153 | if(current.getCount() < cutoffValue) { //check if current's count is less than cutoffValue
154 | oneNodeBehindCurrent.setNext(current.getNext()); //set oneNodeBehindCurrent's next to current's next
155 | current = oneNodeBehindCurrent; //set current to oneNodeBehindCurrent
156 | size--; //decrement size
157 | }
158 | }
159 | if(current.getCount() < cutoffValue) { //account for last node in SortedLinkedList and check if it's count is less than cutoffValue
160 | current = null; //remove last node in SortedLinkedList
161 | size--; //decrement size
162 | }
163 | }
164 |
165 |
166 | }
167 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | OSLab2Scheduler
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5 | org.eclipse.jdt.core.compiler.compliance=1.8
6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11 | org.eclipse.jdt.core.compiler.source=1.8
12 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/FCFS/input1.txt:
--------------------------------------------------------------------------------
1 | 1 0 1 5 1
2 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/FCFS/input2.txt:
--------------------------------------------------------------------------------
1 | 2 0 1 5 1 0 1 5 1
2 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/FCFS/input3.txt:
--------------------------------------------------------------------------------
1 | 3 0 1 5 1 0 1 5 1 3 1 5 1
2 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/FCFS/input4.txt:
--------------------------------------------------------------------------------
1 | 5 0 3 200 3 0 9 500 2 0 20 500 1 100 1 100 3 100 100 500 1
2 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/FCFS/input5.txt:
--------------------------------------------------------------------------------
1 | 3 1 5 30 2 1 5 30 2 0 5 30 2
2 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/FCFS/input6.txt:
--------------------------------------------------------------------------------
1 | 3 0 1 5 1 0 1 5 1 0 1 10 1
2 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/FCFS/input7.txt:
--------------------------------------------------------------------------------
1 | 3 0 1 20 1 0 1 20 1 10 1 10 1
2 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/src/scheduler/Process.java:
--------------------------------------------------------------------------------
1 | package scheduler;
2 |
3 | public class Process implements Comparable {
4 |
5 | boolean added = false;
6 |
7 | //arrival time of process
8 | protected int arrivalTime;
9 |
10 | //cpu burst of process
11 | protected int cpuBurst;
12 |
13 | //total cpu time required by process
14 | protected int cpuTime;
15 |
16 | //current burst time of process
17 | protected int burst;
18 |
19 | //current blocked time of process
20 | protected int blocked;
21 |
22 | //copy of cpu time remaining
23 | protected int cpuTimeCopy;
24 |
25 | //multiplier of process
26 | protected int multiplier;
27 |
28 | //finishing time of process
29 | protected int finishingTime;
30 |
31 | //total finishing time of process
32 | protected int totalFinishingTime;
33 |
34 | //turnaround time of process
35 | protected int turnaroundTime;
36 |
37 | //input/ouput time of process
38 | protected int inputOutputTime;
39 |
40 | //total input/output time of process
41 | protected int totalInputOutputTime;
42 |
43 | //waiting time of process
44 | protected int waitingTime;
45 |
46 | //current state of process
47 | protected String currentState = "unstarted";
48 |
49 |
50 | Process() {
51 |
52 | //default constructor
53 |
54 | }
55 |
56 | Process(int arrivalTime, int cpuBurst, int cpuTime, int multiplier) {
57 |
58 | //set arrival time attribute of process
59 | this.arrivalTime = arrivalTime;
60 |
61 | //set cpu burst attribute of process
62 | this.cpuBurst = cpuBurst;
63 |
64 | //set cpu time attribute of process
65 | this.cpuTime = cpuTime;
66 |
67 | //set multplier attribute of process
68 | this.multiplier = multiplier;
69 |
70 | }
71 |
72 | @Override
73 | public int compareTo(Process o) {
74 |
75 | //if arrival times are equal
76 | if(this.arrivalTime == o.arrivalTime) {
77 |
78 | return 0;
79 |
80 | }
81 | //if arrival time is earlier...
82 | else if(this.arrivalTime < o.arrivalTime) {
83 |
84 | return -1;
85 |
86 | }
87 |
88 | //if arrival time is later...
89 | else {
90 |
91 | return 1;
92 |
93 | }
94 |
95 | }
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/OSLab2Scheduler/src/scheduler/README.txt:
--------------------------------------------------------------------------------
1 | Kevin Naughton Jr.
2 | Operating Systems Scheduler Lab
3 |
4 | COMPILE
5 | In terminal, navigate to the directory that contains Scheduler.java, Process.java, and the input files. Once you are in the correct directory, run the following command to compile the program:
6 | javac Scheduler.java Process.java
7 |
8 | RUN
9 | Run the following command where “inputfile.txt” is the desired input file (ensure that the input file is within the same directory as the source code):
10 | java Scheduler input1.txt
11 |
12 | RUN WITH VERBOSE FLAG
13 | Run the following command where “inputfile.txt” is the desired input file (ensure that the input file is within the same directory as the source code):
14 | java Scheduler --verbose input1.txt
15 |
16 | EXAMPLE
17 |
18 | RUN
19 | javac Scheduler.java Process.java input1.txt
20 | java Scheduler input1.txt
21 |
22 | RUN WITH VERBOSE FLAG
23 | javac Scheduler.java Process.java input1.txt
24 | java Scheduler --verbose input1.txt
--------------------------------------------------------------------------------