Skip to content

Commit 284b37e

Browse files
committed
Adding homeworks
1 parent 9e389fb commit 284b37e

File tree

22 files changed

+1803
-0
lines changed

22 files changed

+1803
-0
lines changed
1.19 MB
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
import java.io.File;
2+
import java.io.FileNotFoundException;
3+
import java.util.*;
4+
import java.util.concurrent.CyclicBarrier;
5+
import java.util.concurrent.locks.Lock;
6+
import java.util.concurrent.locks.ReentrantLock;
7+
8+
public class MultithreadedSearch {
9+
//keyword to be searched in each file.
10+
static String wordSearched;
11+
12+
//path of each one of the files to search.
13+
static ArrayList<String> filesSearched = new ArrayList<>();
14+
15+
//total occurrences of the word in every file.
16+
static int totalOccurrences = 0;
17+
18+
//option to change the execution.
19+
static boolean liveResults = false;
20+
21+
public static void main(String[] args) throws InterruptedException {
22+
//first argument is the word to be searched.
23+
//cast to lower case to make the searching easier.
24+
wordSearched = args[0].toLowerCase();
25+
26+
//process each argument from the second to the last.
27+
for(int i=1;i<(args.length);i++){
28+
//if the user used the option -liveResults, change the static variable of this class.
29+
if(args[i].equals("-liveResults")){
30+
liveResults = true;
31+
continue;
32+
}
33+
34+
//store all file names.
35+
filesSearched.add(args[i]);
36+
}
37+
38+
//create a array of threads to search for the word we need to find.
39+
SearchingThread[] threadsToSearch = new SearchingThread[filesSearched.size()];
40+
41+
//if liveResult is selected as a option, print the live results.
42+
if(liveResults){
43+
System.out.println("LIVE RESULTS:\n");
44+
}
45+
46+
for(int i=0;i<filesSearched.size();i++){
47+
//create and start each thread.
48+
threadsToSearch[i] = new SearchingThread(filesSearched.get(i));
49+
threadsToSearch[i].start();
50+
}
51+
52+
//join all the threads.
53+
for(Thread thread:threadsToSearch){
54+
thread.join();
55+
}
56+
57+
//print the summary.
58+
System.out.println("\nTHE SUMMARY:\n");
59+
60+
//each thread is printed in parallell to each other.
61+
Thread[] printThreads = new Thread[filesSearched.size()];
62+
63+
for(int i=0;i<filesSearched.size();i++){
64+
//create and start threads to print the result of each thread.
65+
printThreads[i] = new PrintableThread(threadsToSearch[i]);
66+
printThreads[i].start();
67+
}
68+
69+
for(Thread thread:printThreads){
70+
//join the printing threads.
71+
thread.join();
72+
}
73+
74+
//print final result.
75+
System.out.println("\nTOTAL: "+totalOccurrences+" occurrence"+(totalOccurrences>1?"s":"")+" of keyword "+wordSearched);
76+
}
77+
78+
//class to print threads' data in parallel.
79+
static class PrintableThread extends Thread{
80+
//thread to be printed.
81+
private final SearchingThread thread;
82+
83+
//constructor
84+
PrintableThread(SearchingThread thread){
85+
this.thread = thread;
86+
}
87+
88+
//override the run method to be run in parallel.
89+
@Override
90+
public void run(){
91+
//print the thread data.
92+
System.out.println(thread);
93+
}
94+
}
95+
96+
//class to search a word in a file in parallel.
97+
static class SearchingThread extends Thread{
98+
//path of the file the thread is searching in.
99+
private final String path_file;
100+
//total occurrences of the word in the file.
101+
private int total=0;
102+
103+
//constructor.
104+
SearchingThread(String path_file){
105+
this.path_file = path_file;
106+
}
107+
108+
109+
@Override
110+
public void run(){
111+
//try to open the file.
112+
try {
113+
//scanner for the file.
114+
Scanner fileInput = new Scanner(new File(path_file));
115+
116+
//keep note of the number of lines of the file.
117+
int lineNum=0;
118+
119+
while(fileInput.hasNext()){
120+
//count lines.
121+
lineNum++;
122+
123+
//get the next line from the file.
124+
//cast to lowercase to make it easier to search the pattern.
125+
String line = fileInput.nextLine().toLowerCase();
126+
127+
//linear search in the line for the word.
128+
for(int i=0;i<line.length()-wordSearched.length()+1;i++){
129+
if(line.substring(i,i+wordSearched.length()).equals(wordSearched)){
130+
total++;
131+
132+
//print the live result.
133+
if(liveResults){
134+
System.out.println(countOccurrence(lineNum));
135+
}
136+
}
137+
}
138+
}
139+
140+
//lock the totalOccurrences variable to add and then unlock.
141+
synchronized (this) {
142+
totalOccurrences += total;
143+
}
144+
}
145+
catch (FileNotFoundException e) {
146+
e.printStackTrace();
147+
}
148+
}
149+
150+
//print the live result.
151+
public String countOccurrence(int line){
152+
return path_file+":\t"+total+" "+"occurrence"+(total>1?"s":"") + " at line "+line;
153+
}
154+
155+
//print the data of the thread.
156+
@Override
157+
public String toString(){
158+
return path_file+":\t"+total+" "+"occurrence"+(total>1?"s":"");
159+
}
160+
}
161+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
In the time since the end of communism and isolationism, Albania has extended its responsibilities and position in
2+
continental and international affairs, developing and establishing friendly relations with other countries around the
3+
world. The country's foreign policy priorities are its accession into the European Union (EU), the international
4+
recognition of Kosovo and the expulsion of Cham Albanians, as well as helping and protecting the rights of the Albanians
5+
in Kosovo, Montenegro, North Macedonia, Greece, Serbia, Italy and the Diaspora.[172]
6+
7+
Albania's admission into the North Atlantic Treaty Organisation (NATO) was considered by Albanian politicians
8+
to be a significant ambition for the country's foreign policy. The country has been extensively engaged with the
9+
NATO and has maintained its position as a stability factor and a strong ally of the United States and the European
10+
Union (EU) in the region of the Balkans. Albania maintains strong ties with the United States ever after it supported
11+
the Albania's independence and democracy.[173] Nowadays, both countries have signed a number of agreements and treaties.
12+
In 2007, Albania welcomed George W. Bush who became the first President of the United States ever to visit the country.
13+
14+
Albania and Kosovo are culturally, socially and economically very closely rooted due to the Albanian majority
15+
population in Kosovo. In 1998, the country contributed in supporting allied efforts to end the humanitarian
16+
tragedy in Kosovo and secure the peace after the NATO bombing of Yugoslavia.
17+
18+
Albania has been an active member of the United Nations since 1955. They country took on membership for the United
19+
Nations Economic and Social Council from 2005 to 2007 as well as in 2012.[174] It served as vice president of the
20+
ECOSOC in 2006 and 2013.[174] In 2014, it also joined the United Nations Human Rights Council from 2015 to 2017 and
21+
was elected vice president in 2015.[175] Albania is a full member of numerous international organisations inclusively
22+
the Council of Europe, International Organisation for Migration, World Health Organization, Union for the Mediterranean,
23+
Organisation of Islamic Cooperation, Organization for Security and Co-operation in Europe, International Monetary Fund,
24+
World Trade Organization and La Francophonie.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
Albania declared independence from the Ottoman Empire on 28 November 1912, accompanied with the establishment of the
2+
Senate and Government by the Assembly of Vlorë on 4 December 1912.[74][75][76][77] Its sovereignty was recognised by
3+
the Conference of London. On 29 July 1913, the Treaty of London delineated the borders of the country and its neighbors,
4+
leaving many Albanians outside Albania, predominantly partitioned between Montenegro, Serbia and Greece.[78]
5+
6+
Headquartered in Vlorë, the International Commission of Control was established on 15 October 1913 to take care of the
7+
administration of newly established Albania, until its own political institutions were in order.[79][80] The International
8+
Gendarmerie was established as the first law enforcement agency of the Principality of Albania. In November, the first
9+
gendarmerie members arrived in the country. Prince of Albania Wilhelm of Wied (Princ Vilhelm Vidi) was selected as the
10+
first prince of the principality.[81] On 7 March, he arrived in the provisional capital of Durrës and started to organise
11+
his government, appointing Turhan Pasha Përmeti to form the first Albanian cabinet.
12+
13+
In November 1913, the Albanian pro-Ottoman forces had offered the throne of Albania to the Ottoman war Minister of
14+
Albanian origin, Ahmed Izzet Pasha.[82] The pro-Ottoman peasants believed that the new regime was a tool of the six
15+
Christian Great Powers and local landowners, that owned half of the arable land.[83]
16+
17+
In February 1914, the Autonomous Republic of Northern Epirus was proclaimed in Gjirokastër by the local Greek population
18+
against incorporation to Albania. This initiative was short-lived, and in 1921 the southern provinces were incorporated
19+
into the Albanian Principality.[84][85] Meanwhile, the revolt of Albanian peasants against the new Albanian regime erupted
20+
under the leadership of the group of Muslim clerics gathered around Essad Pasha Toptani, who proclaimed himself the savior
21+
of Albania and Islam.[86][87] In order to gain support of the Mirdita Catholic volunteers from the northern part of Albania,
22+
Prince Wied appointed their leader, Prênk Bibë Doda, to be the foreign minister of the Principality of Albania.
23+
In May and June 1914, the International Gendarmerie was joined by Isa Boletini and his men, mostly from Kosovo,[88]
24+
and northern Mirdita Catholics, were defeated by the rebels who captured most of Central Albania by the end of August
25+
1914.[89] The regime of Prince Wied collapsed, and he left the country on 3 September 1914.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Albania declared independence from the Ottoman Empire on 28 November 1912, accompanied with the establishment of the
2+
Senate and Government by the Assembly of Vlorë on 4 December 1912.[74][75][76][77] Its sovereignty was recognised by
3+
the Conference of London. On 29 July 1913, the Treaty of London delineated the borders of the country and its neighbors,
4+
leaving many Albanians outside Albania, predominantly partitioned between Montenegro, Serbia and Greece.[78]
5+
6+
Headquartered in Vlorë, the International Commission of Control was established on 15 October 1913 to take care of the
7+
administration of newly established Albania, until its own political institutions were in order.[79][80] The International
8+
Gendarmerie was established as the first law enforcement agency of the Principality of Albania. In November, the first
9+
gendarmerie members arrived in the country. Prince of Albania Wilhelm of Wied (Princ Vilhelm Vidi) was selected as the
10+
first prince of the principality.[81] On 7 March, he arrived in the provisional capital of Durrës and started to organise
11+
his government, appointing Turhan Pasha Përmeti to form the first Albanian cabinet.
12+
13+
In November 1913, the Albanian pro-Ottoman forces had offered the throne of Albania to the Ottoman war Minister of
14+
Albanian origin, Ahmed Izzet Pasha.[82] The pro-Ottoman peasants believed that the new regime was a tool of the six
15+
Christian Great Powers and local landowners, that owned half of the arable land.[83]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import java.util.concurrent.locks.Lock;
2+
import java.util.concurrent.locks.ReentrantLock;
3+
4+
public class ProbabilityEstimation {
5+
//2 patterns we want to calculate the probability of appearing first.
6+
static String pattern1;
7+
static String pattern2;
8+
9+
//default values for the number of trials and the number of threads used.
10+
static int trials = 1000000;
11+
static int threadsNum = 10;
12+
13+
//total occurrences found from all the threads.
14+
static int pattern1Found = 0;
15+
static int pattern2Found = 0;
16+
17+
public static void main(String[] args) throws InterruptedException {
18+
//get arguments from the args and depending on the length, process them.
19+
pattern1 = args[0];
20+
pattern2 = args[1];
21+
22+
//if there is a third argument.
23+
if(args.length>2){
24+
trials = Integer.parseInt(args[2]);
25+
}
26+
27+
//if there is a forth argument.
28+
if(args.length>3){
29+
threadsNum = Integer.parseInt(args[3]);
30+
}
31+
32+
//create array of threads.
33+
Thread[] threads = new Thread[threadsNum];
34+
35+
for(int i=0;i<threadsNum;i++){
36+
//create custom threads giving their rank as a property.
37+
threads[i] = new GenerateCoinFlips(i);
38+
39+
//start each thread.
40+
threads[i].start();
41+
}
42+
43+
//join each thread with the main thread.
44+
for(Thread thread:threads){
45+
thread.join();
46+
}
47+
48+
//print the result.
49+
System.out.println("Estimated values with "+trials+" random experiments with "+threadsNum+" threads:");
50+
System.out.println("The probability that "+pattern1+" appears first is "+calculateProbability(pattern1Found));
51+
System.out.println("The probability that "+pattern2+" appears first is "+calculateProbability(pattern2Found));
52+
}
53+
54+
//just to make sure the number of trials isn't 0.
55+
static double calculateProbability(int occurrences){
56+
return trials!=0?(double)occurrences/trials:0;
57+
}
58+
59+
//class inheriting from Thread class.
60+
static class GenerateCoinFlips extends Thread{
61+
//Pattern generated by flipping coins to be compared to our patterns.
62+
private String patternGenerated = "";
63+
//rank to separate the work as evenly as possible.
64+
private final int rank;
65+
66+
//number of locally found patterns by this thread.
67+
private int pattern1FoundHere = 0;
68+
private int pattern2FoundHere = 0;
69+
70+
//constructor.
71+
GenerateCoinFlips(int rank){
72+
this.rank = rank;
73+
}
74+
75+
//override the run method.
76+
@Override
77+
public void run(){
78+
//while the thread has not reached the number of trials.
79+
for(int i=rank;i<trials;){
80+
//generate a random H for heads and T for tails.
81+
String randomChar = ((int)(Math.random()*2) == 1) ? "H":"T";
82+
83+
//concatenate the pattern it generated until now with the new "H":"T" char.
84+
patternGenerated = patternGenerated.concat(randomChar);
85+
86+
//if the generated pattern ending matches with one of the patterns, increment its count and reset the pattern generated.
87+
if(patternGenerated.endsWith(pattern1)){
88+
pattern1FoundHere++;
89+
patternGenerated = "";
90+
//helps since i%threadNum = rank always.
91+
i+=threadsNum;
92+
}
93+
if(patternGenerated.endsWith(pattern2)){
94+
pattern2FoundHere++;
95+
patternGenerated = "";
96+
//helps since i%threadNum = rank always.
97+
i+=threadsNum;
98+
}
99+
}
100+
101+
//synchronize this block to assure data integrity.
102+
synchronized (this) {
103+
pattern1Found += pattern1FoundHere;
104+
pattern2Found += pattern2FoundHere;
105+
}
106+
}
107+
}
108+
}

0 commit comments

Comments
 (0)