Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Primes algo changed, tests added #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/Runner.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import threads.ThreadKeeper;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Runner {
public static void main(String[] args) {
int threadPool;
int startNumber;
int endNumber;

Scanner scanner = new Scanner(System.in);
System.out.println("Enter thread pool size:");
threadPool = scanner.nextInt();
Expand All @@ -17,8 +16,9 @@ public static void main(String[] args) {
System.out.println("Enter end number:");
endNumber = scanner.nextInt();

List<Integer> primes = new ArrayList<>();
ThreadKeeper threadKeeper = new ThreadKeeper(threadPool, startNumber, endNumber, primes);
threadKeeper.start();

ThreadKeeper threadKeeper = new ThreadKeeper(threadPool, startNumber, endNumber, args!=null);
threadKeeper.start();

}
}
3 changes: 3 additions & 0 deletions src/resources/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
hehe karp-rabin algo is cool, cause it is karp-rabin algo!
karp-rabin algo is cool,ho hehe cause it is karp-rabin algo!
hehe
23 changes: 23 additions & 0 deletions src/resources/text.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
— Ну, у тебя не навыпуск… Интеллигенты паршивые!.. Вот ищу, ищу, тут такое дело большое: босяков этих самых развелось, мальчишек — по улице пройти нельзя, и по квартирам лазят. Мне говорят: это ваше дело, наробразовское… Ну?

— А что — «ну»?

— Да вот это самое: никто не хочет, кому ни говорю — руками и ногами, зарежут, говорят. Вам бы это кабинетик, книжечки… Очки вон надел…

— Ну, добре, — сказал я с облегчением, потому что в тот момент ничего страшнее комнат губсовнархоза для меня не было.

— Деньги?..

— Деньги есть. Вот получи.

— И на коров?

— С коровами подождешь, там стекол нет. А на год смету составишь.

— Неловко так, посмотреть бы не мешало раньше.

— Я уже смотрел… что ж, ты лучше меня увидишь? Поезжай — и все.

— Ну, добре, — сказал я с облегчением, потому что в тот момент ничего страшнее комнат губсовнархоза для меня не было.

— Вот это молодец! — сказал завгубнаробразом. — Действуй! Дело святое!
10 changes: 6 additions & 4 deletions src/sequences/hierarchy/Searcher.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package sequences.hierarchy;

import sequences.karprabin.data.ResultSet;
import sequences.karprabin.impl.RK;
import sequences.karprabin.impl.KarpRabinAlgorithm;

public class Searcher extends Thread {

Expand All @@ -12,7 +12,7 @@ public class Searcher extends Thread {
private String pattern = "";
private ResultSet matches;
private ResultSet searchResult;
private RK searcherImpl = new RK();
private KarpRabinAlgorithm searcherImpl = new KarpRabinAlgorithm();

public Searcher(Displayer displayer, int minPatternSize, String text, String name) {
super(name);
Expand All @@ -36,8 +36,9 @@ private ResultSet checkAllPatterns(int patternSize) {
ResultSet lastMatches = new ResultSet();
for (int i = 0; i < text.length() - pattern.length() - 1; i++) {
pattern = text.substring(i, i + patternSize);
if (searcherImpl.find(text, pattern).found())
lastMatches = searcherImpl.find(text, pattern);
lastMatches = searcherImpl.find(text, pattern);
if (lastMatches.found())
return lastMatches;
}
// lastMatches = searcherImpl.find(text, pattern).results().stream().flatMap(a -> Stream.of(a.start)).collect(Collectors.toList());
return lastMatches;
Expand All @@ -49,6 +50,7 @@ public void run() {
searchingRunning = true;
while (pattern.length() < text.length() / 2) {
for (int i = minPatternSize; i <= text.length() / 2; i++) {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!NEW SIZE OF PATTERN " + i + "!!!!!!!!!!!!!!!!!!!!");
searchResult = checkAllPatterns(i);
if (searchResult.found()) {
matches = searchResult;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sequences.karprabin.data.Result;
import sequences.karprabin.data.ResultSet;

public class RK{
public class KarpRabinAlgorithm {

private static final int COEFFICIENT = 2;
private static final int MAX_VALUE = Integer.MAX_VALUE;
Expand Down
61 changes: 55 additions & 6 deletions src/threads/ExecutorServiceRunner.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,61 @@
package threads;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.*;

public class ExecutorServiceRunner {
int threadPool;
int startNumber;
int endNumber;
ExecutorService service = Executors.newFixedThreadPool(2);
private static List<List<Integer>> setTasks(int threadPoolSize, int startNumber, int endNumber) {
List<List<Integer>> tasks = new ArrayList<>();
for (int i = 0; i < threadPoolSize; i++) {
tasks.add(new ArrayList<Integer>());
}
for (int i = startNumber; i <= endNumber; i++) {
tasks.get(i % threadPoolSize).add(i);
}
return tasks;
}

public static void main(String[] args) {

long startTime;
long endTime;
int threadPool;
int startNumber;
int endNumber;
List<Integer> primes = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter thread pool size:");
threadPool = scanner.nextInt();
ExecutorService service = Executors.newFixedThreadPool(threadPool);
System.out.println("Enter start number:");
startNumber = scanner.nextInt();
System.out.println("Enter end number:");
endNumber = scanner.nextInt();
List<List<Integer>> tasks = setTasks(threadPool, startNumber, endNumber);
List<Future<Integer>>futures = new ArrayList<>();
startTime = System.currentTimeMillis();
for (int i = 0; i < tasks.size(); i++) {
futures.add(service.submit(new PrimeNumberCounterCallable(i, tasks.get(i), primes, args != null)));
}
for (int i = 0; i <futures.size() ; i++) {
try {
futures.get(i).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
endTime = System.currentTimeMillis();

System.out.println(primes.size());
System.out.println("primes = " + primes);
System.out.println();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(endTime - startTime);
System.out.println("Time on calculations = " + cal.get(Calendar.MILLISECOND));
}
}
50 changes: 29 additions & 21 deletions src/threads/PrimeNumberCounter.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,28 @@
import java.util.List;

public class PrimeNumberCounter extends Thread {
List<Integer> task;
List<Integer> primes;
List<Integer> localPrimes = new ArrayList<>();
private boolean isSynchronized;
private int id;
private int number;
private int startNumber;
private int endNumber;
private boolean isPrime;
List<Integer> primes;
List<Integer> localPrimes = new ArrayList<>();

public PrimeNumberCounter(int id, int number, List<Integer> primes) {
public PrimeNumberCounter(int id, List<Integer> task, List<Integer> primes, boolean isSynchronized) {
this.id = id;
this.number = number;
this.task = task;
this.primes = primes;
this.isSynchronized = isSynchronized;
}

public PrimeNumberCounter(int id, int startNumber, int endNumber, List<Integer> primes) {
public PrimeNumberCounter(int id, int number, List<Integer> primes) {
this.id = id;
this.startNumber = startNumber;
this.endNumber = endNumber;
this.number = number;
this.primes = primes;
}

private void calculate(int number){
private void calculate(int number) {
isPrime = true;
for (int i = 2; i < number / 2; i++) {
if (number % i == 0) {
Expand All @@ -34,23 +34,31 @@ private void calculate(int number){
}
}
if (isPrime) {
localPrimes.add(number);
localPrimes.add(number);
if (isSynchronized) {
synchronized (primes) {
primes.add(number);
}
}
}
}

private void saveAllPrimes(List<Integer> localPrimes) {
synchronized (primes) {
primes.addAll(localPrimes);
}
}

@Override
public void run() {
if(startNumber == 0 && endNumber == 0){
calculate(number);
} else {
for (int i = startNumber; i < endNumber; i++) {
calculate(i);
}
}
System.out.println("localPrimes of Thread-" + id + " = " + localPrimes);
synchronized (primes){
primes.addAll(localPrimes);

for (int i = 0; i < task.size(); i++) {
calculate(task.get(i));
}

System.err.println("localPrimes of Thread-" + id + " = " + localPrimes);
if (!isSynchronized)
saveAllPrimes(localPrimes);
}

public void setNumber(int number) {
Expand Down
77 changes: 77 additions & 0 deletions src/threads/PrimeNumberCounterCallable.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package threads;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

public class PrimeNumberCounterCallable implements Callable<Integer> {
List<Integer> task;
List<Integer> primes;
List<Integer> localPrimes = new ArrayList<>();
private boolean isSynchronized;
private int id;
private int number;
private int startNumber;
private int endNumber;
private boolean isPrime;

public PrimeNumberCounterCallable(int id, List<Integer> task, List<Integer> primes, boolean isSynchronized) {
this.id = id;
this.task = task;
this.primes = primes;
this.isSynchronized = isSynchronized;
}

public PrimeNumberCounterCallable(int id, int number, List<Integer> primes) {
this.id = id;
this.number = number;
this.primes = primes;
}

public PrimeNumberCounterCallable(int id, int startNumber, int endNumber, List<Integer> primes) {
this.id = id;
this.startNumber = startNumber;
this.endNumber = endNumber;
this.primes = primes;
}

private void calculate(int number) {
isPrime = true;
for (int i = 2; i < number / 2; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
localPrimes.add(number);
if (isSynchronized) {
synchronized (primes) {
primes.add(number);
}
}
}
}

private void saveAllPrimes(List<Integer> localPrimes) {
synchronized (primes) {
primes.addAll(localPrimes);
}
}

public void setNumber(int number) {
this.number = number;
}

@Override
public Integer call() throws Exception {
for (int i = 0; i < task.size(); i++) {
calculate(task.get(i));
}

System.err.println("localPrimes of Thread-" + id + " = " + localPrimes);
if (!isSynchronized)
saveAllPrimes(localPrimes);
return 42;
}
}
Loading