From 78f4ba73a02b93ede59840a4f52ebf324c4e44d2 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 19 Mar 2016 06:32:21 +0200 Subject: [PATCH 01/32] Refactored HomeWork of Module5 --- src/module5/ArrMinMaxSortTestDrive.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/module5/ArrMinMaxSortTestDrive.java b/src/module5/ArrMinMaxSortTestDrive.java index c93eeb6..2d6edd6 100644 --- a/src/module5/ArrMinMaxSortTestDrive.java +++ b/src/module5/ArrMinMaxSortTestDrive.java @@ -14,6 +14,11 @@ public static void main(String[] args) { System.out.println("Max Array's value is " + getMaxValue(arr)); System.out.println("Min Array's value is " + getMinValue(arr)); + + System.out.println("Sort arr using 'bubble sort':" + Arrays.toString(doBubbleSort(arr))); + } + + public static int[] doBubbleSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { @@ -21,13 +26,11 @@ public static void main(String[] args) { arr[j] = arr[j + 1]; arr[j + 1] = tmp; } - } } - System.out.println("Sort arr using 'bubble sort':" + Arrays.toString(arr)); + return arr; } - public static int getMaxValue(int[] arr) { int maxValue = arr[0]; for (int i = 0; i < arr.length; i++) { From 695d951f43969a33741ca6fe03f68985a55163e0 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Mon, 21 Mar 2016 18:55:35 +0200 Subject: [PATCH 02/32] Music Store --- src/module6/Directory.java | 29 ------- src/module6/File.java | 8 -- src/module6/FileTestDrive.java | 56 ------------- src/module6/WrongCharException.java | 17 ---- .../AudioFile.java | 19 ++--- .../ex1_aboutfile_Exception/Directory.java | 34 ++++++++ src/module6/ex1_aboutfile_Exception/File.java | 22 +++++ .../FileTestDrive.java | 50 +++++++++++ .../ImgFile.java | 17 +--- .../TextFile.java | 17 +--- .../WrongCharException.java | 25 ++++++ .../Guitar.java | 9 ++ .../MusicInstrumentTestDrive.java | 82 +++++++++++++++++++ .../MusicInstruments.java | 13 +++ .../MusicStore.java | 41 ++++++++++ .../ex2_musicinstruments_exception/Piano.java | 9 ++ .../Trumpet.java | 9 ++ 17 files changed, 308 insertions(+), 149 deletions(-) delete mode 100644 src/module6/Directory.java delete mode 100644 src/module6/File.java delete mode 100644 src/module6/FileTestDrive.java delete mode 100644 src/module6/WrongCharException.java rename src/module6/{ => ex1_aboutfile_Exception}/AudioFile.java (55%) create mode 100644 src/module6/ex1_aboutfile_Exception/Directory.java create mode 100644 src/module6/ex1_aboutfile_Exception/File.java create mode 100644 src/module6/ex1_aboutfile_Exception/FileTestDrive.java rename src/module6/{ => ex1_aboutfile_Exception}/ImgFile.java (56%) rename src/module6/{ => ex1_aboutfile_Exception}/TextFile.java (56%) create mode 100644 src/module6/ex1_aboutfile_Exception/WrongCharException.java create mode 100644 src/module6/ex2_musicinstruments_exception/Guitar.java create mode 100644 src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java create mode 100644 src/module6/ex2_musicinstruments_exception/MusicInstruments.java create mode 100644 src/module6/ex2_musicinstruments_exception/MusicStore.java create mode 100644 src/module6/ex2_musicinstruments_exception/Piano.java create mode 100644 src/module6/ex2_musicinstruments_exception/Trumpet.java diff --git a/src/module6/Directory.java b/src/module6/Directory.java deleted file mode 100644 index 9d753d3..0000000 --- a/src/module6/Directory.java +++ /dev/null @@ -1,29 +0,0 @@ -package module6; - - -public class Directory { - private TextFile textFile; - private ImgFile imgFile; - private AudioFile audioFile; - - public Directory() { - this.textFile = new TextFile(); - textFile.setSizeOfKeeping("99 megabytes"); - this.imgFile = new ImgFile(); - imgFile.setSizeOfKeeping("919 megabytes"); - this.audioFile = new AudioFile(); - audioFile.setSizeOfKeeping("929 megabytes"); - } - - public String getTextFile() { - return textFile.getSizeOfKeeping(); - } - - public String getImgFile() { - return imgFile.getSizeOfKeeping(); - } - - public String getAudioFile() { - return audioFile.getSizeOfKeeping(); - } -} diff --git a/src/module6/File.java b/src/module6/File.java deleted file mode 100644 index 72a7d88..0000000 --- a/src/module6/File.java +++ /dev/null @@ -1,8 +0,0 @@ -package module6; - -abstract public class File { - public abstract void printFileDetails(); -} - - - diff --git a/src/module6/FileTestDrive.java b/src/module6/FileTestDrive.java deleted file mode 100644 index 145cc29..0000000 --- a/src/module6/FileTestDrive.java +++ /dev/null @@ -1,56 +0,0 @@ -package module6; - -import java.util.Scanner; - -public class FileTestDrive { - public static void main(String[] args) { - Directory directory = new Directory(); - Scanner scanner = new Scanner(System.in); - System.out.println(); - try { - System.out.println("Gues what type of file is right:"); - System.out.println("These are our variants: "); - System.out.println("AudioFile"); - System.out.println("ImgFile"); - System.out.println("TextFile"); - System.out.println("Media"); - System.out.println("Your answer"); - System.out.println(); - System.out.println("Write your answer:"); - String answer = scanner.nextLine(); - if (answer.contains("AudioFile") || answer.contains("ImgFile") || answer.contains("TextFile")) { - System.out.println("Wright answer!!!"); - } else { - throw new WrongCharException(answer); - } - } catch (WrongCharException e) { - System.out.println("Fatal Error: you'v wrote " + "\"" + e.getType() + "\"" + " and it is wrong answer so we will die!!! :)))"); - } - System.out.println(); - - File[] files = new File[3]; - files[0] = new AudioFile(); - files[1] = new TextFile(); - files[2] = new ImgFile(); - String[] arrCheckSizeOfKeeping = new String[3]; - arrCheckSizeOfKeeping[0] = directory.getAudioFile(); - arrCheckSizeOfKeeping[1] = directory.getImgFile(); - arrCheckSizeOfKeeping[2] = directory.getTextFile(); - - System.out.println("There such types of files in Directory as:"); - try { - for (int i = 0; i < files.length; i++) { - files[i].printFileDetails(); - } - } catch (Exception e) { - System.out.println(e); - } - - - System.out.println(); - System.out.println("Some others information about files:"); - System.out.println("AudioFile - max size of keeping is " + directory.getAudioFile() + ";"); - System.out.println("TextFile - max size of keeping is " + directory.getImgFile() + ";"); - System.out.println("ImgFile - max size of keeping is " + directory.getTextFile() + "."); - } -} diff --git a/src/module6/WrongCharException.java b/src/module6/WrongCharException.java deleted file mode 100644 index 7d40010..0000000 --- a/src/module6/WrongCharException.java +++ /dev/null @@ -1,17 +0,0 @@ -package module6; - -public class WrongCharException extends Exception { - private String type; - - public WrongCharException(String type) { - this.type = type; - } - - public void setType(String type) { - this.type = type; - } - - public String getType() { - return type; - } -} diff --git a/src/module6/AudioFile.java b/src/module6/ex1_aboutfile_Exception/AudioFile.java similarity index 55% rename from src/module6/AudioFile.java rename to src/module6/ex1_aboutfile_Exception/AudioFile.java index fa8f908..8bb353b 100644 --- a/src/module6/AudioFile.java +++ b/src/module6/ex1_aboutfile_Exception/AudioFile.java @@ -1,24 +1,17 @@ -package module6; +package module6.ex1_aboutfile_Exception; public class AudioFile extends File { - private String type; private String sizeOfKeeping; - AudioFile() { - this.type = "AudioFile"; + public AudioFile() { this.sizeOfKeeping = "100 megabytes"; } + // we put @Override annotation to confirm that we indeed implementing (overrding) + // parrent's method. + @Override public void printFileDetails() { - System.out.println("Type: " + getType() + "; "); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; + System.out.println("Type: " + getType() + "; sizeOfKeeping=" + sizeOfKeeping); } public void setSizeOfKeeping(String sizeOfKeeping) { diff --git a/src/module6/ex1_aboutfile_Exception/Directory.java b/src/module6/ex1_aboutfile_Exception/Directory.java new file mode 100644 index 0000000..30cc2af --- /dev/null +++ b/src/module6/ex1_aboutfile_Exception/Directory.java @@ -0,0 +1,34 @@ +package module6.ex1_aboutfile_Exception; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Directory { + // Usually directory contains just list of files + // you can deal with files (create, copy, delete), you can list directory to + // find out how many files it contains, or what files it contains. + // I removed methods like getSizeOfKeeping, because directory doesn't care + // what kinds of files it contains and how large they can be. + // Directory can be empty, so there can be no files inside. + private List files; + + public Directory() { + files = new ArrayList(); + } + + public void putFile(File file) { + files.add(file); + } + + public List listFiles() { + return Collections.unmodifiableList(files); + } + + public void printFilesDetails() { + System.out.println("There such types of files in Directory as:"); + for (File file : files) { + file.printFileDetails(); + } + } +} diff --git a/src/module6/ex1_aboutfile_Exception/File.java b/src/module6/ex1_aboutfile_Exception/File.java new file mode 100644 index 0000000..d2c5332 --- /dev/null +++ b/src/module6/ex1_aboutfile_Exception/File.java @@ -0,0 +1,22 @@ +package module6.ex1_aboutfile_Exception; + +abstract public class File { + // type is protected, so it will be available for all subclasses + protected String type; + + // the super constructor is called before subclass constructor, so type will + // be initialized when we create new TextFile() or new AudioFile or new + // ImgFile() objects + public File() { + this.type = this.getClass().getSimpleName(); + } + + public abstract void printFileDetails(); + + public String getType() { + return type; + } +} + + + diff --git a/src/module6/ex1_aboutfile_Exception/FileTestDrive.java b/src/module6/ex1_aboutfile_Exception/FileTestDrive.java new file mode 100644 index 0000000..85f41d9 --- /dev/null +++ b/src/module6/ex1_aboutfile_Exception/FileTestDrive.java @@ -0,0 +1,50 @@ +package module6.ex1_aboutfile_Exception; + +import java.util.Scanner; + +public class FileTestDrive { + public static void main(String[] args) { + // extracted logic into different methods to make it easier to read. + testConsoleReadNoExceptions(); + testDirectory(); + } + + private static void testConsoleReadNoExceptions() { + try { + readUsersAnswer(); + } catch (WrongCharException e) { + e.printStackTrace(); + } + System.out.println(); + } + + private static void readUsersAnswer() throws WrongCharException { + // this is auto-closable try-catch, it will close resources opened in + // try() + try (Scanner scanner = new Scanner(System.in);) { + System.out.println("Gues what type of file is right:"); + System.out.println("These are our variants: "); + System.out.println("AudioFile"); + System.out.println("ImgFile"); + System.out.println("TextFile"); + System.out.println("Media"); + System.out.println("Your answer"); + System.out.println(); + System.out.println("Write your answer:"); + String answer = scanner.nextLine(); + if (answer.contains("AudioFile") || answer.contains("ImgFile") || answer.contains("TextFile")) { + System.out.println("Wright answer!!!"); + } else { + throw new WrongCharException("Fatal Error: you'v wrote " + "\"" + answer + "\"" + " and it is wrong answer so we will die!!! :)))"); + } + } + } + + private static void testDirectory() { + Directory directory = new Directory(); + directory.putFile(new AudioFile()); + directory.putFile(new TextFile()); + directory.putFile(new ImgFile()); + directory.printFilesDetails(); + } +} \ No newline at end of file diff --git a/src/module6/ImgFile.java b/src/module6/ex1_aboutfile_Exception/ImgFile.java similarity index 56% rename from src/module6/ImgFile.java rename to src/module6/ex1_aboutfile_Exception/ImgFile.java index 54c3b82..76b9d38 100644 --- a/src/module6/ImgFile.java +++ b/src/module6/ex1_aboutfile_Exception/ImgFile.java @@ -1,24 +1,15 @@ -package module6; +package module6.ex1_aboutfile_Exception; public class ImgFile extends File { - String type; private String sizeOfKeeping; - ImgFile() { - this.type = "ImgFile"; + public ImgFile() { this.sizeOfKeeping = "50 megabytes"; } + @Override public void printFileDetails() { - System.out.println("Type: " + getType() + "; "); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; + System.out.println("Type: " + getType() + "; sizeOfKeeping=" + sizeOfKeeping); } public void setSizeOfKeeping(String sizeOfKeeping) { diff --git a/src/module6/TextFile.java b/src/module6/ex1_aboutfile_Exception/TextFile.java similarity index 56% rename from src/module6/TextFile.java rename to src/module6/ex1_aboutfile_Exception/TextFile.java index b791aa6..9731ec2 100644 --- a/src/module6/TextFile.java +++ b/src/module6/ex1_aboutfile_Exception/TextFile.java @@ -1,24 +1,15 @@ -package module6; +package module6.ex1_aboutfile_Exception; public class TextFile extends File { - String type; private String sizeOfKeeping; - TextFile() { - this.type = "TextFile"; + public TextFile() { this.sizeOfKeeping = "25 megabytes"; } + @Override public void printFileDetails() { - System.out.println("Type: " + getType() + "; "); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; + System.out.println("Type: " + getType() + "; sizeOfKeeping=" + sizeOfKeeping); } public void setSizeOfKeeping(String sizeOfKeeping) { diff --git a/src/module6/ex1_aboutfile_Exception/WrongCharException.java b/src/module6/ex1_aboutfile_Exception/WrongCharException.java new file mode 100644 index 0000000..636b5a9 --- /dev/null +++ b/src/module6/ex1_aboutfile_Exception/WrongCharException.java @@ -0,0 +1,25 @@ +package module6.ex1_aboutfile_Exception; + +public class WrongCharException extends Exception { + // Exception is designed to keep message and other exceptions details + // When we create new Exception's class, usually we initialize all types of + // constructor as Exception class has. + // Исключением разработан, чтобы хранить сообщение и другие детали исключения + // Когда мы создаем новый класс Исключения, обычно мы инициализируем все виды + // конструкторов которые имеет класс Исключение. + public WrongCharException(String message) { + super(message); + } + + public WrongCharException() { + super(); + } + + public WrongCharException(String message, Throwable cause) { + super(message, cause); + } + + public WrongCharException(Throwable cause) { + super(cause); + } +} diff --git a/src/module6/ex2_musicinstruments_exception/Guitar.java b/src/module6/ex2_musicinstruments_exception/Guitar.java new file mode 100644 index 0000000..b30471a --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/Guitar.java @@ -0,0 +1,9 @@ +package module6.ex2_musicinstruments_exception; + +public class Guitar extends MusicInstruments { + + @Override + public String getType() { + return "guitar"; + } +} diff --git a/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java new file mode 100644 index 0000000..791efb6 --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java @@ -0,0 +1,82 @@ +package module6.ex2_musicinstruments_exception; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MusicInstrumentTestDrive { + public static void main(String[] args) { + MusicStore musicStore = new MusicStore(); + ArrayList guitars = new ArrayList<>(); + for (int i = 0; i < 26; i++) { + guitars.add(new Guitar()); + } + musicStore.setGuitars(guitars); + + ArrayList pianos = new ArrayList<>(); + for (int i = 0; i < 56; i++) { + pianos.add(new Piano()); + } + musicStore.setPianos(pianos); + + ArrayList trumpets = new ArrayList<>(); + for (int i = 0; i < 41; i++) { + trumpets.add(new Trumpet()); + } + musicStore.setTrumpets(trumpets); + + System.out.println(musicStore); + + Map order = new HashMap<>(); + order.put("guitars", 23); + order.put("pianos", 2); + order.put("trumpets", 32); + + List guitarsToRemove = prepareOrder(musicStore, order); + System.out.println("removed guitars: " + guitarsToRemove.size()); + List pianosToRemove = prepareOrder(musicStore, order); + System.out.println("removed pianos: " + pianosToRemove.size()); + List trumpetsToRemove = prepareOrder(musicStore, order); + System.out.println("removed trumpets: " + trumpetsToRemove.size()); + + + System.out.println(musicStore); + + } + + private static List prepareOrder(MusicStore musicStore, Map order) { + ArrayList result = new ArrayList<>(); + + List guitars = musicStore.getGuitars(); + int numberOfGuitarsToRemove = order.get("guitars"); + + if (musicStore.getGuitars().size() < numberOfGuitarsToRemove) throw new IllegalStateException(); + List guitarsToRemove = musicStore.getGuitars().subList(0, numberOfGuitarsToRemove); + List guitarsToStay = musicStore.getGuitars().subList(numberOfGuitarsToRemove, guitars.size()); + musicStore.setGuitars(guitarsToStay); + result.addAll(guitarsToRemove); + + + List pianos = musicStore.getPianos(); + int numberOfPianoToRemove = order.get("pianos"); + + if (musicStore.getPianos().size() < numberOfPianoToRemove) throw new IllegalStateException(); + List pianosToRemove = musicStore.getPianos().subList(0, numberOfPianoToRemove); + List pianosToStay = musicStore.getPianos().subList(numberOfPianoToRemove, pianos.size()); + musicStore.setPianos(pianosToStay); + result.addAll(pianosToRemove); + + + List trumpets = musicStore.getTrumpets(); + int numberOfTrumpetsToRemove = order.get("trumpets"); + + if (musicStore.getTrumpets().size() < numberOfTrumpetsToRemove) throw new IllegalStateException(); + List trumpetsToRemove = musicStore.getTrumpets().subList(0, numberOfTrumpetsToRemove); + List trumpetsToStay = musicStore.getTrumpets().subList(numberOfTrumpetsToRemove, trumpets.size()); + musicStore.setTrumpets(trumpetsToStay); + result.addAll(trumpetsToRemove); + + return result; + } +} diff --git a/src/module6/ex2_musicinstruments_exception/MusicInstruments.java b/src/module6/ex2_musicinstruments_exception/MusicInstruments.java new file mode 100644 index 0000000..5de0199 --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/MusicInstruments.java @@ -0,0 +1,13 @@ +package module6.ex2_musicinstruments_exception; + +abstract public class MusicInstruments { + public abstract String getType(); + + @Override + public String toString() { + return "MusicInstrument {" + getType() + "}"; + } + +} + + diff --git a/src/module6/ex2_musicinstruments_exception/MusicStore.java b/src/module6/ex2_musicinstruments_exception/MusicStore.java new file mode 100644 index 0000000..66b4118 --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/MusicStore.java @@ -0,0 +1,41 @@ +package module6.ex2_musicinstruments_exception; + +import java.util.List; + +public class MusicStore { + List pianos; + List guitars; + List trumpets; + + public List getPianos() { + return pianos; + } + + public void setPianos(List pianos) { + this.pianos = pianos; + } + + public List getGuitars() { + return guitars; + } + + public void setGuitars(List guitars) { + this.guitars = guitars; + } + + public List getTrumpets() { + return trumpets; + } + + protected void setTrumpets(List trumpets) { + this.trumpets = trumpets; + } + + @Override + public String toString() { + return "MusicStore {" + "guitars=" + guitars.size() + ", pianos=" + pianos.size() + ", trumpets=" + trumpets.size() + '}'; + + } +} + + diff --git a/src/module6/ex2_musicinstruments_exception/Piano.java b/src/module6/ex2_musicinstruments_exception/Piano.java new file mode 100644 index 0000000..44ed863 --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/Piano.java @@ -0,0 +1,9 @@ +package module6.ex2_musicinstruments_exception; + +public class Piano extends MusicInstruments { + + @Override + public String getType() { + return "piano"; + } +} \ No newline at end of file diff --git a/src/module6/ex2_musicinstruments_exception/Trumpet.java b/src/module6/ex2_musicinstruments_exception/Trumpet.java new file mode 100644 index 0000000..ac40a1e --- /dev/null +++ b/src/module6/ex2_musicinstruments_exception/Trumpet.java @@ -0,0 +1,9 @@ +package module6.ex2_musicinstruments_exception; + +public class Trumpet extends MusicInstruments { + + @Override + public String getType() { + return "trumpet"; + } +} \ No newline at end of file From cefefe8f695bad2ba8734d50fb9b4c498381054f Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 26 Mar 2016 12:00:44 +0200 Subject: [PATCH 03/32] Next variant... --- .../MusicInstrumentTestDrive.java | 91 +++++++------------ .../MusicStore.java | 34 ++++--- 2 files changed, 49 insertions(+), 76 deletions(-) diff --git a/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java index 791efb6..ce676b4 100644 --- a/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java +++ b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java @@ -8,75 +8,50 @@ public class MusicInstrumentTestDrive { public static void main(String[] args) { MusicStore musicStore = new MusicStore(); - ArrayList guitars = new ArrayList<>(); - for (int i = 0; i < 26; i++) { - guitars.add(new Guitar()); - } - musicStore.setGuitars(guitars); - - ArrayList pianos = new ArrayList<>(); - for (int i = 0; i < 56; i++) { - pianos.add(new Piano()); - } - musicStore.setPianos(pianos); - - ArrayList trumpets = new ArrayList<>(); - for (int i = 0; i < 41; i++) { - trumpets.add(new Trumpet()); - } - musicStore.setTrumpets(trumpets); + musicStore.setGuitars(52); + musicStore.setPianos(26); + musicStore.setTrumpets(89); System.out.println(musicStore); Map order = new HashMap<>(); - order.put("guitars", 23); - order.put("pianos", 2); - order.put("trumpets", 32); + order.put("guitar", 1); + order.put("piano", 6); + order.put("trumpet", 1); List guitarsToRemove = prepareOrder(musicStore, order); - System.out.println("removed guitars: " + guitarsToRemove.size()); List pianosToRemove = prepareOrder(musicStore, order); - System.out.println("removed pianos: " + pianosToRemove.size()); List trumpetsToRemove = prepareOrder(musicStore, order); - System.out.println("removed trumpets: " + trumpetsToRemove.size()); - - - System.out.println(musicStore); + System.out.println(musicStore + " after removed."); } private static List prepareOrder(MusicStore musicStore, Map order) { - ArrayList result = new ArrayList<>(); - - List guitars = musicStore.getGuitars(); - int numberOfGuitarsToRemove = order.get("guitars"); - - if (musicStore.getGuitars().size() < numberOfGuitarsToRemove) throw new IllegalStateException(); - List guitarsToRemove = musicStore.getGuitars().subList(0, numberOfGuitarsToRemove); - List guitarsToStay = musicStore.getGuitars().subList(numberOfGuitarsToRemove, guitars.size()); - musicStore.setGuitars(guitarsToStay); - result.addAll(guitarsToRemove); - - - List pianos = musicStore.getPianos(); - int numberOfPianoToRemove = order.get("pianos"); - - if (musicStore.getPianos().size() < numberOfPianoToRemove) throw new IllegalStateException(); - List pianosToRemove = musicStore.getPianos().subList(0, numberOfPianoToRemove); - List pianosToStay = musicStore.getPianos().subList(numberOfPianoToRemove, pianos.size()); - musicStore.setPianos(pianosToStay); - result.addAll(pianosToRemove); - - - List trumpets = musicStore.getTrumpets(); - int numberOfTrumpetsToRemove = order.get("trumpets"); - - if (musicStore.getTrumpets().size() < numberOfTrumpetsToRemove) throw new IllegalStateException(); - List trumpetsToRemove = musicStore.getTrumpets().subList(0, numberOfTrumpetsToRemove); - List trumpetsToStay = musicStore.getTrumpets().subList(numberOfTrumpetsToRemove, trumpets.size()); - musicStore.setTrumpets(trumpetsToStay); - result.addAll(trumpetsToRemove); - + int numberOfGuitarsToRemove = order.get("guitar"); + int numberOfPianosToRemove = order.get("piano"); + int numberOfTrumpetsToRemove = order.get("trumpet"); + + if (musicStore.getGuitars() < numberOfGuitarsToRemove) + throw new IllegalStateException("There no such amount instruments in the store."); + if (musicStore.getPianos() < numberOfPianosToRemove) + throw new IllegalStateException("There no such amount instruments in the store."); + if (musicStore.getTrumpets() < numberOfTrumpetsToRemove) + throw new IllegalStateException("There no such amount instruments in the store."); + + musicStore.setGuitars(musicStore.getGuitars() - numberOfGuitarsToRemove); + musicStore.setPianos(musicStore.getPianos() - numberOfPianosToRemove); + musicStore.setTrumpets(musicStore.getTrumpets() - numberOfTrumpetsToRemove); + + List result = new ArrayList<>(); + for (int i = 0; i < numberOfGuitarsToRemove; i++) { + result.add(new Guitar()); + } + for (int i = 0; i < numberOfPianosToRemove; i++) { + result.add(new Piano()); + } + for (int i = 0; i < numberOfTrumpetsToRemove; i++) { + result.add(new Trumpet()); + } return result; } -} +} \ No newline at end of file diff --git a/src/module6/ex2_musicinstruments_exception/MusicStore.java b/src/module6/ex2_musicinstruments_exception/MusicStore.java index 66b4118..0df9436 100644 --- a/src/module6/ex2_musicinstruments_exception/MusicStore.java +++ b/src/module6/ex2_musicinstruments_exception/MusicStore.java @@ -1,39 +1,37 @@ package module6.ex2_musicinstruments_exception; -import java.util.List; - public class MusicStore { - List pianos; - List guitars; - List trumpets; + int pianos; + int guitars; + int trumpets; - public List getPianos() { - return pianos; + public void setPianos(int pianos) { + this.pianos = pianos; } - public void setPianos(List pianos) { - this.pianos = pianos; + public void setGuitars(int guitars) { + this.guitars = guitars; } - public List getGuitars() { - return guitars; + public void setTrumpets(int trumpets) { + this.trumpets = trumpets; } - public void setGuitars(List guitars) { - this.guitars = guitars; + public int getPianos() { + return pianos; } - public List getTrumpets() { - return trumpets; + public int getGuitars() { + return guitars; } - protected void setTrumpets(List trumpets) { - this.trumpets = trumpets; + public int getTrumpets() { + return trumpets; } @Override public String toString() { - return "MusicStore {" + "guitars=" + guitars.size() + ", pianos=" + pianos.size() + ", trumpets=" + trumpets.size() + '}'; + return "MusicStore contains " + "guitars=" + guitars + ", pianos=" + pianos + ", trumpets=" + trumpets; } } From 90a832a1d819d1c22262d0bbe655577b4e48af7b Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 26 Mar 2016 12:12:34 +0200 Subject: [PATCH 04/32] with comments --- .../MusicInstrumentTestDrive.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java index ce676b4..ec27767 100644 --- a/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java +++ b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java @@ -20,10 +20,11 @@ public static void main(String[] args) { order.put("trumpet", 1); List guitarsToRemove = prepareOrder(musicStore, order); + System.out.println("removed guitars" + guitarsToRemove.size()); //выводит общее кол-во инструментов, всеравно что написать "removed pianos" + pianosToRemove.size() List pianosToRemove = prepareOrder(musicStore, order); List trumpetsToRemove = prepareOrder(musicStore, order); - System.out.println(musicStore + " after removed."); + System.out.println(musicStore + " after removed.");//здесь выводит кол-во позиции, которые нужно удалить, умноженные на три } private static List prepareOrder(MusicStore musicStore, Map order) { From 594bfe7bc0a77d62ce51916e2cadac45cd814a3a Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sun, 27 Mar 2016 20:01:16 +0300 Subject: [PATCH 05/32] Work with text file --- Text.txt | 1 + src/module10/CezarCryptoMethods.java | 31 +++++++++++++++ src/module10/DecryptionCezar.java | 56 ++++++++++++++++++++++++++++ src/module10/EncryptCezar.java | 37 ++++++++++++++++++ src/module10/WorkWithText.java | 53 ++++++++++++++++++++++++++ 5 files changed, 178 insertions(+) create mode 100644 Text.txt create mode 100644 src/module10/CezarCryptoMethods.java create mode 100644 src/module10/DecryptionCezar.java create mode 100644 src/module10/EncryptCezar.java create mode 100644 src/module10/WorkWithText.java diff --git a/Text.txt b/Text.txt new file mode 100644 index 0000000..a80fd1e --- /dev/null +++ b/Text.txt @@ -0,0 +1 @@ +Java \ No newline at end of file diff --git a/src/module10/CezarCryptoMethods.java b/src/module10/CezarCryptoMethods.java new file mode 100644 index 0000000..5011dba --- /dev/null +++ b/src/module10/CezarCryptoMethods.java @@ -0,0 +1,31 @@ +package module10; + +public class CezarCryptoMethods { + + protected static final int n = 27; + protected static char[] upper = + new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', + 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' '}; + + protected static char[] lower = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '}; + + public static int findIndUpper(char c) { + int rez = -1; + + for (int i = 0; i < upper.length; ++i) { + if (c == upper[i]) rez = i; + } + return rez; + } + + public static int findIndLower(char c) { + int rez = -1; + + for (int i = 0; i < lower.length; ++i) { + if (c == lower[i]) rez = i; + } + return rez; + } + +} diff --git a/src/module10/DecryptionCezar.java b/src/module10/DecryptionCezar.java new file mode 100644 index 0000000..8e7ce19 --- /dev/null +++ b/src/module10/DecryptionCezar.java @@ -0,0 +1,56 @@ +package module10; + +public class DecryptionCezar extends CezarCryptoMethods { + private String output; + + public DecryptionCezar(String text, int k) { + StringBuilder dec = new StringBuilder(); + + for (int i = 0; i < text.length(); ++i) { + char c = text.charAt(i); + + if (findIndLower(c) == -1) { + int x = (findIndUpper(c) - k + n) % n; + dec.append(upper[x]); + } + if (findIndUpper(c) == -1) { + int x = (findIndLower(c) - k + n) % n; + dec.append(lower[x]); + } + if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { + dec.append(c); + } + } + + this.output = dec.toString(); + } + + public DecryptionCezar(EncryptCezar enc) { + int k = enc.getK(); + String input = enc.getEncText(); + StringBuilder dec = new StringBuilder(); + + for (int i = 0; i < input.length(); ++i) { + char c = input.charAt(i); + + if (findIndLower(c) == -1) { + int x = (findIndUpper(c) - k + n) % n; + dec.append(upper[x]); + } + if (findIndUpper(c) == -1) { + int x = (findIndLower(c) - k + n) % n; + dec.append(lower[x]); + } + if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { + dec.append(c); + } + } + + this.output = dec.toString(); + } + + public String getDecText() { + return this.output; + } + +} diff --git a/src/module10/EncryptCezar.java b/src/module10/EncryptCezar.java new file mode 100644 index 0000000..2a0bdb9 --- /dev/null +++ b/src/module10/EncryptCezar.java @@ -0,0 +1,37 @@ +package module10; + +public class EncryptCezar extends CezarCryptoMethods { + private String output; + private int k; + + public EncryptCezar(String text, int k) { + this.k = k; + StringBuilder output = new StringBuilder(); + + for (int i = 0; i < text.length(); ++i) { + char c = text.charAt(i); + + if (findIndLower(c) == -1) { + int y = (findIndUpper(c) + k) % n; + output.append(upper[y]); + } + if (findIndUpper(c) == -1) { + int y = (findIndLower(c) + k) % n; + output.append(lower[y]); + } + if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { + output.append(c); + } + } + this.output = output.toString(); + } + + public String getEncText() { + return this.output; + } + + public int getK() { + return this.k; + } + +} diff --git a/src/module10/WorkWithText.java b/src/module10/WorkWithText.java new file mode 100644 index 0000000..52a4697 --- /dev/null +++ b/src/module10/WorkWithText.java @@ -0,0 +1,53 @@ +package module10; + + +import java.io.*; +import java.util.Scanner; + +/* +Реализовать сохранение/загрузку текстового сообщения в файл с предварительным +шифрованием/расшифрованием. Предусмотреть обработку различных ошибок ввода/вывода +*/ +public class WorkWithText { + public static void main(String[] args) throws IOException { + + String text = "Java"; + + EncryptCezar enc = new EncryptCezar(text, 2); + DecryptionCezar dec = new DecryptionCezar(enc.getEncText(), enc.getK()); + + try (FileWriter writer = new FileWriter("Text.txt")) { + writer.write(enc.getEncText()); + writer.flush(); + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + + try (FileReader reader = new FileReader("Text.txt")) { + int c; + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + + System.out.println(); + + try (FileWriter writer = new FileWriter("Text.txt")) { + writer.write(dec.getDecText()); + writer.flush(); + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + + try (FileReader reader = new FileReader("Text.txt")) { + int c; + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } +} From 0133fcfa626c5616307157d9d7b6fe06dd3e4b67 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Mon, 28 Mar 2016 06:35:15 +0300 Subject: [PATCH 06/32] ...for work on work --- src/module8/Guitar.java | 24 +++++ src/module8/MusicInstrumentTestDrive.java | 59 ++++++++++++ src/module8/MusicInstruments.java | 6 ++ src/module8/MusicStore.java | 33 +++++++ src/module8/Piano.java | 24 +++++ src/module8/Trumpet.java | 24 +++++ src/module9/AudioFile.java | 22 +++++ src/module9/CaesarAlgorithmTestDrive.java | 21 +++++ src/module9/CeasarAlgorithm.java | 108 ++++++++++++++++++++++ src/module9/File.java | 8 ++ 10 files changed, 329 insertions(+) create mode 100644 src/module8/Guitar.java create mode 100644 src/module8/MusicInstrumentTestDrive.java create mode 100644 src/module8/MusicInstruments.java create mode 100644 src/module8/MusicStore.java create mode 100644 src/module8/Piano.java create mode 100644 src/module8/Trumpet.java create mode 100644 src/module9/AudioFile.java create mode 100644 src/module9/CaesarAlgorithmTestDrive.java create mode 100644 src/module9/CeasarAlgorithm.java create mode 100644 src/module9/File.java diff --git a/src/module8/Guitar.java b/src/module8/Guitar.java new file mode 100644 index 0000000..26fb20d --- /dev/null +++ b/src/module8/Guitar.java @@ -0,0 +1,24 @@ +package module8; + +public class Guitar extends MusicInstruments { + private String typeOfInstruments; + private int priceOfInstruments; + + public Guitar(String typeOfInstruments, int priceOfInstruments) { + this.typeOfInstruments = typeOfInstruments; + this.priceOfInstruments = priceOfInstruments; + } + + public int getPriceOfInstruments() { + return priceOfInstruments; + } + + public String getTypeOfInstruments() { + return typeOfInstruments; + } + + @Override + public String toString() { + return typeOfInstruments + " " + priceOfInstruments; + } +} diff --git a/src/module8/MusicInstrumentTestDrive.java b/src/module8/MusicInstrumentTestDrive.java new file mode 100644 index 0000000..25a1302 --- /dev/null +++ b/src/module8/MusicInstrumentTestDrive.java @@ -0,0 +1,59 @@ +package module8; + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; +import java.util.Iterator; + +public class MusicInstrumentTestDrive { + public static void main(String[] args) { + /* ArrayList guitarList = new ArrayList<>(); + ArrayList pianoList = new ArrayList<>(); + ArrayList trumpetList = new ArrayList<>(); + ArrayList musicInstruments = new ArrayList<>(); + + musicInstruments.add(List ); + + pianoList.add(new Piano("My piano", 25)); + pianoList.add(new Piano("Your piano", 66)); + pianoList.add(new Piano("Our piano", 77)); + + guitarList.add(new Guitar("My guitar", 2)); + guitarList.add(new Guitar("Your guitar", 6)); + guitarList.add(new Guitar("Our guitar", 7)); + + trumpetList.add(new Trumpet("My trumpet", 256)); + trumpetList.add(new Trumpet("Your trumpet", 666)); + trumpetList.add(new Trumpet("Our trumpet", 776)); + + System.out.println("List of Collections"); + System.out.println("Type of instruments " + "Price of instruments"); + + + guitarList.stream().forEach(instrument -> System.out.println(instrument + " ")); + pianoList.stream().forEach(instrument -> System.out.println(instrument + " ")); + trumpetList.stream().forEach(instrument -> System.out.println(instrument + " ")); +/* + TreeSet ts = new TreeSet(); + + ts.add("b"); + ts.add("a"); + ts.add("d"); + ts.add("c"); + + // get element in Iterator + Iterator it = ts.iterator(); + + // get descending order of elements + //Iterator it=ts.descendingIterator(); + + while (it.hasNext()) { + String value = (String) it.next(); + + System.out.println("Value :" + value); + } + } + */ + + } +} diff --git a/src/module8/MusicInstruments.java b/src/module8/MusicInstruments.java new file mode 100644 index 0000000..e319f42 --- /dev/null +++ b/src/module8/MusicInstruments.java @@ -0,0 +1,6 @@ +package module8; + +abstract public class MusicInstruments { + protected String typeOfInstruments; + protected int priceOfInstruments; +} diff --git a/src/module8/MusicStore.java b/src/module8/MusicStore.java new file mode 100644 index 0000000..e5c1563 --- /dev/null +++ b/src/module8/MusicStore.java @@ -0,0 +1,33 @@ +package module8; + +import java.util.List; + +public class MusicStore { + private List guitars; + private List pianos; + private List trumpets; + + public List getTrumpets() { + return trumpets; + } + + public void setTrumpets(List trumpets) { + this.trumpets = trumpets; + } + + public List getGuitars() { + return guitars; + } + + public void setGuitars(List guitars) { + this.guitars = guitars; + } + + public List getPianos() { + return pianos; + } + + public void setPianos(List pianos) { + this.pianos = pianos; + } +} \ No newline at end of file diff --git a/src/module8/Piano.java b/src/module8/Piano.java new file mode 100644 index 0000000..3dbe1ca --- /dev/null +++ b/src/module8/Piano.java @@ -0,0 +1,24 @@ +package module8; + +public class Piano extends MusicInstruments { + private String typeOfInstruments; + private int priceOfInstruments; + + public Piano(String typeOfInstruments, int priceOfInstruments) { + this.typeOfInstruments = typeOfInstruments; + this.priceOfInstruments = priceOfInstruments; + } + + public int getPriceOfInstruments() { + return priceOfInstruments; + } + + public String getTypeOfInstruments() { + return typeOfInstruments; + } + + @Override + public String toString() { + return typeOfInstruments + " " + priceOfInstruments; + } +} \ No newline at end of file diff --git a/src/module8/Trumpet.java b/src/module8/Trumpet.java new file mode 100644 index 0000000..2a923dc --- /dev/null +++ b/src/module8/Trumpet.java @@ -0,0 +1,24 @@ +package module8; + +public class Trumpet extends MusicInstruments { + private String typeOfInstruments; + private int priceOfInstruments; + + public Trumpet(String typeOfInstruments, int priceOfInstruments) { + this.typeOfInstruments = typeOfInstruments; + this.priceOfInstruments = priceOfInstruments; + } + + public int getPriceOfInstruments() { + return priceOfInstruments; + } + + public String getTypeOfInstruments() { + return typeOfInstruments; + } + + @Override + public String toString() { + return typeOfInstruments + " " + priceOfInstruments; + } +} \ No newline at end of file diff --git a/src/module9/AudioFile.java b/src/module9/AudioFile.java new file mode 100644 index 0000000..eaf083f --- /dev/null +++ b/src/module9/AudioFile.java @@ -0,0 +1,22 @@ +package module9; + +public class AudioFile extends File { + + private String typeOfFile; + + public AudioFile(String typeOfFile) { + this.typeOfFile = typeOfFile; + } + + public String getTypeOfFile() { + return typeOfFile; + } + + @Override + public String toString() { + return "AudioFile{" + + "typeOfFile='" + typeOfFile + '\'' + + '}'; + } + +} \ No newline at end of file diff --git a/src/module9/CaesarAlgorithmTestDrive.java b/src/module9/CaesarAlgorithmTestDrive.java new file mode 100644 index 0000000..e563765 --- /dev/null +++ b/src/module9/CaesarAlgorithmTestDrive.java @@ -0,0 +1,21 @@ +package module9; +/* +Реализовать шифрование текста с помощью алгоритма Цезаря. +Зашифровать и расшифровать текстовое представление коллекци обьектов из ДЗ из Модуля 3: ООП в Java +*/ + +import com.sun.xml.internal.fastinfoset.util.CharArray; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CaesarAlgorithmTestDrive { + public static void main(String[] args) { +ArrayList audioFiles = new ArrayList<>(); + audioFiles.add(new AudioFile("Album")); + CeasarAlgorithm ceasarAlgorithm = new CeasarAlgorithm(); + + + } +} diff --git a/src/module9/CeasarAlgorithm.java b/src/module9/CeasarAlgorithm.java new file mode 100644 index 0000000..029ebb9 --- /dev/null +++ b/src/module9/CeasarAlgorithm.java @@ -0,0 +1,108 @@ +package module9; + +public class CeasarAlgorithm { + + // Шифровать + public static String Encrypt(String text) { + if (text.isEmpty()) + throw new RuntimeException("Text is empty"); + + String res = ""; + for (int i = 0; i < text.length(); i++) { + res += EncryptChar(text.charAt(i)); + } + return res; + } + + // Расшифровать + public static String Decrypt(String text) { + if (text.isEmpty()) + throw new RuntimeException("Text is empty"); + + String res = ""; + for (int i = 0; i < text.length(); i++) + res += DecryptChar(text.charAt(i)); + + return res; + } + + // Шифровать мимвол + private static char EncryptChar(char c) { + return c == Character.MAX_VALUE ? '\0' : (char) (c + 1); + } + + // Расшифровать символ + private static char DecryptChar(char c) { + return c == '\0' ? Character.MAX_VALUE : (char) (c - 1); + } + + +/* + List alphabet = new ArrayList(); + private final static char[] PUNCTUATION = {'.', ',', ';', ':', '!', '?', '-'}; + CeasarAlgorithm() { + for (char c = 'a'; c <= 'z'; c++) { + alphabet.add(c); + } + for (char c = '0'; c <= '9'; c++) { + alphabet.add(c); + } + for (char c : PUNCTUATION) { + alphabet.add(c); + } + } + + String encrypt(String text, int m, int k) { + int n = alphabet.size(); + m = m % n; + k = k % n; + if (gcd(n, m) != 1) {//проверка простоты n относительно m + return null; + } + StringBuilder cryptogram = new StringBuilder(); + //блок шифрования данных + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + int index = alphabet.indexOf(c); + index = (index * m + k) % n; + cryptogram.append(alphabet.get(index)); + } + return cryptogram.toString(); + } + public String decrypt(String text, int m, int k){ + int n = alphabet.size(); + m = m % n; + k = k % n; + int reversedM = -1;//обратное к m + //ищем обратное к m + for (int i = 0; i < n; i++) { + if ((i * m) % n == 1) { + reversedM = i; + break; + } + } + StringBuilder newText = new StringBuilder(); + //блок дешифрования данных + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + int index = alphabet.indexOf(c); + index = (((index - k) * reversedM) % n + n) % n; + newText.append(alphabet.get(index)); + } + return newText.toString(); + + } + //алгоритм поиска наибольшего общего делителя + private static int gcd(int a, int b) { + while (a > 0 && b > 0) { + if (a > b) { + a %= b; + } else { + b %= a; + } + } + return a + b; + }*/ + } + + diff --git a/src/module9/File.java b/src/module9/File.java new file mode 100644 index 0000000..622e49f --- /dev/null +++ b/src/module9/File.java @@ -0,0 +1,8 @@ +package module9; + +abstract public class File { +protected String type; +} + + + From 946613bf45cc46b8f94219e9d0472b706e4a57ad Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Mon, 28 Mar 2016 20:09:58 +0300 Subject: [PATCH 07/32] Finally I'v made module8. --- src/module8/MusicInstrumentTestDrive.java | 52 ++++++++++++----------- src/module8/MusicInstruments.java | 4 ++ src/module8/MusicStore.java | 31 ++++++-------- src/module8/Piano.java | 32 +++++++++++++- 4 files changed, 74 insertions(+), 45 deletions(-) diff --git a/src/module8/MusicInstrumentTestDrive.java b/src/module8/MusicInstrumentTestDrive.java index 25a1302..67a97a3 100644 --- a/src/module8/MusicInstrumentTestDrive.java +++ b/src/module8/MusicInstrumentTestDrive.java @@ -1,18 +1,33 @@ package module8; +/* +Выбрать иерархию классов из ДЗ по теме OOP in Java и создать несколько коллекций объектов из данной иерархии. +Хотя бы одна коллекция должна содержать в себе объекты разных классов. +Создать класс, который печатает созданные коллекции на экран в виде таблицы. + +Колонки таблицы соответствуют полям объектов. Каждая строка в таблице соответствует объекту из коллекции. + +Создать упорядоченный список объектов из ДЗ по теме OOP in Java не прибегая к использованию Collections.sort(). +*/ import java.util.ArrayList; -import java.util.List; +import java.util.Comparator; import java.util.TreeSet; import java.util.Iterator; public class MusicInstrumentTestDrive { public static void main(String[] args) { - /* ArrayList guitarList = new ArrayList<>(); + ArrayList guitarList = new ArrayList<>(); ArrayList pianoList = new ArrayList<>(); ArrayList trumpetList = new ArrayList<>(); - ArrayList musicInstruments = new ArrayList<>(); + MusicStore musicStore = new MusicStore(); - musicInstruments.add(List ); + System.out.println("Sort piano's list:"); + makeSort(); + System.out.println(); + + musicStore.putMusicInstrument(new Guitar("Best guitar", 656)); + musicStore.putMusicInstrument(new Piano("Best piano", 56)); + musicStore.putMusicInstrument(new Trumpet("Best trumpet", 56)); pianoList.add(new Piano("My piano", 25)); pianoList.add(new Piano("Your piano", 66)); @@ -29,31 +44,20 @@ public static void main(String[] args) { System.out.println("List of Collections"); System.out.println("Type of instruments " + "Price of instruments"); - guitarList.stream().forEach(instrument -> System.out.println(instrument + " ")); pianoList.stream().forEach(instrument -> System.out.println(instrument + " ")); trumpetList.stream().forEach(instrument -> System.out.println(instrument + " ")); -/* - TreeSet ts = new TreeSet(); + musicStore.printMusicInstrumentDetails(); - ts.add("b"); - ts.add("a"); - ts.add("d"); - ts.add("c"); - - // get element in Iterator - Iterator it = ts.iterator(); - - // get descending order of elements - //Iterator it=ts.descendingIterator(); - - while (it.hasNext()) { - String value = (String) it.next(); - - System.out.println("Value :" + value); - } } - */ + public static void makeSort() { + TreeSet piano = new TreeSet(); + piano.add(new Piano("Jack's piano", 56)); + piano.add(new Piano("Nick's piano", 856)); + piano.add(new Piano("Alice's piano", 526)); + piano.add(new Piano("Bill's piano", 456)); + for (Piano pianos : piano) System.out.println(pianos.getTypeOfInstruments()); } } + diff --git a/src/module8/MusicInstruments.java b/src/module8/MusicInstruments.java index e319f42..e333cdc 100644 --- a/src/module8/MusicInstruments.java +++ b/src/module8/MusicInstruments.java @@ -3,4 +3,8 @@ abstract public class MusicInstruments { protected String typeOfInstruments; protected int priceOfInstruments; + + public MusicInstruments() { + this.typeOfInstruments = this.getClass().getSimpleName(); + } } diff --git a/src/module8/MusicStore.java b/src/module8/MusicStore.java index e5c1563..9504b30 100644 --- a/src/module8/MusicStore.java +++ b/src/module8/MusicStore.java @@ -1,33 +1,26 @@ package module8; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; public class MusicStore { - private List guitars; - private List pianos; - private List trumpets; - public List getTrumpets() { - return trumpets; - } - - public void setTrumpets(List trumpets) { - this.trumpets = trumpets; - } + private List musicInstruments; - public List getGuitars() { - return guitars; + public MusicStore() { + musicInstruments = new ArrayList(); } - public void setGuitars(List guitars) { - this.guitars = guitars; + public void putMusicInstrument(MusicInstruments musicInstrument) { + musicInstruments.add(musicInstrument); } - public List getPianos() { - return pianos; + public List listMusicInstruments() { + return Collections.unmodifiableList(musicInstruments); } - public void setPianos(List pianos) { - this.pianos = pianos; + public void printMusicInstrumentDetails() { + for (MusicInstruments musicInstrument : musicInstruments) System.out.println(musicInstrument); } -} \ No newline at end of file +} diff --git a/src/module8/Piano.java b/src/module8/Piano.java index 3dbe1ca..420037d 100644 --- a/src/module8/Piano.java +++ b/src/module8/Piano.java @@ -1,6 +1,8 @@ package module8; -public class Piano extends MusicInstruments { +import java.util.Comparator; + +public class Piano extends MusicInstruments implements Comparable{ private String typeOfInstruments; private int priceOfInstruments; @@ -21,4 +23,30 @@ public String getTypeOfInstruments() { public String toString() { return typeOfInstruments + " " + priceOfInstruments; } -} \ No newline at end of file + public int compareTo(Piano p){ + + return typeOfInstruments.compareTo(p.getTypeOfInstruments()); + } + + + /*class PianoTypeOfInstruments implements Comparator { + public int compare(Piano a, Piano b) { + + return a.getTypeOfInstruments().compareTo(b.getTypeOfInstruments()); + } + } + + class PianoPriceOfInstruments implements Comparator { + + public int compare(Piano a, Piano b) { + + if (a.getPriceOfInstruments() > b.getPriceOfInstruments()) + return 1; + else if (a.getPriceOfInstruments() < b.getPriceOfInstruments()) + return -1; + else + return 0; + }*/ + } + + From f3767f69090f669eb9e3bbeab526ea98739673cd Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Wed, 30 Mar 2016 18:17:11 +0300 Subject: [PATCH 08/32] Finally I'v made module6. --- .../MusicInstrumentTestDrive.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java index ec27767..a036dbe 100644 --- a/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java +++ b/src/module6/ex2_musicinstruments_exception/MusicInstrumentTestDrive.java @@ -20,11 +20,13 @@ public static void main(String[] args) { order.put("trumpet", 1); List guitarsToRemove = prepareOrder(musicStore, order); - System.out.println("removed guitars" + guitarsToRemove.size()); //выводит общее кол-во инструментов, всеравно что написать "removed pianos" + pianosToRemove.size() + System.out.println("removed guitars " + guitarsToRemove.size()); List pianosToRemove = prepareOrder(musicStore, order); + System.out.println("removed pianos " + pianosToRemove.size()); List trumpetsToRemove = prepareOrder(musicStore, order); + System.out.println("removed trumpets " + trumpetsToRemove.size()); - System.out.println(musicStore + " after removed.");//здесь выводит кол-во позиции, которые нужно удалить, умноженные на три + System.out.println(musicStore + " after removed."); } private static List prepareOrder(MusicStore musicStore, Map order) { From a8d4b13af9e4ba0684eef342a1ea15ee59380fbd Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Wed, 30 Mar 2016 22:00:12 +0300 Subject: [PATCH 09/32] Big Home work --- src/module10/Text | 0 src/module10/WorkWithText.java | 3 - .../MusicInstrumentByPriceComparator.java | 16 +++ src/module8/MusicInstrumentTestDrive.java | 25 ++-- src/module8/MusicInstruments.java | 8 ++ src/module8/Piano.java | 27 +---- src/module9/CaesarAlgorithmTestDrive.java | 21 ---- src/module9/CeasarAlgorithm.java | 108 ------------------ src/module9/CezarCryptoMethods.java | 31 +++++ src/module9/CezarTestDrive.java | 19 +++ src/module9/DecryptionCezar.java | 56 +++++++++ src/module9/Directory.java | 34 ++++++ src/module9/EncryptCezar.java | 37 ++++++ src/module9/File.java | 11 +- src/module9/TextFile.java | 22 ++++ src/test/AudioFile.java | 20 ++++ src/test/CezarCryptoMethods.java | 31 +++++ src/test/DecryptionCezar.java | 57 +++++++++ src/test/EncryptCezar.java | 38 ++++++ src/test/File.java | 8 ++ src/test/Main.java | 22 ++++ 21 files changed, 424 insertions(+), 170 deletions(-) create mode 100644 src/module10/Text create mode 100644 src/module8/MusicInstrumentByPriceComparator.java delete mode 100644 src/module9/CaesarAlgorithmTestDrive.java delete mode 100644 src/module9/CeasarAlgorithm.java create mode 100644 src/module9/CezarCryptoMethods.java create mode 100644 src/module9/CezarTestDrive.java create mode 100644 src/module9/DecryptionCezar.java create mode 100644 src/module9/Directory.java create mode 100644 src/module9/EncryptCezar.java create mode 100644 src/module9/TextFile.java create mode 100644 src/test/AudioFile.java create mode 100644 src/test/CezarCryptoMethods.java create mode 100644 src/test/DecryptionCezar.java create mode 100644 src/test/EncryptCezar.java create mode 100644 src/test/File.java create mode 100644 src/test/Main.java diff --git a/src/module10/Text b/src/module10/Text new file mode 100644 index 0000000..e69de29 diff --git a/src/module10/WorkWithText.java b/src/module10/WorkWithText.java index 52a4697..b0d6af4 100644 --- a/src/module10/WorkWithText.java +++ b/src/module10/WorkWithText.java @@ -1,9 +1,6 @@ package module10; - import java.io.*; -import java.util.Scanner; - /* Реализовать сохранение/загрузку текстового сообщения в файл с предварительным шифрованием/расшифрованием. Предусмотреть обработку различных ошибок ввода/вывода diff --git a/src/module8/MusicInstrumentByPriceComparator.java b/src/module8/MusicInstrumentByPriceComparator.java new file mode 100644 index 0000000..3228b12 --- /dev/null +++ b/src/module8/MusicInstrumentByPriceComparator.java @@ -0,0 +1,16 @@ +package module8; + +import java.util.Comparator; + +class MusicInstrumentByPriceComparator implements Comparator { + + public int compare(MusicInstruments a, MusicInstruments b) { + if (a.getPriceOfInstruments() > b.getPriceOfInstruments()) + return 1; + else if (a.getPriceOfInstruments() < b.getPriceOfInstruments()) + return -1; + else + return 0; + } +} + diff --git a/src/module8/MusicInstrumentTestDrive.java b/src/module8/MusicInstrumentTestDrive.java index 67a97a3..9278c70 100644 --- a/src/module8/MusicInstrumentTestDrive.java +++ b/src/module8/MusicInstrumentTestDrive.java @@ -9,10 +9,7 @@ Создать упорядоченный список объектов из ДЗ по теме OOP in Java не прибегая к использованию Collections.sort(). */ -import java.util.ArrayList; -import java.util.Comparator; -import java.util.TreeSet; -import java.util.Iterator; +import java.util.*; public class MusicInstrumentTestDrive { public static void main(String[] args) { @@ -21,10 +18,10 @@ public static void main(String[] args) { ArrayList trumpetList = new ArrayList<>(); MusicStore musicStore = new MusicStore(); - System.out.println("Sort piano's list:"); + System.out.println("Sort Music Instruments list:"); makeSort(); - System.out.println(); + System.out.println(); musicStore.putMusicInstrument(new Guitar("Best guitar", 656)); musicStore.putMusicInstrument(new Piano("Best piano", 56)); musicStore.putMusicInstrument(new Trumpet("Best trumpet", 56)); @@ -48,16 +45,16 @@ public static void main(String[] args) { pianoList.stream().forEach(instrument -> System.out.println(instrument + " ")); trumpetList.stream().forEach(instrument -> System.out.println(instrument + " ")); musicStore.printMusicInstrumentDetails(); - } public static void makeSort() { - TreeSet piano = new TreeSet(); - piano.add(new Piano("Jack's piano", 56)); - piano.add(new Piano("Nick's piano", 856)); - piano.add(new Piano("Alice's piano", 526)); - piano.add(new Piano("Bill's piano", 456)); - for (Piano pianos : piano) System.out.println(pianos.getTypeOfInstruments()); + Comparator musicInstrumentsComparator = new MusicInstrumentByPriceComparator().thenComparing(new MusicInstrumentByPriceComparator()); + + TreeSet musicInstrumentses = new TreeSet(musicInstrumentsComparator); + musicInstrumentses.add(new Piano("Jack's piano ", 56)); + musicInstrumentses.add(new Guitar("Nick's guitar ", 22)); + musicInstrumentses.add(new Trumpet("Alice's trumpet", 23)); + + musicInstrumentses.stream().forEach(instrument -> System.out.println(instrument + " ")); } } - diff --git a/src/module8/MusicInstruments.java b/src/module8/MusicInstruments.java index e333cdc..110db8a 100644 --- a/src/module8/MusicInstruments.java +++ b/src/module8/MusicInstruments.java @@ -4,6 +4,14 @@ abstract public class MusicInstruments { protected String typeOfInstruments; protected int priceOfInstruments; + public int getPriceOfInstruments() { + return priceOfInstruments; + } + + public String getTypeOfInstruments() { + return typeOfInstruments; + } + public MusicInstruments() { this.typeOfInstruments = this.getClass().getSimpleName(); } diff --git a/src/module8/Piano.java b/src/module8/Piano.java index 420037d..fdf1c10 100644 --- a/src/module8/Piano.java +++ b/src/module8/Piano.java @@ -2,7 +2,7 @@ import java.util.Comparator; -public class Piano extends MusicInstruments implements Comparable{ +public class Piano extends MusicInstruments implements Comparable { private String typeOfInstruments; private int priceOfInstruments; @@ -23,30 +23,11 @@ public String getTypeOfInstruments() { public String toString() { return typeOfInstruments + " " + priceOfInstruments; } - public int compareTo(Piano p){ - - return typeOfInstruments.compareTo(p.getTypeOfInstruments()); - } + public int compareTo(Piano p) { - /*class PianoTypeOfInstruments implements Comparator { - public int compare(Piano a, Piano b) { - - return a.getTypeOfInstruments().compareTo(b.getTypeOfInstruments()); - } - } - - class PianoPriceOfInstruments implements Comparator { - - public int compare(Piano a, Piano b) { - - if (a.getPriceOfInstruments() > b.getPriceOfInstruments()) - return 1; - else if (a.getPriceOfInstruments() < b.getPriceOfInstruments()) - return -1; - else - return 0; - }*/ + return typeOfInstruments.compareTo(p.getTypeOfInstruments()); } +} diff --git a/src/module9/CaesarAlgorithmTestDrive.java b/src/module9/CaesarAlgorithmTestDrive.java deleted file mode 100644 index e563765..0000000 --- a/src/module9/CaesarAlgorithmTestDrive.java +++ /dev/null @@ -1,21 +0,0 @@ -package module9; -/* -Реализовать шифрование текста с помощью алгоритма Цезаря. -Зашифровать и расшифровать текстовое представление коллекци обьектов из ДЗ из Модуля 3: ООП в Java -*/ - -import com.sun.xml.internal.fastinfoset.util.CharArray; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class CaesarAlgorithmTestDrive { - public static void main(String[] args) { -ArrayList audioFiles = new ArrayList<>(); - audioFiles.add(new AudioFile("Album")); - CeasarAlgorithm ceasarAlgorithm = new CeasarAlgorithm(); - - - } -} diff --git a/src/module9/CeasarAlgorithm.java b/src/module9/CeasarAlgorithm.java deleted file mode 100644 index 029ebb9..0000000 --- a/src/module9/CeasarAlgorithm.java +++ /dev/null @@ -1,108 +0,0 @@ -package module9; - -public class CeasarAlgorithm { - - // Шифровать - public static String Encrypt(String text) { - if (text.isEmpty()) - throw new RuntimeException("Text is empty"); - - String res = ""; - for (int i = 0; i < text.length(); i++) { - res += EncryptChar(text.charAt(i)); - } - return res; - } - - // Расшифровать - public static String Decrypt(String text) { - if (text.isEmpty()) - throw new RuntimeException("Text is empty"); - - String res = ""; - for (int i = 0; i < text.length(); i++) - res += DecryptChar(text.charAt(i)); - - return res; - } - - // Шифровать мимвол - private static char EncryptChar(char c) { - return c == Character.MAX_VALUE ? '\0' : (char) (c + 1); - } - - // Расшифровать символ - private static char DecryptChar(char c) { - return c == '\0' ? Character.MAX_VALUE : (char) (c - 1); - } - - -/* - List alphabet = new ArrayList(); - private final static char[] PUNCTUATION = {'.', ',', ';', ':', '!', '?', '-'}; - CeasarAlgorithm() { - for (char c = 'a'; c <= 'z'; c++) { - alphabet.add(c); - } - for (char c = '0'; c <= '9'; c++) { - alphabet.add(c); - } - for (char c : PUNCTUATION) { - alphabet.add(c); - } - } - - String encrypt(String text, int m, int k) { - int n = alphabet.size(); - m = m % n; - k = k % n; - if (gcd(n, m) != 1) {//проверка простоты n относительно m - return null; - } - StringBuilder cryptogram = new StringBuilder(); - //блок шифрования данных - for (int i = 0; i < text.length(); i++) { - char c = text.charAt(i); - int index = alphabet.indexOf(c); - index = (index * m + k) % n; - cryptogram.append(alphabet.get(index)); - } - return cryptogram.toString(); - } - public String decrypt(String text, int m, int k){ - int n = alphabet.size(); - m = m % n; - k = k % n; - int reversedM = -1;//обратное к m - //ищем обратное к m - for (int i = 0; i < n; i++) { - if ((i * m) % n == 1) { - reversedM = i; - break; - } - } - StringBuilder newText = new StringBuilder(); - //блок дешифрования данных - for (int i = 0; i < text.length(); i++) { - char c = text.charAt(i); - int index = alphabet.indexOf(c); - index = (((index - k) * reversedM) % n + n) % n; - newText.append(alphabet.get(index)); - } - return newText.toString(); - - } - //алгоритм поиска наибольшего общего делителя - private static int gcd(int a, int b) { - while (a > 0 && b > 0) { - if (a > b) { - a %= b; - } else { - b %= a; - } - } - return a + b; - }*/ - } - - diff --git a/src/module9/CezarCryptoMethods.java b/src/module9/CezarCryptoMethods.java new file mode 100644 index 0000000..b44e37d --- /dev/null +++ b/src/module9/CezarCryptoMethods.java @@ -0,0 +1,31 @@ +package module9; + +public class CezarCryptoMethods { + + protected static final int n = 27; + protected static char[] upper = + new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', + 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' '}; + + protected static char[] lower = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '}; + + public static int findIndUpper(char c) { + int rez = -1; + + for (int i = 0; i < upper.length; ++i) { + if (c == upper[i]) rez = i; + } + return rez; + } + + public static int findIndLower(char c) { + int rez = -1; + + for (int i = 0; i < lower.length; ++i) { + if (c == lower[i]) rez = i; + } + return rez; + } + +} diff --git a/src/module9/CezarTestDrive.java b/src/module9/CezarTestDrive.java new file mode 100644 index 0000000..794638a --- /dev/null +++ b/src/module9/CezarTestDrive.java @@ -0,0 +1,19 @@ +package module9; + +import java.util.ArrayList; +import java.util.List; + +public class CezarTestDrive { + public static void main(String[] args) { + List fileList = new ArrayList<>(); + fileList.add(new AudioFile("Audio")); + fileList.add(new TextFile("Text")); + + System.out.println(fileList); + + for (int i = 0; i < fileList.size(); i++) { + EncryptCezar enc = new EncryptCezar(fileList.get(i)); + } + + } +} diff --git a/src/module9/DecryptionCezar.java b/src/module9/DecryptionCezar.java new file mode 100644 index 0000000..6ecab1d --- /dev/null +++ b/src/module9/DecryptionCezar.java @@ -0,0 +1,56 @@ +package module9; + +public class DecryptionCezar extends CezarCryptoMethods { + private String output; + + public DecryptionCezar(String text, int k) { + StringBuilder dec = new StringBuilder(); + + for (int i = 0; i < text.length(); ++i) { + char c = text.charAt(i); + + if (findIndLower(c) == -1) { + int x = (findIndUpper(c) - k + n) % n; + dec.append(upper[x]); + } + if (findIndUpper(c) == -1) { + int x = (findIndLower(c) - k + n) % n; + dec.append(lower[x]); + } + if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { + dec.append(c); + } + } + + this.output = dec.toString(); + } + + public DecryptionCezar(EncryptCezar enc) { + int k = enc.getK(); + String input = enc.getEncText(); + StringBuilder dec = new StringBuilder(); + + for (int i = 0; i < input.length(); ++i) { + char c = input.charAt(i); + + if (findIndLower(c) == -1) { + int x = (findIndUpper(c) - k + n) % n; + dec.append(upper[x]); + } + if (findIndUpper(c) == -1) { + int x = (findIndLower(c) - k + n) % n; + dec.append(lower[x]); + } + if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { + dec.append(c); + } + } + + this.output = dec.toString(); + } + + public String getDecText() { + return this.output; + } + +} diff --git a/src/module9/Directory.java b/src/module9/Directory.java new file mode 100644 index 0000000..1eb33fc --- /dev/null +++ b/src/module9/Directory.java @@ -0,0 +1,34 @@ +package module9; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Directory { + + + + public Directory() { + files = new ArrayList(); + } + + public void putFile(File file) { + files.add(file); + } + + public List listFiles() { + return Collections.unmodifiableList(files); + } + + public List getFiles() { + return files; + } + @Override + public String toString() { + return "Directory{" + + "files=" + files + + '}'; + } + + private List files; +} \ No newline at end of file diff --git a/src/module9/EncryptCezar.java b/src/module9/EncryptCezar.java new file mode 100644 index 0000000..ecf7c15 --- /dev/null +++ b/src/module9/EncryptCezar.java @@ -0,0 +1,37 @@ +package module9; + +public class EncryptCezar extends CezarCryptoMethods { + private String output; + private int k; + + public EncryptCezar(String text, int k) { + this.k = k; + StringBuilder output = new StringBuilder(); + + for (int i = 0; i < text.length(); ++i) { + char c = text.charAt(i); + + if (findIndLower(c) == -1) { + int y = (findIndUpper(c) + k) % n; + output.append(upper[y]); + } + if (findIndUpper(c) == -1) { + int y = (findIndLower(c) + k) % n; + output.append(lower[y]); + } + if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { + output.append(c); + } + } + this.output = output.toString(); + } + + public String getEncText() { + return this.output; + } + + public int getK() { + return this.k; + } + +} diff --git a/src/module9/File.java b/src/module9/File.java index 622e49f..43e3283 100644 --- a/src/module9/File.java +++ b/src/module9/File.java @@ -1,8 +1,17 @@ package module9; abstract public class File { -protected String type; + protected String typeOfFile; + + public File() { + this.typeOfFile = this.getClass().getSimpleName(); + } + + public String getTypeOfFile() { + return typeOfFile; + } } + diff --git a/src/module9/TextFile.java b/src/module9/TextFile.java new file mode 100644 index 0000000..ba3f603 --- /dev/null +++ b/src/module9/TextFile.java @@ -0,0 +1,22 @@ +package module9; + +public class TextFile extends File { + + private String typeOfFile; + + public TextFile(String typeOfFile) { + this.typeOfFile = typeOfFile; + } + + public String getTypeOfFile() { + return typeOfFile; + } + + @Override + public String toString() { + return "TextFile{" + + "typeOfFile='" + typeOfFile + '\'' + + '}'; + } + +} \ No newline at end of file diff --git a/src/test/AudioFile.java b/src/test/AudioFile.java new file mode 100644 index 0000000..230b741 --- /dev/null +++ b/src/test/AudioFile.java @@ -0,0 +1,20 @@ +package test; + +public class AudioFile extends File { + + private String typeOfFile; + + public AudioFile(String typeOfFile) { + this.typeOfFile = typeOfFile; + } + + public String getTypeOfFile() { + return typeOfFile; + } + + @Override + public String toString() { + return typeOfFile; + } + +} \ No newline at end of file diff --git a/src/test/CezarCryptoMethods.java b/src/test/CezarCryptoMethods.java new file mode 100644 index 0000000..a54ac83 --- /dev/null +++ b/src/test/CezarCryptoMethods.java @@ -0,0 +1,31 @@ +package test; + +public class CezarCryptoMethods { + + protected static final int n = 26; + protected static char[] upper = + {'A','B','C','D','E','F','G','H','I','J','K','L','M','N', 'O','P','Q', + 'R','S','T','U','V','W','X','Y','Z'}; + + protected static char[] lower= {'a','b','c','d','e','f','g','h', + 'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; + + public static int findIndUpper(char c){ + int rez = -1; + + for(int i=0; i audioFiles = new ArrayList<>(); + audioFiles.add(new AudioFile("Album")); + audioFiles.stream().forEach(file -> System.out.println(file)); + + + EncryptCezar enc = new EncryptCezar(audioFiles.toString(), 1); + System.out.println(enc.getEncText()); + + DecryptionCezar dec = new DecryptionCezar(enc.getEncText(), enc.getK()); + System.out.println(dec.getDecText()); + + audioFiles.stream().findAny(); + } +} From 0e84738ce561783db8ba67a6233003533e5c46aa Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Wed, 30 Mar 2016 22:00:36 +0300 Subject: [PATCH 10/32] Big Home work --- .../ex1_square/CalculateSquareTestDrive.java | 10 ++++++---- src/module4/ex1_square/CircleSquare.java | 11 +++-------- src/module4/ex1_square/RectangleSquare.java | 16 ++-------------- src/module4/ex1_square/TriangleSquare.java | 19 ++++--------------- 4 files changed, 15 insertions(+), 41 deletions(-) diff --git a/src/module4/ex1_square/CalculateSquareTestDrive.java b/src/module4/ex1_square/CalculateSquareTestDrive.java index 0c1f678..53bd803 100644 --- a/src/module4/ex1_square/CalculateSquareTestDrive.java +++ b/src/module4/ex1_square/CalculateSquareTestDrive.java @@ -2,14 +2,16 @@ public class CalculateSquareTestDrive { public static void main(String[] args) { - CircleSquare circleSquare = new CircleSquare(); - TriangleSquare triangleSquare = new TriangleSquare(); - RectangleSquare rectangleSquare = new RectangleSquare(); - circleSquare.setRadius(6); + CircleSquare circleSquare = new CircleSquare(5); + TriangleSquare triangleSquare = new TriangleSquare(5, 5); + RectangleSquare rectangleSquare = new RectangleSquare(9, 8); + + /* circleSquare.setRadius(6); triangleSquare.setHeightOfTriangle(5); triangleSquare.setSideOfTriangle(5); rectangleSquare.setHeightOfRectangle(9); rectangleSquare.setWidthOfRectangle(8); + */ System.out.println("Площадь треугольника = " + circleSquare.countCircleSquare() + ";"); //Triangle Square System.out.println("Площадь прямоугольника = " + triangleSquare.countTriangleSquare() + ";"); //Rectangle Square diff --git a/src/module4/ex1_square/CircleSquare.java b/src/module4/ex1_square/CircleSquare.java index 462a393..9e96bdb 100644 --- a/src/module4/ex1_square/CircleSquare.java +++ b/src/module4/ex1_square/CircleSquare.java @@ -4,16 +4,11 @@ public class CircleSquare { private int radius; //radius of circle - public int getRadius() { - return radius; - } - - public void setRadius(int radius) { + public CircleSquare(int radius) { this.radius = radius; } - public int countCircleSquare() { - int circleSqure = (int) (Math.PI * radius); - return circleSqure; + public int countCircleSquare() { + return (int) (Math.PI * radius); } } diff --git a/src/module4/ex1_square/RectangleSquare.java b/src/module4/ex1_square/RectangleSquare.java index dd65761..27fbd5a 100644 --- a/src/module4/ex1_square/RectangleSquare.java +++ b/src/module4/ex1_square/RectangleSquare.java @@ -4,24 +4,12 @@ public class RectangleSquare { private int heightOfRectangle; private int widthOfRectangle; - public int getHeightOfRectangle() { - return heightOfRectangle; - } - - public void setHeightOfRectangle(int heightOfRectangle) { + public RectangleSquare(int heightOfRectangle, int widthOfRectangle) { this.heightOfRectangle = heightOfRectangle; - } - - public int getWidthOfRectangle() { - return widthOfRectangle; - } - - public void setWidthOfRectangle(int widthOfRectangle) { this.widthOfRectangle = widthOfRectangle; } public int countRectangleSquare() { - int rectangleSqure = heightOfRectangle * widthOfRectangle; - return rectangleSqure; + return heightOfRectangle * widthOfRectangle; } } diff --git a/src/module4/ex1_square/TriangleSquare.java b/src/module4/ex1_square/TriangleSquare.java index 9219a5a..470004b 100644 --- a/src/module4/ex1_square/TriangleSquare.java +++ b/src/module4/ex1_square/TriangleSquare.java @@ -1,27 +1,16 @@ package module4.ex1_square; public class TriangleSquare { + private int sideOfTriangle; private int heightOfTriangle; //the height of a triangle lowered on the side "sideOfTriangle" - public int getHeightOfTriangle() { - return heightOfTriangle; - } - - public void setHeightOfTriangle(int heightOfTriangle) { - this.heightOfTriangle = heightOfTriangle; - } - - public int getSideOfTriangle() { - return sideOfTriangle; - } - - public void setSideOfTriangle(int sideOfTriangle) { + public TriangleSquare(int sideOfTriangle, int heightOfTriangle) { this.sideOfTriangle = sideOfTriangle; + this.heightOfTriangle = heightOfTriangle; } public int countTriangleSquare() { - int triangleSqure = (sideOfTriangle * heightOfTriangle) / 2; - return triangleSqure; + return (sideOfTriangle * heightOfTriangle) / 2; } } From 120dee7627d14af8535460c4b1e66e2cf626a3a2 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 2 Apr 2016 13:57:38 +0300 Subject: [PATCH 11/32] Ceaser Cipher --- src/module10/CaesarCipherTestDrive.java | 90 +++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 src/module10/CaesarCipherTestDrive.java diff --git a/src/module10/CaesarCipherTestDrive.java b/src/module10/CaesarCipherTestDrive.java new file mode 100644 index 0000000..a73f9b7 --- /dev/null +++ b/src/module10/CaesarCipherTestDrive.java @@ -0,0 +1,90 @@ +package module10; + +import java.io.*; +import java.util.Scanner; + +public class CaesarCipherTestDrive { + public static void main(String[] args) throws IOException { + Scanner scanner = new Scanner(System.in); + System.out.println("Print text:"); + String text = scanner.nextLine(); + System.out.println("Print key:"); + int key = scanner.nextInt(); + System.out.println(); + System.out.println("Caesar Cipher in work:"); + + try (FileWriter writer = new FileWriter("Text.txt")) { + writer.write(encrypt(text, key)); + writer.flush(); + } catch (IOException ex) { + System.out.println("Encrypt: " + ex.getMessage()); + } + + try (FileReader reader = new FileReader("Text.txt")) { + int c; + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + + System.out.println(); + + try (FileWriter writer = new FileWriter("Text.txt")) { + writer.write(decrypt(encrypt(text, key), key)); + writer.flush(); + } catch (IOException ex) { + System.out.println("Decrypt: " + ex.getMessage()); + } + + try (FileReader reader = new FileReader("Text.txt")) { + int c; + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } + + public static String encrypt(String str, int keyLength) { + String encrypted = ""; + for (int i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c + (keyLength % 26); + if (c > 'Z') + c = c - 26; + } else if (Character.isLowerCase(c)) { + c = c + (keyLength % 26); + + if (c > 'z') + c = c - 26; + } + encrypted = encrypted + (char) c; + } + return encrypted; + } + + public static String decrypt(String str, int keyLength) { + String decrypted = ""; + for (int i = 0; i < str.length(); i++) { + + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c - (keyLength % 26); + + if (c < 'A') + c = c + 26; + } else if (Character.isLowerCase(c)) { + c = c - (keyLength % 26); + + if (c < 'a') + c = c + 26; + } + decrypted = decrypted + (char) c; + } + return decrypted; + } +} \ No newline at end of file From cbf9baeda36f9a91981c4afc1a75dc00c7e9b326 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 2 Apr 2016 14:02:33 +0300 Subject: [PATCH 12/32] Cezar Method --- src/module10/CezarCryptoMethods.java | 31 --------------- src/module10/DecryptionCezar.java | 56 ---------------------------- src/module10/EncryptCezar.java | 37 ------------------ src/module10/Text | 0 src/module10/WorkWithText.java | 50 ------------------------- 5 files changed, 174 deletions(-) delete mode 100644 src/module10/CezarCryptoMethods.java delete mode 100644 src/module10/DecryptionCezar.java delete mode 100644 src/module10/EncryptCezar.java delete mode 100644 src/module10/Text delete mode 100644 src/module10/WorkWithText.java diff --git a/src/module10/CezarCryptoMethods.java b/src/module10/CezarCryptoMethods.java deleted file mode 100644 index 5011dba..0000000 --- a/src/module10/CezarCryptoMethods.java +++ /dev/null @@ -1,31 +0,0 @@ -package module10; - -public class CezarCryptoMethods { - - protected static final int n = 27; - protected static char[] upper = - new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', - 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' '}; - - protected static char[] lower = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '}; - - public static int findIndUpper(char c) { - int rez = -1; - - for (int i = 0; i < upper.length; ++i) { - if (c == upper[i]) rez = i; - } - return rez; - } - - public static int findIndLower(char c) { - int rez = -1; - - for (int i = 0; i < lower.length; ++i) { - if (c == lower[i]) rez = i; - } - return rez; - } - -} diff --git a/src/module10/DecryptionCezar.java b/src/module10/DecryptionCezar.java deleted file mode 100644 index 8e7ce19..0000000 --- a/src/module10/DecryptionCezar.java +++ /dev/null @@ -1,56 +0,0 @@ -package module10; - -public class DecryptionCezar extends CezarCryptoMethods { - private String output; - - public DecryptionCezar(String text, int k) { - StringBuilder dec = new StringBuilder(); - - for (int i = 0; i < text.length(); ++i) { - char c = text.charAt(i); - - if (findIndLower(c) == -1) { - int x = (findIndUpper(c) - k + n) % n; - dec.append(upper[x]); - } - if (findIndUpper(c) == -1) { - int x = (findIndLower(c) - k + n) % n; - dec.append(lower[x]); - } - if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { - dec.append(c); - } - } - - this.output = dec.toString(); - } - - public DecryptionCezar(EncryptCezar enc) { - int k = enc.getK(); - String input = enc.getEncText(); - StringBuilder dec = new StringBuilder(); - - for (int i = 0; i < input.length(); ++i) { - char c = input.charAt(i); - - if (findIndLower(c) == -1) { - int x = (findIndUpper(c) - k + n) % n; - dec.append(upper[x]); - } - if (findIndUpper(c) == -1) { - int x = (findIndLower(c) - k + n) % n; - dec.append(lower[x]); - } - if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { - dec.append(c); - } - } - - this.output = dec.toString(); - } - - public String getDecText() { - return this.output; - } - -} diff --git a/src/module10/EncryptCezar.java b/src/module10/EncryptCezar.java deleted file mode 100644 index 2a0bdb9..0000000 --- a/src/module10/EncryptCezar.java +++ /dev/null @@ -1,37 +0,0 @@ -package module10; - -public class EncryptCezar extends CezarCryptoMethods { - private String output; - private int k; - - public EncryptCezar(String text, int k) { - this.k = k; - StringBuilder output = new StringBuilder(); - - for (int i = 0; i < text.length(); ++i) { - char c = text.charAt(i); - - if (findIndLower(c) == -1) { - int y = (findIndUpper(c) + k) % n; - output.append(upper[y]); - } - if (findIndUpper(c) == -1) { - int y = (findIndLower(c) + k) % n; - output.append(lower[y]); - } - if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { - output.append(c); - } - } - this.output = output.toString(); - } - - public String getEncText() { - return this.output; - } - - public int getK() { - return this.k; - } - -} diff --git a/src/module10/Text b/src/module10/Text deleted file mode 100644 index e69de29..0000000 diff --git a/src/module10/WorkWithText.java b/src/module10/WorkWithText.java deleted file mode 100644 index b0d6af4..0000000 --- a/src/module10/WorkWithText.java +++ /dev/null @@ -1,50 +0,0 @@ -package module10; - -import java.io.*; -/* -Реализовать сохранение/загрузку текстового сообщения в файл с предварительным -шифрованием/расшифрованием. Предусмотреть обработку различных ошибок ввода/вывода -*/ -public class WorkWithText { - public static void main(String[] args) throws IOException { - - String text = "Java"; - - EncryptCezar enc = new EncryptCezar(text, 2); - DecryptionCezar dec = new DecryptionCezar(enc.getEncText(), enc.getK()); - - try (FileWriter writer = new FileWriter("Text.txt")) { - writer.write(enc.getEncText()); - writer.flush(); - } catch (IOException ex) { - System.out.println(ex.getMessage()); - } - - try (FileReader reader = new FileReader("Text.txt")) { - int c; - while ((c = reader.read()) != -1) { - System.out.print((char) c); - } - } catch (IOException ex) { - System.out.println(ex.getMessage()); - } - - System.out.println(); - - try (FileWriter writer = new FileWriter("Text.txt")) { - writer.write(dec.getDecText()); - writer.flush(); - } catch (IOException ex) { - System.out.println(ex.getMessage()); - } - - try (FileReader reader = new FileReader("Text.txt")) { - int c; - while ((c = reader.read()) != -1) { - System.out.print((char) c); - } - } catch (IOException ex) { - System.out.println(ex.getMessage()); - } - } -} From e7aae7f78888319d4184df4f6b771ee070adb9db Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 2 Apr 2016 15:02:07 +0300 Subject: [PATCH 13/32] Done module 9 --- Text.txt | 2 +- src/module9/AudioFile.java | 4 +-- src/module9/CezarCryptoMethods.java | 31 ---------------- src/module9/CezarTestDrive.java | 52 +++++++++++++++++++++++---- src/module9/DecryptionCezar.java | 56 ----------------------------- src/module9/Directory.java | 1 + src/module9/EncryptCezar.java | 37 ------------------- src/module9/TextFile.java | 4 +-- 8 files changed, 50 insertions(+), 137 deletions(-) delete mode 100644 src/module9/CezarCryptoMethods.java delete mode 100644 src/module9/DecryptionCezar.java delete mode 100644 src/module9/EncryptCezar.java diff --git a/Text.txt b/Text.txt index a80fd1e..f584548 100644 --- a/Text.txt +++ b/Text.txt @@ -1 +1 @@ -Java \ No newline at end of file +Hello World!!! \ No newline at end of file diff --git a/src/module9/AudioFile.java b/src/module9/AudioFile.java index eaf083f..246f70a 100644 --- a/src/module9/AudioFile.java +++ b/src/module9/AudioFile.java @@ -14,9 +14,7 @@ public String getTypeOfFile() { @Override public String toString() { - return "AudioFile{" + - "typeOfFile='" + typeOfFile + '\'' + - '}'; + return typeOfFile; } } \ No newline at end of file diff --git a/src/module9/CezarCryptoMethods.java b/src/module9/CezarCryptoMethods.java deleted file mode 100644 index b44e37d..0000000 --- a/src/module9/CezarCryptoMethods.java +++ /dev/null @@ -1,31 +0,0 @@ -package module9; - -public class CezarCryptoMethods { - - protected static final int n = 27; - protected static char[] upper = - new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', - 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' '}; - - protected static char[] lower = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '}; - - public static int findIndUpper(char c) { - int rez = -1; - - for (int i = 0; i < upper.length; ++i) { - if (c == upper[i]) rez = i; - } - return rez; - } - - public static int findIndLower(char c) { - int rez = -1; - - for (int i = 0; i < lower.length; ++i) { - if (c == lower[i]) rez = i; - } - return rez; - } - -} diff --git a/src/module9/CezarTestDrive.java b/src/module9/CezarTestDrive.java index 794638a..af59560 100644 --- a/src/module9/CezarTestDrive.java +++ b/src/module9/CezarTestDrive.java @@ -5,15 +5,55 @@ public class CezarTestDrive { public static void main(String[] args) { - List fileList = new ArrayList<>(); - fileList.add(new AudioFile("Audio")); - fileList.add(new TextFile("Text")); + List files = new ArrayList<>(); + files.add(new AudioFile("Audio file")); + files.add(new TextFile("Text file")); - System.out.println(fileList); + System.out.println("File\'s List: " + files + "\n"); + System.out.println("Encrypt File's List: "); + System.out.println(encrypt((files.toString()), 2) + "\n"); + System.out.println("Decrypt File's List: "); + System.out.println(decrypt((encrypt((files.toString()), 2)), 2)); + } + + public static String encrypt(String str, int keyLength) { + String encrypted = ""; + for (int i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c + (keyLength % 26); + if (c > 'Z') + c = c - 26; + } else if (Character.isLowerCase(c)) { + c = c + (keyLength % 26); - for (int i = 0; i < fileList.size(); i++) { - EncryptCezar enc = new EncryptCezar(fileList.get(i)); + if (c > 'z') + c = c - 26; + } + encrypted = encrypted + (char) c; } + return encrypted; + } + + public static String decrypt(String str, int keyLength) { + String decrypted = ""; + for (int i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c - (keyLength % 26); + + if (c < 'A') + c = c + 26; + } else if (Character.isLowerCase(c)) { + c = c - (keyLength % 26); + + if (c < 'a') + c = c + 26; + } + decrypted = decrypted + (char) c; + } + return decrypted; } } + diff --git a/src/module9/DecryptionCezar.java b/src/module9/DecryptionCezar.java deleted file mode 100644 index 6ecab1d..0000000 --- a/src/module9/DecryptionCezar.java +++ /dev/null @@ -1,56 +0,0 @@ -package module9; - -public class DecryptionCezar extends CezarCryptoMethods { - private String output; - - public DecryptionCezar(String text, int k) { - StringBuilder dec = new StringBuilder(); - - for (int i = 0; i < text.length(); ++i) { - char c = text.charAt(i); - - if (findIndLower(c) == -1) { - int x = (findIndUpper(c) - k + n) % n; - dec.append(upper[x]); - } - if (findIndUpper(c) == -1) { - int x = (findIndLower(c) - k + n) % n; - dec.append(lower[x]); - } - if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { - dec.append(c); - } - } - - this.output = dec.toString(); - } - - public DecryptionCezar(EncryptCezar enc) { - int k = enc.getK(); - String input = enc.getEncText(); - StringBuilder dec = new StringBuilder(); - - for (int i = 0; i < input.length(); ++i) { - char c = input.charAt(i); - - if (findIndLower(c) == -1) { - int x = (findIndUpper(c) - k + n) % n; - dec.append(upper[x]); - } - if (findIndUpper(c) == -1) { - int x = (findIndLower(c) - k + n) % n; - dec.append(lower[x]); - } - if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { - dec.append(c); - } - } - - this.output = dec.toString(); - } - - public String getDecText() { - return this.output; - } - -} diff --git a/src/module9/Directory.java b/src/module9/Directory.java index 1eb33fc..f2f735b 100644 --- a/src/module9/Directory.java +++ b/src/module9/Directory.java @@ -23,6 +23,7 @@ public List listFiles() { public List getFiles() { return files; } + @Override public String toString() { return "Directory{" + diff --git a/src/module9/EncryptCezar.java b/src/module9/EncryptCezar.java deleted file mode 100644 index ecf7c15..0000000 --- a/src/module9/EncryptCezar.java +++ /dev/null @@ -1,37 +0,0 @@ -package module9; - -public class EncryptCezar extends CezarCryptoMethods { - private String output; - private int k; - - public EncryptCezar(String text, int k) { - this.k = k; - StringBuilder output = new StringBuilder(); - - for (int i = 0; i < text.length(); ++i) { - char c = text.charAt(i); - - if (findIndLower(c) == -1) { - int y = (findIndUpper(c) + k) % n; - output.append(upper[y]); - } - if (findIndUpper(c) == -1) { - int y = (findIndLower(c) + k) % n; - output.append(lower[y]); - } - if ((findIndUpper(c) == -1) && (findIndLower(c) == -1)) { - output.append(c); - } - } - this.output = output.toString(); - } - - public String getEncText() { - return this.output; - } - - public int getK() { - return this.k; - } - -} diff --git a/src/module9/TextFile.java b/src/module9/TextFile.java index ba3f603..ae97a3d 100644 --- a/src/module9/TextFile.java +++ b/src/module9/TextFile.java @@ -14,9 +14,7 @@ public String getTypeOfFile() { @Override public String toString() { - return "TextFile{" + - "typeOfFile='" + typeOfFile + '\'' + - '}'; + return typeOfFile; } } \ No newline at end of file From 4bb083daedc252c73662f4e0bfe1589afc00a4b3 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Tue, 5 Apr 2016 13:27:26 +0300 Subject: [PATCH 14/32] Ref. Module 10. --- src/module10/CaesarCipherTestDrive.java | 79 +++---------------------- src/module10/CeasarCipher.java | 45 ++++++++++++++ src/module10/FileUtil.java | 28 +++++++++ 3 files changed, 80 insertions(+), 72 deletions(-) create mode 100644 src/module10/CeasarCipher.java create mode 100644 src/module10/FileUtil.java diff --git a/src/module10/CaesarCipherTestDrive.java b/src/module10/CaesarCipherTestDrive.java index a73f9b7..ea4710b 100644 --- a/src/module10/CaesarCipherTestDrive.java +++ b/src/module10/CaesarCipherTestDrive.java @@ -5,6 +5,8 @@ public class CaesarCipherTestDrive { public static void main(String[] args) throws IOException { + + CeasarCipher ceasarCipher = new CeasarCipher(); Scanner scanner = new Scanner(System.in); System.out.println("Print text:"); String text = scanner.nextLine(); @@ -13,78 +15,11 @@ public static void main(String[] args) throws IOException { System.out.println(); System.out.println("Caesar Cipher in work:"); - try (FileWriter writer = new FileWriter("Text.txt")) { - writer.write(encrypt(text, key)); - writer.flush(); - } catch (IOException ex) { - System.out.println("Encrypt: " + ex.getMessage()); - } - - try (FileReader reader = new FileReader("Text.txt")) { - int c; - while ((c = reader.read()) != -1) { - System.out.print((char) c); - } - } catch (IOException ex) { - System.out.println(ex.getMessage()); - } - + FileUtil fileUtil = new FileUtil(); + fileUtil.write("Text.txt", ceasarCipher.encrypt(text, key)); + fileUtil.read("Text.txt"); System.out.println(); - - try (FileWriter writer = new FileWriter("Text.txt")) { - writer.write(decrypt(encrypt(text, key), key)); - writer.flush(); - } catch (IOException ex) { - System.out.println("Decrypt: " + ex.getMessage()); - } - - try (FileReader reader = new FileReader("Text.txt")) { - int c; - while ((c = reader.read()) != -1) { - System.out.print((char) c); - } - } catch (IOException ex) { - System.out.println(ex.getMessage()); - } - } - - public static String encrypt(String str, int keyLength) { - String encrypted = ""; - for (int i = 0; i < str.length(); i++) { - int c = str.charAt(i); - if (Character.isUpperCase(c)) { - c = c + (keyLength % 26); - if (c > 'Z') - c = c - 26; - } else if (Character.isLowerCase(c)) { - c = c + (keyLength % 26); - - if (c > 'z') - c = c - 26; - } - encrypted = encrypted + (char) c; - } - return encrypted; - } - - public static String decrypt(String str, int keyLength) { - String decrypted = ""; - for (int i = 0; i < str.length(); i++) { - - int c = str.charAt(i); - if (Character.isUpperCase(c)) { - c = c - (keyLength % 26); - - if (c < 'A') - c = c + 26; - } else if (Character.isLowerCase(c)) { - c = c - (keyLength % 26); - - if (c < 'a') - c = c + 26; - } - decrypted = decrypted + (char) c; - } - return decrypted; + fileUtil.write("Text.txt", ceasarCipher.decrypt(ceasarCipher.encrypt(text, key), key)); + fileUtil.read("Text.txt"); } } \ No newline at end of file diff --git a/src/module10/CeasarCipher.java b/src/module10/CeasarCipher.java new file mode 100644 index 0000000..13129d7 --- /dev/null +++ b/src/module10/CeasarCipher.java @@ -0,0 +1,45 @@ +package module10; + + +public class CeasarCipher { + + public static String encrypt(String str, int keyLength) { + String encrypted = ""; + for (int i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c + (keyLength % 26); + if (c > 'Z') + c = c - 26; + } else if (Character.isLowerCase(c)) { + c = c + (keyLength % 26); + + if (c > 'z') + c = c - 26; + } + encrypted = encrypted + (char) c; + } + return encrypted; + } + + public static String decrypt(String str, int keyLength) { + String decrypted = ""; + for (int i = 0; i < str.length(); i++) { + + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c - (keyLength % 26); + + if (c < 'A') + c = c + 26; + } else if (Character.isLowerCase(c)) { + c = c - (keyLength % 26); + + if (c < 'a') + c = c + 26; + } + decrypted = decrypted + (char) c; + } + return decrypted; + } +} diff --git a/src/module10/FileUtil.java b/src/module10/FileUtil.java new file mode 100644 index 0000000..f96038a --- /dev/null +++ b/src/module10/FileUtil.java @@ -0,0 +1,28 @@ +package module10; + +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +public class FileUtil { + + public void read(String fileName) { + try (FileReader reader = new FileReader(fileName)) { + int c; + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } + + public void write(String filename, String textToWrite) { + try (FileWriter writer = new FileWriter(filename)) { + writer.write(textToWrite); + writer.flush(); + } catch (IOException ex) { + System.out.println("Decrypt: " + ex.getMessage()); + } + } +} From 7a99e9126233996d86ce5fe5cf50bce7c1be956d Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Wed, 6 Apr 2016 19:59:02 +0300 Subject: [PATCH 15/32] JUnit test --- Text.txt | 2 +- gojavaonline.iml | 10 ++++ src/test/CezarCryptoMethods.java | 31 ---------- src/test/DecryptionCezar.java | 57 ------------------ src/test/EncryptCezar.java | 38 ------------ src/test/File.java | 8 --- src/test/Main.java | 22 ------- src/test/module10/CaesarCipherTestDrive.java | 25 ++++++++ src/test/module10/CeasarCipher.java | 45 ++++++++++++++ src/test/module10/CeaserCipherTest.java | 33 +++++++++++ src/test/module10/FileUtil.java | 28 +++++++++ .../ex1_square/CalculateSquareTest.java | 40 +++++++++++++ .../ex1_square/CalculateSquareTestDrive.java | 20 +++++++ src/test/module4/ex1_square/CircleSquare.java | 14 +++++ .../module4/ex1_square/RectangleSquare.java | 15 +++++ .../module4/ex1_square/TriangleSquare.java | 16 +++++ .../ex2_temperature/ConvertsTemperature.java | 39 ++++++++++++ .../ConvertsTemperatureTest.java | 30 ++++++++++ .../ConvertsTemperatureTestDrive.java | 12 ++++ .../ex3_distance/CalculateDistance.java | 46 +++++++++++++++ .../ex3_distance/CalculateDistanceTest.java | 23 ++++++++ .../CalculateDistanceTestDrive.java | 13 ++++ src/test/module5/ArrMinMaxSortTest.java | 41 +++++++++++++ src/test/module5/ArrMinMaxSortTestDrive.java | 56 ++++++++++++++++++ src/test/{ => module9}/AudioFile.java | 4 +- src/test/module9/CezarTest.java | 31 ++++++++++ src/test/module9/CezarTestDrive.java | 59 +++++++++++++++++++ src/test/module9/Directory.java | 35 +++++++++++ src/test/module9/File.java | 17 ++++++ src/test/module9/TextFile.java | 20 +++++++ 30 files changed, 671 insertions(+), 159 deletions(-) delete mode 100644 src/test/CezarCryptoMethods.java delete mode 100644 src/test/DecryptionCezar.java delete mode 100644 src/test/EncryptCezar.java delete mode 100644 src/test/File.java delete mode 100644 src/test/Main.java create mode 100644 src/test/module10/CaesarCipherTestDrive.java create mode 100644 src/test/module10/CeasarCipher.java create mode 100644 src/test/module10/CeaserCipherTest.java create mode 100644 src/test/module10/FileUtil.java create mode 100644 src/test/module4/ex1_square/CalculateSquareTest.java create mode 100644 src/test/module4/ex1_square/CalculateSquareTestDrive.java create mode 100644 src/test/module4/ex1_square/CircleSquare.java create mode 100644 src/test/module4/ex1_square/RectangleSquare.java create mode 100644 src/test/module4/ex1_square/TriangleSquare.java create mode 100644 src/test/module4/ex2_temperature/ConvertsTemperature.java create mode 100644 src/test/module4/ex2_temperature/ConvertsTemperatureTest.java create mode 100644 src/test/module4/ex2_temperature/ConvertsTemperatureTestDrive.java create mode 100644 src/test/module4/ex3_distance/CalculateDistance.java create mode 100644 src/test/module4/ex3_distance/CalculateDistanceTest.java create mode 100644 src/test/module4/ex3_distance/CalculateDistanceTestDrive.java create mode 100644 src/test/module5/ArrMinMaxSortTest.java create mode 100644 src/test/module5/ArrMinMaxSortTestDrive.java rename src/test/{ => module9}/AudioFile.java (85%) create mode 100644 src/test/module9/CezarTest.java create mode 100644 src/test/module9/CezarTestDrive.java create mode 100644 src/test/module9/Directory.java create mode 100644 src/test/module9/File.java create mode 100644 src/test/module9/TextFile.java diff --git a/Text.txt b/Text.txt index f584548..50524ca 100644 --- a/Text.txt +++ b/Text.txt @@ -1 +1 @@ -Hello World!!! \ No newline at end of file +Hello Java!!! \ No newline at end of file diff --git a/gojavaonline.iml b/gojavaonline.iml index c90834f..3a8ffcf 100644 --- a/gojavaonline.iml +++ b/gojavaonline.iml @@ -7,5 +7,15 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/test/CezarCryptoMethods.java b/src/test/CezarCryptoMethods.java deleted file mode 100644 index a54ac83..0000000 --- a/src/test/CezarCryptoMethods.java +++ /dev/null @@ -1,31 +0,0 @@ -package test; - -public class CezarCryptoMethods { - - protected static final int n = 26; - protected static char[] upper = - {'A','B','C','D','E','F','G','H','I','J','K','L','M','N', 'O','P','Q', - 'R','S','T','U','V','W','X','Y','Z'}; - - protected static char[] lower= {'a','b','c','d','e','f','g','h', - 'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; - - public static int findIndUpper(char c){ - int rez = -1; - - for(int i=0; i audioFiles = new ArrayList<>(); - audioFiles.add(new AudioFile("Album")); - audioFiles.stream().forEach(file -> System.out.println(file)); - - - EncryptCezar enc = new EncryptCezar(audioFiles.toString(), 1); - System.out.println(enc.getEncText()); - - DecryptionCezar dec = new DecryptionCezar(enc.getEncText(), enc.getK()); - System.out.println(dec.getDecText()); - - audioFiles.stream().findAny(); - } -} diff --git a/src/test/module10/CaesarCipherTestDrive.java b/src/test/module10/CaesarCipherTestDrive.java new file mode 100644 index 0000000..cf91127 --- /dev/null +++ b/src/test/module10/CaesarCipherTestDrive.java @@ -0,0 +1,25 @@ +package test.module10; + +import java.io.IOException; +import java.util.Scanner; + +public class CaesarCipherTestDrive { + public static void main(String[] args) throws IOException { + + CeasarCipher ceasarCipher = new CeasarCipher(); + Scanner scanner = new Scanner(System.in); + System.out.println("Print text:"); + String text = scanner.nextLine(); + System.out.println("Print key:"); + int key = scanner.nextInt(); + System.out.println(); + System.out.println("Caesar Cipher in work:"); + + FileUtil fileUtil = new FileUtil(); + fileUtil.write("Text.txt", ceasarCipher.encrypt(text, key)); + fileUtil.read("Text.txt"); + System.out.println(); + fileUtil.write("Text.txt", ceasarCipher.decrypt(ceasarCipher.encrypt(text, key), key)); + fileUtil.read("Text.txt"); + } +} \ No newline at end of file diff --git a/src/test/module10/CeasarCipher.java b/src/test/module10/CeasarCipher.java new file mode 100644 index 0000000..2d47a1d --- /dev/null +++ b/src/test/module10/CeasarCipher.java @@ -0,0 +1,45 @@ +package test.module10; + + +public class CeasarCipher { + + public static String encrypt(String str, int keyLength) { + String encrypted = ""; + for (int i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c + (keyLength % 26); + if (c > 'Z') + c = c - 26; + } else if (Character.isLowerCase(c)) { + c = c + (keyLength % 26); + + if (c > 'z') + c = c - 26; + } + encrypted = encrypted + (char) c; + } + return encrypted; + } + + public static String decrypt(String str, int keyLength) { + String decrypted = ""; + for (int i = 0; i < str.length(); i++) { + + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c - (keyLength % 26); + + if (c < 'A') + c = c + 26; + } else if (Character.isLowerCase(c)) { + c = c - (keyLength % 26); + + if (c < 'a') + c = c + 26; + } + decrypted = decrypted + (char) c; + } + return decrypted; + } +} diff --git a/src/test/module10/CeaserCipherTest.java b/src/test/module10/CeaserCipherTest.java new file mode 100644 index 0000000..92fd4ab --- /dev/null +++ b/src/test/module10/CeaserCipherTest.java @@ -0,0 +1,33 @@ +package test.module10; + +import org.junit.Assert; +import org.junit.Test; + +public class CeaserCipherTest { + + @Test(timeout = 3000) + public void testEncrypt() throws Exception { + + final String string = "Hello Java!!!"; + final int key = 2; + + CeasarCipher ceasarCipher = new CeasarCipher(); + final String encryptString = ceasarCipher.encrypt(string, key); + + Assert.assertEquals("Jgnnq Lcxc!!!", encryptString); + } + + @Test(timeout = 3000) + public void testDeEncrypt() throws Exception { + + final String string = "Jgnnq Lcxc!!!"; + final int key = 2; + + CeasarCipher ceasarCipher = new CeasarCipher(); + final String decryptString = ceasarCipher.decrypt(string, key); + + Assert.assertEquals("Hello Java!!!", decryptString); + } + + +} \ No newline at end of file diff --git a/src/test/module10/FileUtil.java b/src/test/module10/FileUtil.java new file mode 100644 index 0000000..ff6a0ba --- /dev/null +++ b/src/test/module10/FileUtil.java @@ -0,0 +1,28 @@ +package test.module10; + +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +public class FileUtil { + + public void read(String fileName) { + try (FileReader reader = new FileReader(fileName)) { + int c; + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } + + public void write(String filename, String textToWrite) { + try (FileWriter writer = new FileWriter(filename)) { + writer.write(textToWrite); + writer.flush(); + } catch (IOException ex) { + System.out.println("Decrypt: " + ex.getMessage()); + } + } +} diff --git a/src/test/module4/ex1_square/CalculateSquareTest.java b/src/test/module4/ex1_square/CalculateSquareTest.java new file mode 100644 index 0000000..6c909e8 --- /dev/null +++ b/src/test/module4/ex1_square/CalculateSquareTest.java @@ -0,0 +1,40 @@ +package test.module4.ex1_square; + + +import org.junit.Assert; +import org.junit.Test; + +public class CalculateSquareTest { + + @Test(timeout = 3000) + public void testCountCircleSquare() throws Exception { + final int radius = 5; + + CircleSquare circleSquare = new CircleSquare(radius); + final int resultCircleSquare = circleSquare.countCircleSquare(); + + Assert.assertEquals(15, resultCircleSquare); + } + + @Test(timeout = 3000) + public void testCountRectangleSquare() throws Exception { + final int heightOfRectangle = 9; + final int widthOfRectangle = 8; + + RectangleSquare rectangleSquare = new RectangleSquare(heightOfRectangle, widthOfRectangle); + final int resultRectangleSquare = rectangleSquare.countRectangleSquare(); + + Assert.assertEquals(72, resultRectangleSquare); + } + + @Test(timeout = 3000) + public void testCountTriangleSquare() throws Exception { + final int sideOfTriangle = 5; + final int heightOfTriangle = 5; + + TriangleSquare triangleSquare = new TriangleSquare(sideOfTriangle, heightOfTriangle); + final int resultTriangleSquare = triangleSquare.countTriangleSquare(); + + Assert.assertEquals(12, resultTriangleSquare); + } +} diff --git a/src/test/module4/ex1_square/CalculateSquareTestDrive.java b/src/test/module4/ex1_square/CalculateSquareTestDrive.java new file mode 100644 index 0000000..2df0e9e --- /dev/null +++ b/src/test/module4/ex1_square/CalculateSquareTestDrive.java @@ -0,0 +1,20 @@ +package test.module4.ex1_square; + +public class CalculateSquareTestDrive { + public static void main(String[] args) { + CircleSquare circleSquare = new CircleSquare(5); + TriangleSquare triangleSquare = new TriangleSquare(5, 5); + RectangleSquare rectangleSquare = new RectangleSquare(9, 8); + + /* circleSquare.setRadius(6); + triangleSquare.setHeightOfTriangle(5); + triangleSquare.setSideOfTriangle(5); + rectangleSquare.setHeightOfRectangle(9); + rectangleSquare.setWidthOfRectangle(8); + */ + + System.out.println("Площадь круга = " + circleSquare.countCircleSquare() + ";"); //Circle Square + System.out.println("Площадь треугольника = " + triangleSquare.countTriangleSquare() + ";"); //Triangle Square + System.out.println("Площадь прямоугольника = " + rectangleSquare.countRectangleSquare() + ";"); //Rectangle Square + } +} diff --git a/src/test/module4/ex1_square/CircleSquare.java b/src/test/module4/ex1_square/CircleSquare.java new file mode 100644 index 0000000..4e2023d --- /dev/null +++ b/src/test/module4/ex1_square/CircleSquare.java @@ -0,0 +1,14 @@ +package test.module4.ex1_square; + +public class CircleSquare { + + private int radius; //radius of circle + + public CircleSquare(int radius) { + this.radius = radius; + } + + public int countCircleSquare() { + return (int) (Math.PI * radius); + } +} diff --git a/src/test/module4/ex1_square/RectangleSquare.java b/src/test/module4/ex1_square/RectangleSquare.java new file mode 100644 index 0000000..42b26e6 --- /dev/null +++ b/src/test/module4/ex1_square/RectangleSquare.java @@ -0,0 +1,15 @@ +package test.module4.ex1_square; + +public class RectangleSquare { + private int heightOfRectangle; + private int widthOfRectangle; + + public RectangleSquare(int heightOfRectangle, int widthOfRectangle) { + this.heightOfRectangle = heightOfRectangle; + this.widthOfRectangle = widthOfRectangle; + } + + public int countRectangleSquare() { + return heightOfRectangle * widthOfRectangle; + } +} diff --git a/src/test/module4/ex1_square/TriangleSquare.java b/src/test/module4/ex1_square/TriangleSquare.java new file mode 100644 index 0000000..5ef0055 --- /dev/null +++ b/src/test/module4/ex1_square/TriangleSquare.java @@ -0,0 +1,16 @@ +package test.module4.ex1_square; + +public class TriangleSquare { + + private int sideOfTriangle; + private int heightOfTriangle; //the height of a triangle lowered on the side "sideOfTriangle" + + public TriangleSquare(int sideOfTriangle, int heightOfTriangle) { + this.sideOfTriangle = sideOfTriangle; + this.heightOfTriangle = heightOfTriangle; + } + + public int countTriangleSquare() { + return (sideOfTriangle * heightOfTriangle) / 2; + } +} diff --git a/src/test/module4/ex2_temperature/ConvertsTemperature.java b/src/test/module4/ex2_temperature/ConvertsTemperature.java new file mode 100644 index 0000000..852a35f --- /dev/null +++ b/src/test/module4/ex2_temperature/ConvertsTemperature.java @@ -0,0 +1,39 @@ +package test.module4.ex2_temperature; + +/** + * Создать класс преобразующий значение температуры по шкале Цельсия + * в значение по шкале Фаренгейта и в обратном направлении. + */ +public class ConvertsTemperature { + + private int celsiusDegree; + private int fahrenheitDegree; + + public int getCelsiusDegree() { + return celsiusDegree; + } + + public int getFahrenheitDegree() { + return fahrenheitDegree; + } + + public void setCelsiusDegree(int celsiusDegree) { + this.celsiusDegree = celsiusDegree; + } + + public void setFahrenheitDegree(int fahrenheitDegree) { + this.fahrenheitDegree = fahrenheitDegree; + } + + public double celsiusToFahrenheit() { + double convertCelsiusToFahrenheit = celsiusDegree * 33.8; + return convertCelsiusToFahrenheit; + } + + public double fahrenheitToCelsius() { + double convertFahrenheitToCelsius = celsiusDegree / 33.8; + return convertFahrenheitToCelsius; + } +} + + diff --git a/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java b/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java new file mode 100644 index 0000000..8fe191b --- /dev/null +++ b/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java @@ -0,0 +1,30 @@ +package test.module4.ex2_temperature; + + +import org.junit.Assert; +import org.junit.Test; + +public class ConvertsTemperatureTest { + + @Test(timeout = 3000) + public void testCelsiusToFahrenheit() throws Exception { + final double fahrenheitDegree = 709.8; + + ConvertsTemperature convertsTemperature = new ConvertsTemperature(); + convertsTemperature.setCelsiusDegree(21); + final double value = convertsTemperature.celsiusToFahrenheit(); + + Assert.assertEquals(fahrenheitDegree, value, 0.1); + } + + @Test(timeout = 3000) + public void testFahrenheitToCelsius() throws Exception { + final double celsiusDegree = 21; + + ConvertsTemperature convertsTemperature = new ConvertsTemperature(); + convertsTemperature.setFahrenheitDegree(709); + final double value = convertsTemperature.fahrenheitToCelsius(); + + Assert.assertEquals(celsiusDegree, value, 0.1); + } +} diff --git a/src/test/module4/ex2_temperature/ConvertsTemperatureTestDrive.java b/src/test/module4/ex2_temperature/ConvertsTemperatureTestDrive.java new file mode 100644 index 0000000..434ea18 --- /dev/null +++ b/src/test/module4/ex2_temperature/ConvertsTemperatureTestDrive.java @@ -0,0 +1,12 @@ +package test.module4.ex2_temperature; + +public class ConvertsTemperatureTestDrive { + public static void main(String[] args) { + ConvertsTemperature convertsTemperature = new ConvertsTemperature(); + convertsTemperature.setCelsiusDegree(21); + convertsTemperature.setFahrenheitDegree(263); + + System.out.println(convertsTemperature.getCelsiusDegree() + " градусов Цельсия по шкале Фаренгейта равняется " + convertsTemperature.celsiusToFahrenheit() + ";"); + System.out.println(convertsTemperature.getFahrenheitDegree() + " градусов Фаренгейтая по шкале Цельсия равняется " + Math.round(convertsTemperature.fahrenheitToCelsius()) + ";"); + } +} diff --git a/src/test/module4/ex3_distance/CalculateDistance.java b/src/test/module4/ex3_distance/CalculateDistance.java new file mode 100644 index 0000000..df3592c --- /dev/null +++ b/src/test/module4/ex3_distance/CalculateDistance.java @@ -0,0 +1,46 @@ +package test.module4.ex3_distance; + +public class CalculateDistance { + + private int x1; + private int x2; + private int y1; + private int y2; + + public void setX1(int x1) { + this.x1 = x1; + } + + public void setX2(int x2) { + this.x2 = x2; + } + + public void setY1(int y1) { + this.y1 = y1; + } + + public void setY2(int y2) { + this.y2 = y2; + } + + public int getX1() { + return x1; + } + + public int getX2() { + return x2; + } + + public int getY1() { + return y1; + } + + public int getY2() { + return y2; + } + + public int distanceBetweenTwoPoints() { + int distance = (int) Math.sqrt(Math.pow(2, (x2 - x1)) + Math.pow(2, (y2 - y1))); + return distance; + } +} diff --git a/src/test/module4/ex3_distance/CalculateDistanceTest.java b/src/test/module4/ex3_distance/CalculateDistanceTest.java new file mode 100644 index 0000000..287cab1 --- /dev/null +++ b/src/test/module4/ex3_distance/CalculateDistanceTest.java @@ -0,0 +1,23 @@ +package test.module4.ex3_distance; + +import org.junit.Assert; +import org.junit.Test; + +public class CalculateDistanceTest { + + @Test(timeout = 3000) + + public void testDistanceBetweenTwoPoints() { + int distanceForCheck = 4; + + CalculateDistance calculateDistance = new CalculateDistance(); + calculateDistance.setX1(5); + calculateDistance.setX2(9); + calculateDistance.setY1(8); + calculateDistance.setY2(7); + final int distance = calculateDistance.distanceBetweenTwoPoints(); + + Assert.assertEquals(distanceForCheck, distance); + } +} + diff --git a/src/test/module4/ex3_distance/CalculateDistanceTestDrive.java b/src/test/module4/ex3_distance/CalculateDistanceTestDrive.java new file mode 100644 index 0000000..994cc89 --- /dev/null +++ b/src/test/module4/ex3_distance/CalculateDistanceTestDrive.java @@ -0,0 +1,13 @@ +package test.module4.ex3_distance; + +public class CalculateDistanceTestDrive { + public static void main(String[] args) { + CalculateDistance calculateDistance = new CalculateDistance(); + calculateDistance.setX1(5); + calculateDistance.setX2(9); + calculateDistance.setY1(8); + calculateDistance.setY2(7); + System.out.println("Pасстояние между двумя точками " + "A(" + calculateDistance.getX1() + ";" + calculateDistance.getY1() + ") и " + "B(" + calculateDistance.getX2() + ";" + calculateDistance.getY2() + ") " + "равняется " + calculateDistance.distanceBetweenTwoPoints()); + + } +} diff --git a/src/test/module5/ArrMinMaxSortTest.java b/src/test/module5/ArrMinMaxSortTest.java new file mode 100644 index 0000000..96ca512 --- /dev/null +++ b/src/test/module5/ArrMinMaxSortTest.java @@ -0,0 +1,41 @@ +package test.module5; + + +import org.junit.Assert; +import org.junit.Test; + +public class ArrMinMaxSortTest { + + @Test(timeout = 3000) + public void testDoBubbleSort() throws Exception { + final int[] arr = {1, 2, 3, 4}; + final int[] arrToDoBubbleSort = {2, 1, 4, 3}; + + ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive(); + final int[] resultDoBubbleSort = arrMinMaxSortTestDrive.doBubbleSort(arrToDoBubbleSort); + + Assert.assertArrayEquals(arr, resultDoBubbleSort); + } + @Test(timeout = 3000) + public void testGetMaxValue() throws Exception { + final int[] arr = {1, 2, 3, 4}; + final int max = 4; + + ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive(); + final int resultMax = arrMinMaxSortTestDrive.getMaxValue(arr); + + Assert.assertEquals(max, resultMax); + } + + @Test(timeout = 3000) + public void testGetMinValue() throws Exception { + final int[] arr = {1, 2, 3, 4}; + final int min = 1; + + ArrMinMaxSortTestDrive arrMinMaxSortTestDrive = new ArrMinMaxSortTestDrive(); + final int resultMin = arrMinMaxSortTestDrive.getMinValue(arr); + + Assert.assertEquals(min, resultMin); + } +} + diff --git a/src/test/module5/ArrMinMaxSortTestDrive.java b/src/test/module5/ArrMinMaxSortTestDrive.java new file mode 100644 index 0000000..7b0606a --- /dev/null +++ b/src/test/module5/ArrMinMaxSortTestDrive.java @@ -0,0 +1,56 @@ +package test.module5; + +import java.util.Arrays; + +/* +Создать класс, который осуществляет поиск максимального и минимального элемента в массиве из целых чисел (int[]). +Выбрать один из алгоритмов сортировки массивов и реализовать его + */ +public class ArrMinMaxSortTestDrive { + public static void main(String[] args) { + + int[] arr = {1, 4, 9, 8, 3}; + + System.out.println("Max Array's value is " + getMaxValue(arr)); + System.out.println("Min Array's value is " + getMinValue(arr)); + + + System.out.println("Sort arr using 'bubble sort':" + Arrays.toString(doBubbleSort(arr))); + } + + public static int[] doBubbleSort(int[] arr) { + for (int i = 0; i < arr.length - 1; i++) { + for (int j = 0; j < arr.length - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + int tmp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = tmp; + } + } + } + return arr; + } + + public static int getMaxValue(int[] arr) { + int maxValue = arr[0]; + for (int i = 0; i < arr.length; i++) { + if (arr[i] > maxValue) { + maxValue = arr[i]; + } + } + return maxValue; + } + + public static int getMinValue(int[] arr) { + int minValue = arr[0]; + for (int i = 0; i < arr.length; i++) { + if (arr[i] < minValue) { + minValue = arr[i]; + } + } + return minValue; + } +} + + + diff --git a/src/test/AudioFile.java b/src/test/module9/AudioFile.java similarity index 85% rename from src/test/AudioFile.java rename to src/test/module9/AudioFile.java index 230b741..4bf2b7f 100644 --- a/src/test/AudioFile.java +++ b/src/test/module9/AudioFile.java @@ -1,4 +1,4 @@ -package test; +package test.module9; public class AudioFile extends File { @@ -14,7 +14,7 @@ public String getTypeOfFile() { @Override public String toString() { - return typeOfFile; + return typeOfFile; } } \ No newline at end of file diff --git a/src/test/module9/CezarTest.java b/src/test/module9/CezarTest.java new file mode 100644 index 0000000..fb822fe --- /dev/null +++ b/src/test/module9/CezarTest.java @@ -0,0 +1,31 @@ +package test.module9; + +import org.junit.Assert; +import org.junit.Test; + +public class CezarTest { + + @Test(timeout = 3000) + public void testEncrypt() throws Exception { + + final String string = "Audio file"; + final int key = 2; + + CezarTestDrive cezarTestDrive = new CezarTestDrive(); + final String encryptString = cezarTestDrive.encrypt(string, key); + + Assert.assertEquals("Cwfkq hkng", encryptString); + } + + @Test(timeout = 3000) + public void testDeEncrypt() throws Exception { + + final String string = "Cwfkq hkng"; + final int key = 2; + + CezarTestDrive cezarTestDrive = new CezarTestDrive(); + final String decryptString = cezarTestDrive.decrypt(string, key); + + Assert.assertEquals("Audio file", decryptString); + } +} diff --git a/src/test/module9/CezarTestDrive.java b/src/test/module9/CezarTestDrive.java new file mode 100644 index 0000000..354d9b9 --- /dev/null +++ b/src/test/module9/CezarTestDrive.java @@ -0,0 +1,59 @@ +package test.module9; + +import java.util.ArrayList; +import java.util.List; + +public class CezarTestDrive { + public static void main(String[] args) { + List files = new ArrayList<>(); + files.add(new AudioFile("Audio file")); + files.add(new TextFile("Text file")); + + System.out.println("File\'s List: " + files + "\n"); + System.out.println("Encrypt File's List: "); + System.out.println(encrypt((files.toString()), 2) + "\n"); + System.out.println("Decrypt File's List: "); + System.out.println(decrypt((encrypt((files.toString()), 2)), 2)); + } + + public static String encrypt(String str, int keyLength) { + String encrypted = ""; + for (int i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c + (keyLength % 26); + if (c > 'Z') + c = c - 26; + } else if (Character.isLowerCase(c)) { + c = c + (keyLength % 26); + + if (c > 'z') + c = c - 26; + } + encrypted = encrypted + (char) c; + } + return encrypted; + } + + public static String decrypt(String str, int keyLength) { + String decrypted = ""; + for (int i = 0; i < str.length(); i++) { + + int c = str.charAt(i); + if (Character.isUpperCase(c)) { + c = c - (keyLength % 26); + + if (c < 'A') + c = c + 26; + } else if (Character.isLowerCase(c)) { + c = c - (keyLength % 26); + + if (c < 'a') + c = c + 26; + } + decrypted = decrypted + (char) c; + } + return decrypted; + } +} + diff --git a/src/test/module9/Directory.java b/src/test/module9/Directory.java new file mode 100644 index 0000000..fb09557 --- /dev/null +++ b/src/test/module9/Directory.java @@ -0,0 +1,35 @@ +package test.module9; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Directory { + + + + public Directory() { + files = new ArrayList(); + } + + public void putFile(File file) { + files.add(file); + } + + public List listFiles() { + return Collections.unmodifiableList(files); + } + + public List getFiles() { + return files; + } + + @Override + public String toString() { + return "Directory{" + + "files=" + files + + '}'; + } + + private List files; +} \ No newline at end of file diff --git a/src/test/module9/File.java b/src/test/module9/File.java new file mode 100644 index 0000000..c39b3bf --- /dev/null +++ b/src/test/module9/File.java @@ -0,0 +1,17 @@ +package test.module9; + +abstract public class File { + protected String typeOfFile; + + public File() { + this.typeOfFile = this.getClass().getSimpleName(); + } + + public String getTypeOfFile() { + return typeOfFile; + } +} + + + + diff --git a/src/test/module9/TextFile.java b/src/test/module9/TextFile.java new file mode 100644 index 0000000..1920e8b --- /dev/null +++ b/src/test/module9/TextFile.java @@ -0,0 +1,20 @@ +package test.module9; + +public class TextFile extends File { + + private String typeOfFile; + + public TextFile(String typeOfFile) { + this.typeOfFile = typeOfFile; + } + + public String getTypeOfFile() { + return typeOfFile; + } + + @Override + public String toString() { + return typeOfFile; + } + +} \ No newline at end of file From e5b64b369786798e15707f601a4c61bc352a1061 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 16 Apr 2016 12:54:21 +0300 Subject: [PATCH 16/32] Remade module11 and made marge sort --- TextTest.txt | 1 + .../ex1_square/CalculateSquareTestDrive.java | 6 +++--- .../ex1_square/CalculateSquareTestDrive.java | 20 ------------------- 3 files changed, 4 insertions(+), 23 deletions(-) create mode 100644 TextTest.txt delete mode 100644 src/test/module4/ex1_square/CalculateSquareTestDrive.java diff --git a/TextTest.txt b/TextTest.txt new file mode 100644 index 0000000..fa294c1 --- /dev/null +++ b/TextTest.txt @@ -0,0 +1 @@ +Hello Sidney. \ No newline at end of file diff --git a/src/module4/ex1_square/CalculateSquareTestDrive.java b/src/module4/ex1_square/CalculateSquareTestDrive.java index 53bd803..9e19766 100644 --- a/src/module4/ex1_square/CalculateSquareTestDrive.java +++ b/src/module4/ex1_square/CalculateSquareTestDrive.java @@ -13,8 +13,8 @@ public static void main(String[] args) { rectangleSquare.setWidthOfRectangle(8); */ - System.out.println("Площадь треугольника = " + circleSquare.countCircleSquare() + ";"); //Triangle Square - System.out.println("Площадь прямоугольника = " + triangleSquare.countTriangleSquare() + ";"); //Rectangle Square - System.out.println("Площадь круга = " + rectangleSquare.countRectangleSquare() + ";"); //Circle Square + System.out.println("Площадь треугольника = " + triangleSquare.countTriangleSquare() + ";"); //Triangle Square + System.out.println("Площадь прямоугольника = " + rectangleSquare.countRectangleSquare() + ";"); //Rectangle Square + System.out.println("Площадь круга = " + circleSquare.countCircleSquare() + ";"); //Circle Square } } diff --git a/src/test/module4/ex1_square/CalculateSquareTestDrive.java b/src/test/module4/ex1_square/CalculateSquareTestDrive.java deleted file mode 100644 index 2df0e9e..0000000 --- a/src/test/module4/ex1_square/CalculateSquareTestDrive.java +++ /dev/null @@ -1,20 +0,0 @@ -package test.module4.ex1_square; - -public class CalculateSquareTestDrive { - public static void main(String[] args) { - CircleSquare circleSquare = new CircleSquare(5); - TriangleSquare triangleSquare = new TriangleSquare(5, 5); - RectangleSquare rectangleSquare = new RectangleSquare(9, 8); - - /* circleSquare.setRadius(6); - triangleSquare.setHeightOfTriangle(5); - triangleSquare.setSideOfTriangle(5); - rectangleSquare.setHeightOfRectangle(9); - rectangleSquare.setWidthOfRectangle(8); - */ - - System.out.println("Площадь круга = " + circleSquare.countCircleSquare() + ";"); //Circle Square - System.out.println("Площадь треугольника = " + triangleSquare.countTriangleSquare() + ";"); //Triangle Square - System.out.println("Площадь прямоугольника = " + rectangleSquare.countRectangleSquare() + ";"); //Rectangle Square - } -} From 07530d37ad96c9d9160783321f012f2dd4837a40 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 16 Apr 2016 12:56:16 +0300 Subject: [PATCH 17/32] Made marge sort --- src/mergeSort/MergeSort.java | 35 +++++++++++++++++++++++++++++++ src/mergeSort/MergeSortDrive.java | 27 ++++++++++++++++++++++++ src/mergeSort/MergeSortTest.java | 26 +++++++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 src/mergeSort/MergeSort.java create mode 100644 src/mergeSort/MergeSortDrive.java create mode 100644 src/mergeSort/MergeSortTest.java diff --git a/src/mergeSort/MergeSort.java b/src/mergeSort/MergeSort.java new file mode 100644 index 0000000..1c2a867 --- /dev/null +++ b/src/mergeSort/MergeSort.java @@ -0,0 +1,35 @@ +package mergeSort; + +import java.util.Arrays; + +public class MergeSort { + + public static int[] sort(int[] arr) { + if (arr.length < 2) return arr; + int m = arr.length / 2; + int[] arr1 = Arrays.copyOfRange(arr, 0, m); + int[] arr2 = Arrays.copyOfRange(arr, m, arr.length); + return merge(sort(arr1), sort(arr2)); + } + + public static int[] merge(int[] arr1, int arr2[]) { + int n = arr1.length + arr2.length; + int[] arr = new int[n]; + int i1 = 0; + int i2 = 0; + for (int i = 0; i < n; i++) { + if (i1 == arr1.length) { + arr[i] = arr2[i2++]; + } else if (i2 == arr2.length) { + arr[i] = arr1[i1++]; + } else { + if (arr1[i1] < arr2[i2]) { + arr[i] = arr1[i1++]; + } else { + arr[i] = arr2[i2++]; + } + } + } + return arr; + } +} \ No newline at end of file diff --git a/src/mergeSort/MergeSortDrive.java b/src/mergeSort/MergeSortDrive.java new file mode 100644 index 0000000..785681d --- /dev/null +++ b/src/mergeSort/MergeSortDrive.java @@ -0,0 +1,27 @@ +package mergeSort; + +import java.util.Arrays; +import java.util.Scanner; + +public class MergeSortDrive { + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + System.out.println("Ведите длину массива: "); + int size = input.nextInt(); + int array[] = new int[size]; + System.out.println("Заполните массив числами: "); + + for (int i = 0; i < size; i++) { + array[i] = input.nextInt(); + } + System.out.print("Заполненный массив состоит из следующих чисел:"); + for (int i = 0; i < size; i++) { + System.out.print(" " + array[i]); + } + System.out.println(); + + System.out.print("Отсортированный массив методом слияния: "); + MergeSort mergeSort = new MergeSort(); + System.out.println(Arrays.toString(mergeSort.sort(array))); + } +} diff --git a/src/mergeSort/MergeSortTest.java b/src/mergeSort/MergeSortTest.java new file mode 100644 index 0000000..6691838 --- /dev/null +++ b/src/mergeSort/MergeSortTest.java @@ -0,0 +1,26 @@ +package mergeSort; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; + +public class MergeSortTest { + @Test + public void testSort() throws Exception { + int[] arr = {2, 1, 9, 3}; + int[] correctArr = {1, 2, 3, 9}; + MergeSort mergeSort = new MergeSort(); + Assert.assertArrayEquals(correctArr, mergeSort.sort(arr)); + } + + @Test + public void testMerge() throws Exception { + int[] arrFirst = {2, 9, 1}; + int[] arrSecond = {8, 1, 7}; + + MergeSort mergeSort = new MergeSort(); + System.out.println(Arrays.toString(mergeSort.merge(arrFirst, arrSecond))); + } +} + From d208ef636b9badcd4c248541ddc71616dc6be691 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 16 Apr 2016 13:00:53 +0300 Subject: [PATCH 18/32] Remade module11 and made marge sort --- src/test/module10/CaesarCipherTestDrive.java | 25 -------- src/test/module10/CeasarCipher.java | 45 -------------- src/test/module10/CeaserCipherTest.java | 20 ++++++- src/test/module10/FileUtil.java | 28 --------- .../ex1_square/CalculateSquareTest.java | 23 ++++---- src/test/module4/ex1_square/CircleSquare.java | 14 ----- .../module4/ex1_square/RectangleSquare.java | 15 ----- .../module4/ex1_square/TriangleSquare.java | 16 ----- .../ex2_temperature/ConvertsTemperature.java | 39 ------------ .../ConvertsTemperatureTest.java | 2 +- .../ConvertsTemperatureTestDrive.java | 12 ---- .../ex3_distance/CalculateDistance.java | 46 --------------- .../ex3_distance/CalculateDistanceTest.java | 2 +- .../CalculateDistanceTestDrive.java | 13 ---- src/test/module5/ArrMinMaxSortTest.java | 2 +- src/test/module5/ArrMinMaxSortTestDrive.java | 56 ------------------ src/test/module9/AudioFile.java | 20 ------- src/test/module9/CezarTest.java | 2 +- src/test/module9/CezarTestDrive.java | 59 ------------------- src/test/module9/Directory.java | 35 ----------- src/test/module9/File.java | 17 ------ src/test/module9/TextFile.java | 20 ------- 22 files changed, 35 insertions(+), 476 deletions(-) delete mode 100644 src/test/module10/CaesarCipherTestDrive.java delete mode 100644 src/test/module10/CeasarCipher.java delete mode 100644 src/test/module10/FileUtil.java delete mode 100644 src/test/module4/ex1_square/CircleSquare.java delete mode 100644 src/test/module4/ex1_square/RectangleSquare.java delete mode 100644 src/test/module4/ex1_square/TriangleSquare.java delete mode 100644 src/test/module4/ex2_temperature/ConvertsTemperature.java delete mode 100644 src/test/module4/ex2_temperature/ConvertsTemperatureTestDrive.java delete mode 100644 src/test/module4/ex3_distance/CalculateDistance.java delete mode 100644 src/test/module4/ex3_distance/CalculateDistanceTestDrive.java delete mode 100644 src/test/module5/ArrMinMaxSortTestDrive.java delete mode 100644 src/test/module9/AudioFile.java delete mode 100644 src/test/module9/CezarTestDrive.java delete mode 100644 src/test/module9/Directory.java delete mode 100644 src/test/module9/File.java delete mode 100644 src/test/module9/TextFile.java diff --git a/src/test/module10/CaesarCipherTestDrive.java b/src/test/module10/CaesarCipherTestDrive.java deleted file mode 100644 index cf91127..0000000 --- a/src/test/module10/CaesarCipherTestDrive.java +++ /dev/null @@ -1,25 +0,0 @@ -package test.module10; - -import java.io.IOException; -import java.util.Scanner; - -public class CaesarCipherTestDrive { - public static void main(String[] args) throws IOException { - - CeasarCipher ceasarCipher = new CeasarCipher(); - Scanner scanner = new Scanner(System.in); - System.out.println("Print text:"); - String text = scanner.nextLine(); - System.out.println("Print key:"); - int key = scanner.nextInt(); - System.out.println(); - System.out.println("Caesar Cipher in work:"); - - FileUtil fileUtil = new FileUtil(); - fileUtil.write("Text.txt", ceasarCipher.encrypt(text, key)); - fileUtil.read("Text.txt"); - System.out.println(); - fileUtil.write("Text.txt", ceasarCipher.decrypt(ceasarCipher.encrypt(text, key), key)); - fileUtil.read("Text.txt"); - } -} \ No newline at end of file diff --git a/src/test/module10/CeasarCipher.java b/src/test/module10/CeasarCipher.java deleted file mode 100644 index 2d47a1d..0000000 --- a/src/test/module10/CeasarCipher.java +++ /dev/null @@ -1,45 +0,0 @@ -package test.module10; - - -public class CeasarCipher { - - public static String encrypt(String str, int keyLength) { - String encrypted = ""; - for (int i = 0; i < str.length(); i++) { - int c = str.charAt(i); - if (Character.isUpperCase(c)) { - c = c + (keyLength % 26); - if (c > 'Z') - c = c - 26; - } else if (Character.isLowerCase(c)) { - c = c + (keyLength % 26); - - if (c > 'z') - c = c - 26; - } - encrypted = encrypted + (char) c; - } - return encrypted; - } - - public static String decrypt(String str, int keyLength) { - String decrypted = ""; - for (int i = 0; i < str.length(); i++) { - - int c = str.charAt(i); - if (Character.isUpperCase(c)) { - c = c - (keyLength % 26); - - if (c < 'A') - c = c + 26; - } else if (Character.isLowerCase(c)) { - c = c - (keyLength % 26); - - if (c < 'a') - c = c + 26; - } - decrypted = decrypted + (char) c; - } - return decrypted; - } -} diff --git a/src/test/module10/CeaserCipherTest.java b/src/test/module10/CeaserCipherTest.java index 92fd4ab..be06bf6 100644 --- a/src/test/module10/CeaserCipherTest.java +++ b/src/test/module10/CeaserCipherTest.java @@ -1,8 +1,11 @@ package test.module10; +import com.sun.prism.shader.Texture_Color_AlphaTest_Loader; +import module10.*; import org.junit.Assert; import org.junit.Test; + public class CeaserCipherTest { @Test(timeout = 3000) @@ -29,5 +32,20 @@ public void testDeEncrypt() throws Exception { Assert.assertEquals("Hello Java!!!", decryptString); } - + @Test(timeout = 3000) + public void testFileUtil() throws Exception { + + FileUtil fileUtil = new FileUtil(); + try { + fileUtil.write("TextTest.txt", "Hello Sidney."); + } catch (Exception e) { + e.printStackTrace(); + } + + try { + fileUtil.read("TextTest.txt"); + } catch (Exception e) { + e.printStackTrace(); + } + } } \ No newline at end of file diff --git a/src/test/module10/FileUtil.java b/src/test/module10/FileUtil.java deleted file mode 100644 index ff6a0ba..0000000 --- a/src/test/module10/FileUtil.java +++ /dev/null @@ -1,28 +0,0 @@ -package test.module10; - -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; - -public class FileUtil { - - public void read(String fileName) { - try (FileReader reader = new FileReader(fileName)) { - int c; - while ((c = reader.read()) != -1) { - System.out.print((char) c); - } - } catch (IOException ex) { - System.out.println(ex.getMessage()); - } - } - - public void write(String filename, String textToWrite) { - try (FileWriter writer = new FileWriter(filename)) { - writer.write(textToWrite); - writer.flush(); - } catch (IOException ex) { - System.out.println("Decrypt: " + ex.getMessage()); - } - } -} diff --git a/src/test/module4/ex1_square/CalculateSquareTest.java b/src/test/module4/ex1_square/CalculateSquareTest.java index 6c909e8..70e7e3c 100644 --- a/src/test/module4/ex1_square/CalculateSquareTest.java +++ b/src/test/module4/ex1_square/CalculateSquareTest.java @@ -1,5 +1,6 @@ package test.module4.ex1_square; +import module4.ex1_square.*; import org.junit.Assert; import org.junit.Test; @@ -8,33 +9,33 @@ public class CalculateSquareTest { @Test(timeout = 3000) public void testCountCircleSquare() throws Exception { - final int radius = 5; + final double radius = 5; CircleSquare circleSquare = new CircleSquare(radius); - final int resultCircleSquare = circleSquare.countCircleSquare(); + final double resultCircleSquare = circleSquare.countCircleSquare(); - Assert.assertEquals(15, resultCircleSquare); + Assert.assertEquals(78.54, resultCircleSquare, 0.01); } @Test(timeout = 3000) public void testCountRectangleSquare() throws Exception { - final int heightOfRectangle = 9; - final int widthOfRectangle = 8; + final double heightOfRectangle = 9; + final double widthOfRectangle = 8; RectangleSquare rectangleSquare = new RectangleSquare(heightOfRectangle, widthOfRectangle); - final int resultRectangleSquare = rectangleSquare.countRectangleSquare(); + final double resultRectangleSquare = rectangleSquare.countRectangleSquare(); - Assert.assertEquals(72, resultRectangleSquare); + Assert.assertEquals(36, resultRectangleSquare, 0.01); } @Test(timeout = 3000) public void testCountTriangleSquare() throws Exception { - final int sideOfTriangle = 5; - final int heightOfTriangle = 5; + final double sideOfTriangle = 5; + final double heightOfTriangle = 5; TriangleSquare triangleSquare = new TriangleSquare(sideOfTriangle, heightOfTriangle); - final int resultTriangleSquare = triangleSquare.countTriangleSquare(); + final double resultTriangleSquare = triangleSquare.countTriangleSquare(); - Assert.assertEquals(12, resultTriangleSquare); + Assert.assertEquals(12.5, resultTriangleSquare, 0.01); } } diff --git a/src/test/module4/ex1_square/CircleSquare.java b/src/test/module4/ex1_square/CircleSquare.java deleted file mode 100644 index 4e2023d..0000000 --- a/src/test/module4/ex1_square/CircleSquare.java +++ /dev/null @@ -1,14 +0,0 @@ -package test.module4.ex1_square; - -public class CircleSquare { - - private int radius; //radius of circle - - public CircleSquare(int radius) { - this.radius = radius; - } - - public int countCircleSquare() { - return (int) (Math.PI * radius); - } -} diff --git a/src/test/module4/ex1_square/RectangleSquare.java b/src/test/module4/ex1_square/RectangleSquare.java deleted file mode 100644 index 42b26e6..0000000 --- a/src/test/module4/ex1_square/RectangleSquare.java +++ /dev/null @@ -1,15 +0,0 @@ -package test.module4.ex1_square; - -public class RectangleSquare { - private int heightOfRectangle; - private int widthOfRectangle; - - public RectangleSquare(int heightOfRectangle, int widthOfRectangle) { - this.heightOfRectangle = heightOfRectangle; - this.widthOfRectangle = widthOfRectangle; - } - - public int countRectangleSquare() { - return heightOfRectangle * widthOfRectangle; - } -} diff --git a/src/test/module4/ex1_square/TriangleSquare.java b/src/test/module4/ex1_square/TriangleSquare.java deleted file mode 100644 index 5ef0055..0000000 --- a/src/test/module4/ex1_square/TriangleSquare.java +++ /dev/null @@ -1,16 +0,0 @@ -package test.module4.ex1_square; - -public class TriangleSquare { - - private int sideOfTriangle; - private int heightOfTriangle; //the height of a triangle lowered on the side "sideOfTriangle" - - public TriangleSquare(int sideOfTriangle, int heightOfTriangle) { - this.sideOfTriangle = sideOfTriangle; - this.heightOfTriangle = heightOfTriangle; - } - - public int countTriangleSquare() { - return (sideOfTriangle * heightOfTriangle) / 2; - } -} diff --git a/src/test/module4/ex2_temperature/ConvertsTemperature.java b/src/test/module4/ex2_temperature/ConvertsTemperature.java deleted file mode 100644 index 852a35f..0000000 --- a/src/test/module4/ex2_temperature/ConvertsTemperature.java +++ /dev/null @@ -1,39 +0,0 @@ -package test.module4.ex2_temperature; - -/** - * Создать класс преобразующий значение температуры по шкале Цельсия - * в значение по шкале Фаренгейта и в обратном направлении. - */ -public class ConvertsTemperature { - - private int celsiusDegree; - private int fahrenheitDegree; - - public int getCelsiusDegree() { - return celsiusDegree; - } - - public int getFahrenheitDegree() { - return fahrenheitDegree; - } - - public void setCelsiusDegree(int celsiusDegree) { - this.celsiusDegree = celsiusDegree; - } - - public void setFahrenheitDegree(int fahrenheitDegree) { - this.fahrenheitDegree = fahrenheitDegree; - } - - public double celsiusToFahrenheit() { - double convertCelsiusToFahrenheit = celsiusDegree * 33.8; - return convertCelsiusToFahrenheit; - } - - public double fahrenheitToCelsius() { - double convertFahrenheitToCelsius = celsiusDegree / 33.8; - return convertFahrenheitToCelsius; - } -} - - diff --git a/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java b/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java index 8fe191b..a41923e 100644 --- a/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java +++ b/src/test/module4/ex2_temperature/ConvertsTemperatureTest.java @@ -1,5 +1,5 @@ package test.module4.ex2_temperature; - +import module4.ex2_temperature.*; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/module4/ex2_temperature/ConvertsTemperatureTestDrive.java b/src/test/module4/ex2_temperature/ConvertsTemperatureTestDrive.java deleted file mode 100644 index 434ea18..0000000 --- a/src/test/module4/ex2_temperature/ConvertsTemperatureTestDrive.java +++ /dev/null @@ -1,12 +0,0 @@ -package test.module4.ex2_temperature; - -public class ConvertsTemperatureTestDrive { - public static void main(String[] args) { - ConvertsTemperature convertsTemperature = new ConvertsTemperature(); - convertsTemperature.setCelsiusDegree(21); - convertsTemperature.setFahrenheitDegree(263); - - System.out.println(convertsTemperature.getCelsiusDegree() + " градусов Цельсия по шкале Фаренгейта равняется " + convertsTemperature.celsiusToFahrenheit() + ";"); - System.out.println(convertsTemperature.getFahrenheitDegree() + " градусов Фаренгейтая по шкале Цельсия равняется " + Math.round(convertsTemperature.fahrenheitToCelsius()) + ";"); - } -} diff --git a/src/test/module4/ex3_distance/CalculateDistance.java b/src/test/module4/ex3_distance/CalculateDistance.java deleted file mode 100644 index df3592c..0000000 --- a/src/test/module4/ex3_distance/CalculateDistance.java +++ /dev/null @@ -1,46 +0,0 @@ -package test.module4.ex3_distance; - -public class CalculateDistance { - - private int x1; - private int x2; - private int y1; - private int y2; - - public void setX1(int x1) { - this.x1 = x1; - } - - public void setX2(int x2) { - this.x2 = x2; - } - - public void setY1(int y1) { - this.y1 = y1; - } - - public void setY2(int y2) { - this.y2 = y2; - } - - public int getX1() { - return x1; - } - - public int getX2() { - return x2; - } - - public int getY1() { - return y1; - } - - public int getY2() { - return y2; - } - - public int distanceBetweenTwoPoints() { - int distance = (int) Math.sqrt(Math.pow(2, (x2 - x1)) + Math.pow(2, (y2 - y1))); - return distance; - } -} diff --git a/src/test/module4/ex3_distance/CalculateDistanceTest.java b/src/test/module4/ex3_distance/CalculateDistanceTest.java index 287cab1..d9096fe 100644 --- a/src/test/module4/ex3_distance/CalculateDistanceTest.java +++ b/src/test/module4/ex3_distance/CalculateDistanceTest.java @@ -1,5 +1,5 @@ package test.module4.ex3_distance; - +import module4.ex3_distance.*; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/module4/ex3_distance/CalculateDistanceTestDrive.java b/src/test/module4/ex3_distance/CalculateDistanceTestDrive.java deleted file mode 100644 index 994cc89..0000000 --- a/src/test/module4/ex3_distance/CalculateDistanceTestDrive.java +++ /dev/null @@ -1,13 +0,0 @@ -package test.module4.ex3_distance; - -public class CalculateDistanceTestDrive { - public static void main(String[] args) { - CalculateDistance calculateDistance = new CalculateDistance(); - calculateDistance.setX1(5); - calculateDistance.setX2(9); - calculateDistance.setY1(8); - calculateDistance.setY2(7); - System.out.println("Pасстояние между двумя точками " + "A(" + calculateDistance.getX1() + ";" + calculateDistance.getY1() + ") и " + "B(" + calculateDistance.getX2() + ";" + calculateDistance.getY2() + ") " + "равняется " + calculateDistance.distanceBetweenTwoPoints()); - - } -} diff --git a/src/test/module5/ArrMinMaxSortTest.java b/src/test/module5/ArrMinMaxSortTest.java index 96ca512..5fe253e 100644 --- a/src/test/module5/ArrMinMaxSortTest.java +++ b/src/test/module5/ArrMinMaxSortTest.java @@ -1,5 +1,5 @@ package test.module5; - +import module5.*; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/module5/ArrMinMaxSortTestDrive.java b/src/test/module5/ArrMinMaxSortTestDrive.java deleted file mode 100644 index 7b0606a..0000000 --- a/src/test/module5/ArrMinMaxSortTestDrive.java +++ /dev/null @@ -1,56 +0,0 @@ -package test.module5; - -import java.util.Arrays; - -/* -Создать класс, который осуществляет поиск максимального и минимального элемента в массиве из целых чисел (int[]). -Выбрать один из алгоритмов сортировки массивов и реализовать его - */ -public class ArrMinMaxSortTestDrive { - public static void main(String[] args) { - - int[] arr = {1, 4, 9, 8, 3}; - - System.out.println("Max Array's value is " + getMaxValue(arr)); - System.out.println("Min Array's value is " + getMinValue(arr)); - - - System.out.println("Sort arr using 'bubble sort':" + Arrays.toString(doBubbleSort(arr))); - } - - public static int[] doBubbleSort(int[] arr) { - for (int i = 0; i < arr.length - 1; i++) { - for (int j = 0; j < arr.length - i - 1; j++) { - if (arr[j] > arr[j + 1]) { - int tmp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = tmp; - } - } - } - return arr; - } - - public static int getMaxValue(int[] arr) { - int maxValue = arr[0]; - for (int i = 0; i < arr.length; i++) { - if (arr[i] > maxValue) { - maxValue = arr[i]; - } - } - return maxValue; - } - - public static int getMinValue(int[] arr) { - int minValue = arr[0]; - for (int i = 0; i < arr.length; i++) { - if (arr[i] < minValue) { - minValue = arr[i]; - } - } - return minValue; - } -} - - - diff --git a/src/test/module9/AudioFile.java b/src/test/module9/AudioFile.java deleted file mode 100644 index 4bf2b7f..0000000 --- a/src/test/module9/AudioFile.java +++ /dev/null @@ -1,20 +0,0 @@ -package test.module9; - -public class AudioFile extends File { - - private String typeOfFile; - - public AudioFile(String typeOfFile) { - this.typeOfFile = typeOfFile; - } - - public String getTypeOfFile() { - return typeOfFile; - } - - @Override - public String toString() { - return typeOfFile; - } - -} \ No newline at end of file diff --git a/src/test/module9/CezarTest.java b/src/test/module9/CezarTest.java index fb822fe..52d6cd1 100644 --- a/src/test/module9/CezarTest.java +++ b/src/test/module9/CezarTest.java @@ -1,5 +1,5 @@ package test.module9; - +import module9.*; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/module9/CezarTestDrive.java b/src/test/module9/CezarTestDrive.java deleted file mode 100644 index 354d9b9..0000000 --- a/src/test/module9/CezarTestDrive.java +++ /dev/null @@ -1,59 +0,0 @@ -package test.module9; - -import java.util.ArrayList; -import java.util.List; - -public class CezarTestDrive { - public static void main(String[] args) { - List files = new ArrayList<>(); - files.add(new AudioFile("Audio file")); - files.add(new TextFile("Text file")); - - System.out.println("File\'s List: " + files + "\n"); - System.out.println("Encrypt File's List: "); - System.out.println(encrypt((files.toString()), 2) + "\n"); - System.out.println("Decrypt File's List: "); - System.out.println(decrypt((encrypt((files.toString()), 2)), 2)); - } - - public static String encrypt(String str, int keyLength) { - String encrypted = ""; - for (int i = 0; i < str.length(); i++) { - int c = str.charAt(i); - if (Character.isUpperCase(c)) { - c = c + (keyLength % 26); - if (c > 'Z') - c = c - 26; - } else if (Character.isLowerCase(c)) { - c = c + (keyLength % 26); - - if (c > 'z') - c = c - 26; - } - encrypted = encrypted + (char) c; - } - return encrypted; - } - - public static String decrypt(String str, int keyLength) { - String decrypted = ""; - for (int i = 0; i < str.length(); i++) { - - int c = str.charAt(i); - if (Character.isUpperCase(c)) { - c = c - (keyLength % 26); - - if (c < 'A') - c = c + 26; - } else if (Character.isLowerCase(c)) { - c = c - (keyLength % 26); - - if (c < 'a') - c = c + 26; - } - decrypted = decrypted + (char) c; - } - return decrypted; - } -} - diff --git a/src/test/module9/Directory.java b/src/test/module9/Directory.java deleted file mode 100644 index fb09557..0000000 --- a/src/test/module9/Directory.java +++ /dev/null @@ -1,35 +0,0 @@ -package test.module9; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class Directory { - - - - public Directory() { - files = new ArrayList(); - } - - public void putFile(File file) { - files.add(file); - } - - public List listFiles() { - return Collections.unmodifiableList(files); - } - - public List getFiles() { - return files; - } - - @Override - public String toString() { - return "Directory{" + - "files=" + files + - '}'; - } - - private List files; -} \ No newline at end of file diff --git a/src/test/module9/File.java b/src/test/module9/File.java deleted file mode 100644 index c39b3bf..0000000 --- a/src/test/module9/File.java +++ /dev/null @@ -1,17 +0,0 @@ -package test.module9; - -abstract public class File { - protected String typeOfFile; - - public File() { - this.typeOfFile = this.getClass().getSimpleName(); - } - - public String getTypeOfFile() { - return typeOfFile; - } -} - - - - diff --git a/src/test/module9/TextFile.java b/src/test/module9/TextFile.java deleted file mode 100644 index 1920e8b..0000000 --- a/src/test/module9/TextFile.java +++ /dev/null @@ -1,20 +0,0 @@ -package test.module9; - -public class TextFile extends File { - - private String typeOfFile; - - public TextFile(String typeOfFile) { - this.typeOfFile = typeOfFile; - } - - public String getTypeOfFile() { - return typeOfFile; - } - - @Override - public String toString() { - return typeOfFile; - } - -} \ No newline at end of file From 51be6ff9e52e577e80afbd88f0e6036f1b980a67 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 16 Apr 2016 13:02:05 +0300 Subject: [PATCH 19/32] Remade module11 and made marge sort --- src/module4/ex1_square/CircleSquare.java | 11 +++++++---- src/module4/ex1_square/RectangleSquare.java | 13 ++++++++----- src/module4/ex1_square/TriangleSquare.java | 13 ++++++++----- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/module4/ex1_square/CircleSquare.java b/src/module4/ex1_square/CircleSquare.java index 9e96bdb..fd5db1f 100644 --- a/src/module4/ex1_square/CircleSquare.java +++ b/src/module4/ex1_square/CircleSquare.java @@ -1,14 +1,17 @@ package module4.ex1_square; +import java.math.BigDecimal; +import java.math.RoundingMode; + public class CircleSquare { - private int radius; //radius of circle + private double radius; //radius of circle - public CircleSquare(int radius) { + public CircleSquare(double radius) { this.radius = radius; } - public int countCircleSquare() { - return (int) (Math.PI * radius); + public double countCircleSquare() { + return new BigDecimal(Math.PI * (radius * radius)).setScale(3, RoundingMode.UP).doubleValue(); } } diff --git a/src/module4/ex1_square/RectangleSquare.java b/src/module4/ex1_square/RectangleSquare.java index 27fbd5a..19fd843 100644 --- a/src/module4/ex1_square/RectangleSquare.java +++ b/src/module4/ex1_square/RectangleSquare.java @@ -1,15 +1,18 @@ package module4.ex1_square; +import java.math.BigDecimal; +import java.math.RoundingMode; + public class RectangleSquare { - private int heightOfRectangle; - private int widthOfRectangle; + private double heightOfRectangle; + private double widthOfRectangle; - public RectangleSquare(int heightOfRectangle, int widthOfRectangle) { + public RectangleSquare(double heightOfRectangle, double widthOfRectangle) { this.heightOfRectangle = heightOfRectangle; this.widthOfRectangle = widthOfRectangle; } - public int countRectangleSquare() { - return heightOfRectangle * widthOfRectangle; + public double countRectangleSquare() { + return new BigDecimal((heightOfRectangle * widthOfRectangle) / 2).setScale(3, RoundingMode.UP).doubleValue(); } } diff --git a/src/module4/ex1_square/TriangleSquare.java b/src/module4/ex1_square/TriangleSquare.java index 470004b..6d58cf8 100644 --- a/src/module4/ex1_square/TriangleSquare.java +++ b/src/module4/ex1_square/TriangleSquare.java @@ -1,16 +1,19 @@ package module4.ex1_square; +import java.math.BigDecimal; +import java.math.RoundingMode; + public class TriangleSquare { - private int sideOfTriangle; - private int heightOfTriangle; //the height of a triangle lowered on the side "sideOfTriangle" + private double sideOfTriangle; + private double heightOfTriangle; //the height of a triangle lowered on the side "sideOfTriangle" - public TriangleSquare(int sideOfTriangle, int heightOfTriangle) { + public TriangleSquare(double sideOfTriangle, double heightOfTriangle) { this.sideOfTriangle = sideOfTriangle; this.heightOfTriangle = heightOfTriangle; } - public int countTriangleSquare() { - return (sideOfTriangle * heightOfTriangle) / 2; + public double countTriangleSquare() { + return new BigDecimal((sideOfTriangle * heightOfTriangle) / 2).setScale(3, RoundingMode.UP).doubleValue(); } } From 9d72bfcdb5749f4e54472d3cbf52d632995991eb Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sun, 17 Apr 2016 00:44:23 +0300 Subject: [PATCH 20/32] merge sort ver.2 --- ArrayForMargeSort.txt | 1 + src/mergeSort/ArrayReader.java | 5 +++ src/mergeSort/ArrayWriter.java | 5 +++ src/mergeSort/ConsoleArrayReader.java | 46 ++++++++++++++++++++ src/mergeSort/FileArrayReader.java | 62 +++++++++++++++++++++++++++ src/mergeSort/MergeSortDrive.java | 30 ++++++------- src/mergeSort/MergeSortTest.java | 1 + 7 files changed, 135 insertions(+), 15 deletions(-) create mode 100644 ArrayForMargeSort.txt create mode 100644 src/mergeSort/ArrayReader.java create mode 100644 src/mergeSort/ArrayWriter.java create mode 100644 src/mergeSort/ConsoleArrayReader.java create mode 100644 src/mergeSort/FileArrayReader.java diff --git a/ArrayForMargeSort.txt b/ArrayForMargeSort.txt new file mode 100644 index 0000000..9883a22 --- /dev/null +++ b/ArrayForMargeSort.txt @@ -0,0 +1 @@ +[1, 5, 9, 5, 3] \ No newline at end of file diff --git a/src/mergeSort/ArrayReader.java b/src/mergeSort/ArrayReader.java new file mode 100644 index 0000000..739e271 --- /dev/null +++ b/src/mergeSort/ArrayReader.java @@ -0,0 +1,5 @@ +package mergeSort; + +public interface ArrayReader { + public abstract void read(); +} diff --git a/src/mergeSort/ArrayWriter.java b/src/mergeSort/ArrayWriter.java new file mode 100644 index 0000000..5a1686c --- /dev/null +++ b/src/mergeSort/ArrayWriter.java @@ -0,0 +1,5 @@ +package mergeSort; + +public interface ArrayWriter { + public abstract void write(); +} diff --git a/src/mergeSort/ConsoleArrayReader.java b/src/mergeSort/ConsoleArrayReader.java new file mode 100644 index 0000000..c53ed7f --- /dev/null +++ b/src/mergeSort/ConsoleArrayReader.java @@ -0,0 +1,46 @@ +package mergeSort; + + +import java.util.Scanner; + +public class ConsoleArrayReader implements ArrayReader, ArrayWriter { + + private int size; + private int array[]; + + public int[] getArray() { + return array; + } + + public void setArray(int[] array) { + this.array = array; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + @Override + public void write() { + Scanner input = new Scanner(System.in); + System.out.println("Ведите длину массива: "); + setSize(input.nextInt()); + setArray(new int[getSize()]); + System.out.println("Заполните массив числами: "); + for (int i = 0; i < size; i++) { + array[i] = input.nextInt(); + } + } + + @Override + public void read() { + System.out.print("Заполненный массив состоит из следующих чисел:"); + for (int i = 0; i < size; i++) { + System.out.print(" " + array[i]); + } + } +} diff --git a/src/mergeSort/FileArrayReader.java b/src/mergeSort/FileArrayReader.java new file mode 100644 index 0000000..7e64f6b --- /dev/null +++ b/src/mergeSort/FileArrayReader.java @@ -0,0 +1,62 @@ +package mergeSort; + + +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Arrays; +import java.util.Scanner; + +public class FileArrayReader implements ArrayWriter, ArrayReader { + private int size; + private int array[]; + String fileName = "ArrayForMargeSort.txt"; + + public int[] getArray() { + return array; + } + + public void setArray(int[] array) { + this.array = array; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + @Override + public void write() { + Scanner input = new Scanner(System.in); + System.out.println("Ведите длину массива: "); + setSize(input.nextInt()); + setArray(new int[getSize()]); + System.out.println("Заполните массив числами: "); + for (int i = 0; i < size; i++) { + array[i] = input.nextInt(); + } + + try (FileWriter writer = new FileWriter(fileName)) { + writer.write(Arrays.toString(array)); + writer.flush(); + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } + + @Override + public void read() { + try (FileReader reader = new FileReader(fileName)) { + int c; + System.out.print("Заполненный массив состоит из следующих чисел:"); + while ((c = reader.read()) != -1) { + System.out.print((char) c); + } + } catch (IOException ex) { + System.out.println(ex.getMessage()); + } + } +} diff --git a/src/mergeSort/MergeSortDrive.java b/src/mergeSort/MergeSortDrive.java index 785681d..cc91d36 100644 --- a/src/mergeSort/MergeSortDrive.java +++ b/src/mergeSort/MergeSortDrive.java @@ -1,27 +1,27 @@ package mergeSort; import java.util.Arrays; -import java.util.Scanner; public class MergeSortDrive { public static void main(String[] args) { - Scanner input = new Scanner(System.in); - System.out.println("Ведите длину массива: "); - int size = input.nextInt(); - int array[] = new int[size]; - System.out.println("Заполните массив числами: "); - for (int i = 0; i < size; i++) { - array[i] = input.nextInt(); - } - System.out.print("Заполненный массив состоит из следующих чисел:"); - for (int i = 0; i < size; i++) { - System.out.print(" " + array[i]); - } + MergeSort mergeSort = new MergeSort(); + + System.out.println("Первый вариант - считывание данных для сортировки с консоли."); + ConsoleArrayReader consoleArrayReader = new ConsoleArrayReader(); + consoleArrayReader.write(); + consoleArrayReader.read(); + System.out.println(); + System.out.print("Отсортированный массив методом слияния: "); + System.out.println(Arrays.toString(mergeSort.sort(consoleArrayReader.getArray()))); System.out.println(); + System.out.println("Второй вариант - считывание данных для сортировки с файла."); + FileArrayReader fileArrayReader = new FileArrayReader(); + fileArrayReader.write(); + fileArrayReader.read(); + System.out.println(); System.out.print("Отсортированный массив методом слияния: "); - MergeSort mergeSort = new MergeSort(); - System.out.println(Arrays.toString(mergeSort.sort(array))); + System.out.println(Arrays.toString(mergeSort.sort(fileArrayReader.getArray()))); } } diff --git a/src/mergeSort/MergeSortTest.java b/src/mergeSort/MergeSortTest.java index 6691838..e720d56 100644 --- a/src/mergeSort/MergeSortTest.java +++ b/src/mergeSort/MergeSortTest.java @@ -22,5 +22,6 @@ public void testMerge() throws Exception { MergeSort mergeSort = new MergeSort(); System.out.println(Arrays.toString(mergeSort.merge(arrFirst, arrSecond))); } + } From c55238a37de395c1b80e5b21bfd94183d753cc45 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sun, 17 Apr 2016 19:02:36 +0300 Subject: [PATCH 21/32] merge sort ver.3 --- ArrayForMargeSort.txt | 2 +- ...soleArrayReader.java => ConsoleInOut.java} | 4 +- .../{FileArrayReader.java => FileInOut.java} | 2 +- src/mergeSort/MergeSortDrive.java | 37 +++++++++++-------- src/mergeSort/MergeSortTest.java | 1 - 5 files changed, 26 insertions(+), 20 deletions(-) rename src/mergeSort/{ConsoleArrayReader.java => ConsoleInOut.java} (93%) rename src/mergeSort/{FileArrayReader.java => FileInOut.java} (95%) diff --git a/ArrayForMargeSort.txt b/ArrayForMargeSort.txt index 9883a22..7bedabe 100644 --- a/ArrayForMargeSort.txt +++ b/ArrayForMargeSort.txt @@ -1 +1 @@ -[1, 5, 9, 5, 3] \ No newline at end of file +[0, -6, 1, 2, 8, 7, 2, 2] \ No newline at end of file diff --git a/src/mergeSort/ConsoleArrayReader.java b/src/mergeSort/ConsoleInOut.java similarity index 93% rename from src/mergeSort/ConsoleArrayReader.java rename to src/mergeSort/ConsoleInOut.java index c53ed7f..cc0de5d 100644 --- a/src/mergeSort/ConsoleArrayReader.java +++ b/src/mergeSort/ConsoleInOut.java @@ -3,7 +3,7 @@ import java.util.Scanner; -public class ConsoleArrayReader implements ArrayReader, ArrayWriter { +public class ConsoleInOut implements ArrayReader, ArrayWriter { private int size; private int array[]; @@ -25,7 +25,9 @@ public void setSize(int size) { } @Override + public void write() { + Scanner input = new Scanner(System.in); System.out.println("Ведите длину массива: "); setSize(input.nextInt()); diff --git a/src/mergeSort/FileArrayReader.java b/src/mergeSort/FileInOut.java similarity index 95% rename from src/mergeSort/FileArrayReader.java rename to src/mergeSort/FileInOut.java index 7e64f6b..985d477 100644 --- a/src/mergeSort/FileArrayReader.java +++ b/src/mergeSort/FileInOut.java @@ -7,7 +7,7 @@ import java.util.Arrays; import java.util.Scanner; -public class FileArrayReader implements ArrayWriter, ArrayReader { +public class FileInOut implements ArrayWriter, ArrayReader { private int size; private int array[]; String fileName = "ArrayForMargeSort.txt"; diff --git a/src/mergeSort/MergeSortDrive.java b/src/mergeSort/MergeSortDrive.java index cc91d36..bca220f 100644 --- a/src/mergeSort/MergeSortDrive.java +++ b/src/mergeSort/MergeSortDrive.java @@ -6,22 +6,27 @@ public class MergeSortDrive { public static void main(String[] args) { MergeSort mergeSort = new MergeSort(); + try { + System.out.println("Первый вариант - считывание данных для сортировки с консоли."); + ConsoleInOut consoleArrayReader = new ConsoleInOut(); + consoleArrayReader.write(); + consoleArrayReader.read(); + System.out.println(); + System.out.print("Отсортированный массив методом слияния: "); + System.out.println(Arrays.toString(mergeSort.sort(consoleArrayReader.getArray())) + '\n'); - System.out.println("Первый вариант - считывание данных для сортировки с консоли."); - ConsoleArrayReader consoleArrayReader = new ConsoleArrayReader(); - consoleArrayReader.write(); - consoleArrayReader.read(); - System.out.println(); - System.out.print("Отсортированный массив методом слияния: "); - System.out.println(Arrays.toString(mergeSort.sort(consoleArrayReader.getArray()))); - System.out.println(); - - System.out.println("Второй вариант - считывание данных для сортировки с файла."); - FileArrayReader fileArrayReader = new FileArrayReader(); - fileArrayReader.write(); - fileArrayReader.read(); - System.out.println(); - System.out.print("Отсортированный массив методом слияния: "); - System.out.println(Arrays.toString(mergeSort.sort(fileArrayReader.getArray()))); + System.out.println("Второй вариант - считывание данных для сортировки с файла."); + FileInOut fileArrayReader = new FileInOut(); + fileArrayReader.write(); + fileArrayReader.read(); + System.out.println(); + System.out.print("Отсортированный массив методом слияния: "); + System.out.println(Arrays.toString(mergeSort.sort(fileArrayReader.getArray()))); + } catch (Exception e) { + System.out.println("Вы ввели недопустимый символ." + '\n' + + "Длина массива должна иметь цыфровое значение и быть больше ноля." + '\n' + + "Заполнять массив можно только цыфрами, значения меньше ноля допускаются." + '\n' + + "Перезагрузите пожалуйста приложение и введите данные заново."); + } } } diff --git a/src/mergeSort/MergeSortTest.java b/src/mergeSort/MergeSortTest.java index e720d56..6691838 100644 --- a/src/mergeSort/MergeSortTest.java +++ b/src/mergeSort/MergeSortTest.java @@ -22,6 +22,5 @@ public void testMerge() throws Exception { MergeSort mergeSort = new MergeSort(); System.out.println(Arrays.toString(mergeSort.merge(arrFirst, arrSecond))); } - } From 6dcbecbd805c24f0c6fd7cabe04f34294402a791 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Tue, 19 Apr 2016 02:01:50 +0300 Subject: [PATCH 22/32] Marge sort --- ArrayForMargeSort.txt | 2 +- src/mergeSort/MergeSortDrive.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ArrayForMargeSort.txt b/ArrayForMargeSort.txt index 7bedabe..770ac0a 100644 --- a/ArrayForMargeSort.txt +++ b/ArrayForMargeSort.txt @@ -1 +1 @@ -[0, -6, 1, 2, 8, 7, 2, 2] \ No newline at end of file +[9, 5, 8, 1, 2] \ No newline at end of file diff --git a/src/mergeSort/MergeSortDrive.java b/src/mergeSort/MergeSortDrive.java index bca220f..1575c2d 100644 --- a/src/mergeSort/MergeSortDrive.java +++ b/src/mergeSort/MergeSortDrive.java @@ -5,8 +5,8 @@ public class MergeSortDrive { public static void main(String[] args) { - MergeSort mergeSort = new MergeSort(); try { + MergeSort mergeSort = new MergeSort(); System.out.println("Первый вариант - считывание данных для сортировки с консоли."); ConsoleInOut consoleArrayReader = new ConsoleInOut(); consoleArrayReader.write(); @@ -25,7 +25,7 @@ public static void main(String[] args) { } catch (Exception e) { System.out.println("Вы ввели недопустимый символ." + '\n' + "Длина массива должна иметь цыфровое значение и быть больше ноля." + '\n' + - "Заполнять массив можно только цыфрами, значения меньше ноля допускаются." + '\n' + + "Заполнять массив можно только цыфрами значения меньше ноля допускаются." + '\n' + "Перезагрузите пожалуйста приложение и введите данные заново."); } } From 5b03423ec2eafe63857f184216c33a417479c0e2 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Tue, 26 Apr 2016 22:15:33 +0300 Subject: [PATCH 23/32] some work 26.04.2016 --- .idea/copyright/profiles_settings.xml | 3 ++ src/some/Numbers.java | 22 ++++++++++++++ src/test/PracticeOne/FindMaxNumberTest.java | 18 ++++++++++++ src/test/PracticeOne/FirstOddNumberTest.java | 17 +++++++++++ src/test/PracticeOne/JoinCharactersTest.java | 29 +++++++++++++++++++ .../PracticeOne/MatrixSnakeTraversalTest.java | 26 +++++++++++++++++ src/test/PracticeOne/SumDigitsTest.java | 17 +++++++++++ 7 files changed, 132 insertions(+) create mode 100644 .idea/copyright/profiles_settings.xml create mode 100644 src/some/Numbers.java create mode 100644 src/test/PracticeOne/FindMaxNumberTest.java create mode 100644 src/test/PracticeOne/FirstOddNumberTest.java create mode 100644 src/test/PracticeOne/JoinCharactersTest.java create mode 100644 src/test/PracticeOne/MatrixSnakeTraversalTest.java create mode 100644 src/test/PracticeOne/SumDigitsTest.java diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/some/Numbers.java b/src/some/Numbers.java new file mode 100644 index 0000000..3bf2f3a --- /dev/null +++ b/src/some/Numbers.java @@ -0,0 +1,22 @@ +package some; + +/** + * Создайте программу, выводящую на экран все четырёхзначные числа последовательности 1000 1003 1006 1009 1012 1015 …. + */ +public class Numbers { + public static void main(String[] args) { + + int[] arr = new int[10]; + numbers(arr); + } + + public static void numbers(int[] arr) { + + int num = 1000; + for (int i = 0; i < arr.length; i++) { + arr[i] = num; + System.out.println(arr[i]); + num = num + 3; + } + } +} diff --git a/src/test/PracticeOne/FindMaxNumberTest.java b/src/test/PracticeOne/FindMaxNumberTest.java new file mode 100644 index 0000000..8dec9d0 --- /dev/null +++ b/src/test/PracticeOne/FindMaxNumberTest.java @@ -0,0 +1,18 @@ +package test.PracticeOne; + +import practiceOne.FindMaxNumber; +import org.junit.Assert; +import org.junit.Test; + +public class FindMaxNumberTest { + + @Test + public void testMax() throws Exception { + int[] input = {-6, -2, -3}; + int expected = -2; + FindMaxNumber findMaxNumber = new FindMaxNumber(); + int extualResult = findMaxNumber.max(input); + Assert.assertEquals(expected, extualResult); + System.out.println(extualResult); + } +} \ No newline at end of file diff --git a/src/test/PracticeOne/FirstOddNumberTest.java b/src/test/PracticeOne/FirstOddNumberTest.java new file mode 100644 index 0000000..9cafa88 --- /dev/null +++ b/src/test/PracticeOne/FirstOddNumberTest.java @@ -0,0 +1,17 @@ +package test.PracticeOne; + +import practiceOne.FirstOddNumber; +import org.junit.Assert; +import org.junit.Test; + +public class FirstOddNumberTest { + @Test + public void testFind() throws Exception { + int[] input = {}; + int expected = -1; + FirstOddNumber firstOddNumber = new FirstOddNumber(); + int extualResult = firstOddNumber.find(input); + Assert.assertEquals(expected, extualResult); + System.out.println(extualResult); + } +} \ No newline at end of file diff --git a/src/test/PracticeOne/JoinCharactersTest.java b/src/test/PracticeOne/JoinCharactersTest.java new file mode 100644 index 0000000..385747a --- /dev/null +++ b/src/test/PracticeOne/JoinCharactersTest.java @@ -0,0 +1,29 @@ +package test.PracticeOne; + +import practiceOne.JoinCharacters; +import org.junit.Assert; +import org.junit.Test; + + +public class JoinCharactersTest { + JoinCharacters joinCharacters = new JoinCharacters(); + + @Test + public void testSingleElementArray() throws Exception { + char[] input = {'1'}; + int expected = 1; + + int extualResult = joinCharacters.join(input); + + Assert.assertEquals("Characters should be joind correctly for single element array.", expected, extualResult); + } + + @Test + public void testThreeElementsArray() throws Exception { + char[] input = {'1', '2', '3'}; + int expected = 123; + + int extualResult = joinCharacters.join(input); + Assert.assertEquals("Characters should be joind correctly for three elements array.", expected, extualResult); + } +} \ No newline at end of file diff --git a/src/test/PracticeOne/MatrixSnakeTraversalTest.java b/src/test/PracticeOne/MatrixSnakeTraversalTest.java new file mode 100644 index 0000000..c31f3ba --- /dev/null +++ b/src/test/PracticeOne/MatrixSnakeTraversalTest.java @@ -0,0 +1,26 @@ +package test.PracticeOne; + +import practiceOne.MatrixSnakeTraversal; +import org.junit.Assert; +import org.junit.Test; + + +public class MatrixSnakeTraversalTest { + + @Test + public void testPrint() throws Exception { + int[][] input = {{1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9} }; + int [] expected = {1, 4, 7, 8, 5, 2, 3, 6, 9}; + MatrixSnakeTraversal matrixSnakeTraversal = new MatrixSnakeTraversal(); + int[] extualResult = matrixSnakeTraversal.print(input); + Assert.assertEquals(expected, extualResult); + + } +} +/* +[[ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ]] + повернути + [1, 4, 7, 8, 5, 2, 3, 6, 9] + */ \ No newline at end of file diff --git a/src/test/PracticeOne/SumDigitsTest.java b/src/test/PracticeOne/SumDigitsTest.java new file mode 100644 index 0000000..12c1250 --- /dev/null +++ b/src/test/PracticeOne/SumDigitsTest.java @@ -0,0 +1,17 @@ +package test.PracticeOne; + +import practiceOne.SumDigits; +import org.junit.Assert; +import org.junit.Test; + +public class SumDigitsTest { + @Test + public void testSum() throws Exception { + int input = -256; + int expected = 13; + SumDigits sumDigits = new SumDigits(); + int extualResult = sumDigits.sum(input); + Assert.assertEquals(expected, extualResult); + System.out.println("Sum numbers in number " + input + " is " + extualResult + "."); + } +} From 769a072082ada0d2afcc99f2f3bd060e70e80c99 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Thu, 5 May 2016 12:57:26 +0300 Subject: [PATCH 24/32] Created practice 1. --- src/practiceOne/MatrixTraversal.java | 61 +++++++++++++++++++ .../PracticeOne/MatrixSnakeTraversalTest.java | 26 ++++---- src/test/PracticeOne/MatrixTraversalTest.java | 31 ++++++++++ 3 files changed, 106 insertions(+), 12 deletions(-) create mode 100644 src/practiceOne/MatrixTraversal.java create mode 100644 src/test/PracticeOne/MatrixTraversalTest.java diff --git a/src/practiceOne/MatrixTraversal.java b/src/practiceOne/MatrixTraversal.java new file mode 100644 index 0000000..0b2ec28 --- /dev/null +++ b/src/practiceOne/MatrixTraversal.java @@ -0,0 +1,61 @@ +package practiceOne; + +import java.util.ArrayList; + +/*Обійти матрицю по спіралі і записати всі числа в одмірний масив. + Для матриці + [[1, 2, 3, 4], + [5, 6, 7, 8] + [9, 10, 11, 12] + [13, 14, 15, 16]] + вивести [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10] +*/ +public class MatrixTraversal { + public int[] print(int[][] input) { + + int m = input.length; + int n = input[0].length; + int[] matrix = new int[m * n]; + int x = 0; + int y = 0; + int index = 0; + while (m > 0 && n > 0) { + if (m == 1) { + for (int i = 0; i < n; i++) { + matrix[index] = input[x][y++]; + index++; + } + break; + } else if (n == 1) { + for (int i = 0; i < m; i++) { + matrix[index] = input[x++][y]; + index++; + } + break; + } + for (int i = 0; i < n - 1; i++) { + matrix[index] = input[x][y++]; + index++; + } + for (int i = 0; i < m - 1; i++) { + matrix[index] = input[x++][y]; + index++; + } + for (int i = 0; i < n - 1; i++) { + matrix[index] = input[x][y--]; + index++; + } + for (int i = 0; i < m - 1; i++) { + matrix[index] = input[x--][y]; + index++; + } + x++; + y++; + m = m - 2; + n = n - 2; + } + return matrix; + } + +} + diff --git a/src/test/PracticeOne/MatrixSnakeTraversalTest.java b/src/test/PracticeOne/MatrixSnakeTraversalTest.java index c31f3ba..3df0332 100644 --- a/src/test/PracticeOne/MatrixSnakeTraversalTest.java +++ b/src/test/PracticeOne/MatrixSnakeTraversalTest.java @@ -4,23 +4,25 @@ import org.junit.Assert; import org.junit.Test; +import java.util.Arrays; + public class MatrixSnakeTraversalTest { + MatrixSnakeTraversal matrixSnakeTraversal = new MatrixSnakeTraversal(); + + @Test - public void testPrint() throws Exception { - int[][] input = {{1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9} }; - int [] expected = {1, 4, 7, 8, 5, 2, 3, 6, 9}; - MatrixSnakeTraversal matrixSnakeTraversal = new MatrixSnakeTraversal(); + public void testPrintForSquareMatrix() throws Exception { + int[][] input = {{1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}}; + + int[] expected = {1, 4, 7, 8, 5, 2, 3, 6, 9}; int[] extualResult = matrixSnakeTraversal.print(input); - Assert.assertEquals(expected, extualResult); + Assert.assertArrayEquals(expected, extualResult); } + + } -/* -[[ 1, 2, 3 ], - [ 4, 5, 6 ], - [ 7, 8, 9 ]] - повернути - [1, 4, 7, 8, 5, 2, 3, 6, 9] - */ \ No newline at end of file diff --git a/src/test/PracticeOne/MatrixTraversalTest.java b/src/test/PracticeOne/MatrixTraversalTest.java new file mode 100644 index 0000000..93d525a --- /dev/null +++ b/src/test/PracticeOne/MatrixTraversalTest.java @@ -0,0 +1,31 @@ +package test.PracticeOne; +/*Обійти матрицю по спіралі і записати всі числа в одмірний масив. + Для матриці + [[1, 2, 3, 4], + [5, 6, 7, 8] + [9, 10, 11, 12] + [13, 14, 15, 16]] + вивести [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10] +*/ + +import org.junit.Assert; +import org.junit.Test; +import practiceOne.MatrixTraversal; + +public class MatrixTraversalTest { + + MatrixTraversal matrixTraversal = new MatrixTraversal(); + + @Test + public void testPrint() throws Exception { + int[][] input = {{1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16}}; + + int[] expected = {1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10}; + int[] extualResult = matrixTraversal.print(input); + Assert.assertArrayEquals(expected, extualResult); + } +} + From 6a2a018dbd16481de2b4de6f28b28622162e4227 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Wed, 11 May 2016 00:43:18 +0300 Subject: [PATCH 25/32] Cont. work with JavaPractice --- src/PracticeOne/FindMaxNumber.java | 18 ++++++++++ src/PracticeOne/FirstOddNumber.java | 18 ++++++++++ src/PracticeOne/JoinCharacters.java | 13 ++++++++ src/PracticeOne/MatrixSnakeTraversal.java | 31 +++++++++++++++++ src/PracticeOne/SumDigits.java | 21 ++++++++++++ src/practiceTwo/AddNumberBase36.java | 17 ++++++++++ src/practiceTwo/AverageNumber.java | 18 ++++++++++ src/practiceTwo/CountBits.java | 17 ++++++++++ src/practiceTwo/PositiveAverageNumber.java | 33 +++++++++++++++++++ src/test/PracticeTwo/AddNumberBase36Test.java | 18 ++++++++++ src/test/PracticeTwo/AverageNumberTest.java | 26 +++++++++++++++ src/test/PracticeTwo/CountBitsTest.java | 12 +++++++ .../PositiveAverageNumberTest.java | 25 ++++++++++++++ 13 files changed, 267 insertions(+) create mode 100644 src/PracticeOne/FindMaxNumber.java create mode 100644 src/PracticeOne/FirstOddNumber.java create mode 100644 src/PracticeOne/JoinCharacters.java create mode 100644 src/PracticeOne/MatrixSnakeTraversal.java create mode 100644 src/PracticeOne/SumDigits.java create mode 100644 src/practiceTwo/AddNumberBase36.java create mode 100644 src/practiceTwo/AverageNumber.java create mode 100644 src/practiceTwo/CountBits.java create mode 100644 src/practiceTwo/PositiveAverageNumber.java create mode 100644 src/test/PracticeTwo/AddNumberBase36Test.java create mode 100644 src/test/PracticeTwo/AverageNumberTest.java create mode 100644 src/test/PracticeTwo/CountBitsTest.java create mode 100644 src/test/PracticeTwo/PositiveAverageNumberTest.java diff --git a/src/PracticeOne/FindMaxNumber.java b/src/PracticeOne/FindMaxNumber.java new file mode 100644 index 0000000..81e03ad --- /dev/null +++ b/src/PracticeOne/FindMaxNumber.java @@ -0,0 +1,18 @@ +package practiceOne; + +/** + * Знайти максимальне число в масиві. + * Гарантується, що масив завжди не пустий. + */ +public class FindMaxNumber { + public int max(int[] input) { + + int maxNumber = input[0]; + for (int i = 0; i < input.length; i++) { + if (maxNumber < input[i]) { + maxNumber = input[i]; + } + } + return maxNumber; + } +} \ No newline at end of file diff --git a/src/PracticeOne/FirstOddNumber.java b/src/PracticeOne/FirstOddNumber.java new file mode 100644 index 0000000..0ca1a3b --- /dev/null +++ b/src/PracticeOne/FirstOddNumber.java @@ -0,0 +1,18 @@ +package practiceOne; + +/** + * Знайти перше непарне число і повернути його індекс. + * Якщо такого немає, повернути -1 + */ +public class FirstOddNumber { + public int find(int[] input) { + int result = -1; + for (int i = 0; i < input.length; i++) { + if (input[i] % 2!= 0) { + result = i; + break; + } + } + return result; + } +} \ No newline at end of file diff --git a/src/PracticeOne/JoinCharacters.java b/src/PracticeOne/JoinCharacters.java new file mode 100644 index 0000000..2e86d59 --- /dev/null +++ b/src/PracticeOne/JoinCharacters.java @@ -0,0 +1,13 @@ +package practiceOne; + + +public class JoinCharacters { + public int join(char[] input) { + int result = 0; + for (int i = 0; i < input.length; i++) { + result = result * 10 + (input[i] - '0'); + } + return result; + } +} + diff --git a/src/PracticeOne/MatrixSnakeTraversal.java b/src/PracticeOne/MatrixSnakeTraversal.java new file mode 100644 index 0000000..e464606 --- /dev/null +++ b/src/PracticeOne/MatrixSnakeTraversal.java @@ -0,0 +1,31 @@ +package practiceOne; + +/** + * Обійти матрицю "змійкою" і повернути всі числа в одномірному масиві. + * Наприклад: + * Для + * [[ 1, 2, 3 ], + * [ 4, 5, 6 ], + * [ 7, 8, 9 ]] + * повернути + * [1, 4, 7, 8, 5, 2, 3, 6, 9] + */ +public class MatrixSnakeTraversal { + public int[] print(int[][] input) { + if (input.length == 0) return new int[]{}; + int[] simpleArr = new int[input.length * input[0].length]; + int index = 0; + int i = 0; + int n = 1; + for (int j = 0; j < input[0].length; j++) { + while (i >= 0 && i < input.length) { + simpleArr[index] = input[i][j]; + index++; + i += n; + } + n = -1 * n; + i += n; + } + return simpleArr; + } +} diff --git a/src/PracticeOne/SumDigits.java b/src/PracticeOne/SumDigits.java new file mode 100644 index 0000000..d7de8af --- /dev/null +++ b/src/PracticeOne/SumDigits.java @@ -0,0 +1,21 @@ +package practiceOne; + +/*Обчислити суму цифр числа. + Наприклад сума цифр числа 123 дорівнює 6. +*/ +public class SumDigits { + public int sum(int number) { + int n; + int sum = 0; + if (number >= 0) { + for (n = number; n != 0; n /= 10) { + sum = sum + (n % 10); + } + } else { + for (n = number; n != 0; n /= 10) { + sum = sum - (n % 10); + } + } + return sum; + } +} diff --git a/src/practiceTwo/AddNumberBase36.java b/src/practiceTwo/AddNumberBase36.java new file mode 100644 index 0000000..70dbeec --- /dev/null +++ b/src/practiceTwo/AddNumberBase36.java @@ -0,0 +1,17 @@ +package practiceTwo; + +/** + Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. + Повернути суму чисел, також в системі 36. + Наприклад: + "9" + "1" = "a" + "z" + "1" = "10" + */ +public class AddNumberBase36 { + public String add(String a, String b) { +int a2 = Integer.parseInt(a); +int b2 = Integer.parseInt(a); + return null; + } +} + diff --git a/src/practiceTwo/AverageNumber.java b/src/practiceTwo/AverageNumber.java new file mode 100644 index 0000000..2ea61ab --- /dev/null +++ b/src/practiceTwo/AverageNumber.java @@ -0,0 +1,18 @@ +package practiceTwo; +/* +Знайти середнє значення двох цілих чисел. +Приклади: +average( 4, 6 ) = 5 +average( -4, -7 ) = -5 +average( -4, 7 ) = 1 + */ + +public class AverageNumber { + public static int average(int a, int b) { + long c = 2; + long averageNumberFirst = ((long) a + b) / c; + int averageNumberLast = (int) averageNumberFirst; + return averageNumberLast; + } +} + diff --git a/src/practiceTwo/CountBits.java b/src/practiceTwo/CountBits.java new file mode 100644 index 0000000..8668468 --- /dev/null +++ b/src/practiceTwo/CountBits.java @@ -0,0 +1,17 @@ +package practiceTwo; + +/** + * Для даного числа порахувати кількість біт. + * Наприклад: + * Для числа 13 в бінарному вигляді 1101 повернути 3. + */ +public class CountBits { + public int count(int num) { + int count = 0; + while (num != 0) { + count++; + num = num & (num - 1); + } + return count; + } +} \ No newline at end of file diff --git a/src/practiceTwo/PositiveAverageNumber.java b/src/practiceTwo/PositiveAverageNumber.java new file mode 100644 index 0000000..7827c46 --- /dev/null +++ b/src/practiceTwo/PositiveAverageNumber.java @@ -0,0 +1,33 @@ +package practiceTwo; + +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigInteger; + +/** + * Знайти середнє арифметике двух додатніх чисел. + * Наприклад: + * average( 2, 4 ) = 3 + * average( 4, 7 ) = 5 + */ +public class PositiveAverageNumber { + public static int average(int a, int b) { + long c = 2; + long a1 = a; + long b1 = b; + long averageNumberFirst = (a1 + b1) / c; + int averageNumberLast = (int) averageNumberFirst; + return averageNumberLast; + } +} + +/* + BigInteger c = BigInteger.valueOf(2); + BigInteger a1 = BigInteger.valueOf(a); + BigInteger b1 = BigInteger.valueOf(b); + BigInteger sum = a1.add(b1); + BigInteger averageNumberFirst = sum.divide(c); + + int averageNumberLast = averageNumberFirst.intValue(); + */ \ No newline at end of file diff --git a/src/test/PracticeTwo/AddNumberBase36Test.java b/src/test/PracticeTwo/AddNumberBase36Test.java new file mode 100644 index 0000000..af46594 --- /dev/null +++ b/src/test/PracticeTwo/AddNumberBase36Test.java @@ -0,0 +1,18 @@ +package test.PracticeTwo; + +import static org.junit.Assert.*; + +/** + Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. + Повернути суму чисел, також в системі 36. + Наприклад: + "9" + "1" = "a" + "z" + "1" = "10" + */ +public class AddNumberBase36Test { + public String add(String a, String b) { + + + return null; +} +} \ No newline at end of file diff --git a/src/test/PracticeTwo/AverageNumberTest.java b/src/test/PracticeTwo/AverageNumberTest.java new file mode 100644 index 0000000..4894cb9 --- /dev/null +++ b/src/test/PracticeTwo/AverageNumberTest.java @@ -0,0 +1,26 @@ +package test.PracticeTwo; + +import org.junit.Assert; +import org.junit.Test; +import practiceTwo.AverageNumber; + +import static org.junit.Assert.*; + +/** + Знайти середнє значення двох цілих чисел. + Приклади: + average( 4, 6 ) = 5 + average( -4, -7 ) = -5 + average( -4, 7 ) = 1 + */ +public class AverageNumberTest { + @Test + public void testAverage() throws Exception { + int inputA = 1073741824; + int inputB = 1073741824; + int expected = 1073741824; + AverageNumber averageNumber = new AverageNumber(); + int extualResult = averageNumber.average(inputA,inputB); + Assert.assertEquals(expected, extualResult); + } +} \ No newline at end of file diff --git a/src/test/PracticeTwo/CountBitsTest.java b/src/test/PracticeTwo/CountBitsTest.java new file mode 100644 index 0000000..7fe7a1f --- /dev/null +++ b/src/test/PracticeTwo/CountBitsTest.java @@ -0,0 +1,12 @@ +package test.PracticeTwo; + +import static org.junit.Assert.*; + +/** + Для даного числа порахувати кількість біт. + Наприклад: + Для числа 13 в бінарному вигляді 1101 повернути 3. + */ +public class CountBitsTest { + +} \ No newline at end of file diff --git a/src/test/PracticeTwo/PositiveAverageNumberTest.java b/src/test/PracticeTwo/PositiveAverageNumberTest.java new file mode 100644 index 0000000..0abb3f0 --- /dev/null +++ b/src/test/PracticeTwo/PositiveAverageNumberTest.java @@ -0,0 +1,25 @@ +package test.PracticeTwo; + +import org.junit.Assert; +import org.junit.Test; +import practiceTwo.PositiveAverageNumber; + +import static org.junit.Assert.*; + +/** + Знайти середнє арифметике двух додатніх чисел. + Наприклад: + average( 2, 4 ) = 3 + average( 4, 7 ) = 5 + */ +public class PositiveAverageNumberTest { + @Test + public void testAverage() throws Exception { + int inputA = 1073741824; + int inputB = 1073741824; + int expected = 1073741824; + PositiveAverageNumber averageNumber = new PositiveAverageNumber(); + int extualResult = averageNumber.average(inputA,inputB); + Assert.assertEquals(expected, extualResult); + } +} \ No newline at end of file From b9b2cc152e99af06a6eae75ebd55e4448d29027e Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sun, 22 May 2016 14:25:09 +0300 Subject: [PATCH 26/32] module 1 --- src/module1_1/Performance.java | 159 +++++++++++ src/practiceTwo/AddNumberBase36.java | 17 -- src/practice_five/BSTSearch.java | 16 ++ .../FindMaxNumber.java | 2 +- .../FirstOddNumber.java | 2 +- .../JoinCharacters.java | 2 +- .../MatrixSnakeTraversal.java | 2 +- .../MatrixTraversal.java | 4 +- .../SumDigits.java | 2 +- src/practice_three/RPN.java | 57 ++++ src/practice_three/ReversePolishNotation.java | 66 +++++ src/practice_three/UnixPath.java | 33 +++ src/practice_two/AbcNumber.java | 21 ++ src/practice_two/AddBinary.java | 38 +++ src/practice_two/AddNumberBase36.java | 121 +++++++++ .../AverageNumber.java | 2 +- .../CountBits.java | 2 +- .../PositiveAverageNumber.java | 7 +- src/practice_two/SetZero.java | 32 +++ src/some/toBase36.java | 257 ++++++++++++++++++ src/test/PracticeTwo/AddNumberBase36Test.java | 18 -- src/test/PracticeTwo/CountBitsTest.java | 12 - src/test/practice_five/BSTSearchTest.java | 16 ++ .../FindMaxNumberTest.java | 4 +- .../FirstOddNumberTest.java | 4 +- .../JoinCharactersTest.java | 4 +- .../MatrixSnakeTraversalTest.java | 6 +- .../MatrixTraversalTest.java | 4 +- .../SumDigitsTest.java | 4 +- src/test/practice_three/BinaryHeap.java | 145 ++++++++++ .../ReversePolishNotationTest.java | 18 ++ src/test/practice_two/AbcNumberTest.java | 23 ++ src/test/practice_two/AddBinaryTest.java | 32 +++ .../practice_two/AddNumberBase36Test.java | 19 ++ .../AverageNumberTest.java | 6 +- .../PositiveAverageNumberTest.java | 6 +- src/test/practice_two/SetZeroTest.java | 24 ++ 37 files changed, 1102 insertions(+), 85 deletions(-) create mode 100644 src/module1_1/Performance.java delete mode 100644 src/practiceTwo/AddNumberBase36.java create mode 100644 src/practice_five/BSTSearch.java rename src/{PracticeOne => practice_one}/FindMaxNumber.java (95%) rename src/{PracticeOne => practice_one}/FirstOddNumber.java (95%) rename src/{PracticeOne => practice_one}/JoinCharacters.java (91%) rename src/{PracticeOne => practice_one}/MatrixSnakeTraversal.java (97%) rename src/{practiceOne => practice_one}/MatrixTraversal.java (97%) rename src/{PracticeOne => practice_one}/SumDigits.java (95%) create mode 100644 src/practice_three/RPN.java create mode 100644 src/practice_three/ReversePolishNotation.java create mode 100644 src/practice_three/UnixPath.java create mode 100644 src/practice_two/AbcNumber.java create mode 100644 src/practice_two/AddBinary.java create mode 100644 src/practice_two/AddNumberBase36.java rename src/{practiceTwo => practice_two}/AverageNumber.java (94%) rename src/{practiceTwo => practice_two}/CountBits.java (94%) rename src/{practiceTwo => practice_two}/PositiveAverageNumber.java (88%) create mode 100644 src/practice_two/SetZero.java create mode 100644 src/some/toBase36.java delete mode 100644 src/test/PracticeTwo/AddNumberBase36Test.java delete mode 100644 src/test/PracticeTwo/CountBitsTest.java create mode 100644 src/test/practice_five/BSTSearchTest.java rename src/test/{PracticeOne => practice_one}/FindMaxNumberTest.java (87%) rename src/test/{PracticeOne => practice_one}/FirstOddNumberTest.java (86%) rename src/test/{PracticeOne => practice_one}/JoinCharactersTest.java (92%) rename src/test/{PracticeOne => practice_one}/MatrixSnakeTraversalTest.java (85%) rename src/test/{PracticeOne => practice_one}/MatrixTraversalTest.java (93%) rename src/test/{PracticeOne => practice_one}/SumDigitsTest.java (88%) create mode 100644 src/test/practice_three/BinaryHeap.java create mode 100644 src/test/practice_three/ReversePolishNotationTest.java create mode 100644 src/test/practice_two/AbcNumberTest.java create mode 100644 src/test/practice_two/AddBinaryTest.java create mode 100644 src/test/practice_two/AddNumberBase36Test.java rename src/test/{PracticeTwo => practice_two}/AverageNumberTest.java (86%) rename src/test/{PracticeTwo => practice_two}/PositiveAverageNumberTest.java (85%) create mode 100644 src/test/practice_two/SetZeroTest.java diff --git a/src/module1_1/Performance.java b/src/module1_1/Performance.java new file mode 100644 index 0000000..5865607 --- /dev/null +++ b/src/module1_1/Performance.java @@ -0,0 +1,159 @@ +package module1_1; + +import javax.swing.*; +import java.awt.*; +import java.util.*; + +public class Performance extends JFrame { + public static void createGUI(String nameFrame, String[] columnNames, String[][] data) { + JFrame frame = new JFrame(nameFrame); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JTable table = new JTable(data, columnNames); + + JScrollPane scrollPane = new JScrollPane(table); + + frame.getContentPane().add(scrollPane); + frame.setPreferredSize(new Dimension(700, 150)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) { + ArrayList arrayList = new ArrayList(); + LinkedList linkedList = new LinkedList(); + HashSet hashSet = new HashSet(); + TreeSet treeSet = new TreeSet(); + + + int tenThousand = 10000; + int hundredThousand = 100000; + int oneMillion = 1000000; + String tableName = "Table 10K"; + String[] columnNames = {"Collections", "add", "get", "contains", "remove", "populate", "iterator.add", "iterator.remove"}; + String[][] data = { + {"ArrayList", addListDuration(arrayList, tenThousand), getListDuration(arrayList, tenThousand), + containsListDuration(arrayList, tenThousand), removeListDuration(arrayList, tenThousand), "", + iteratorAddListDuration(arrayList, tenThousand), iteratorRemoveListDuration(arrayList, tenThousand), ""}, + + {"LinkedList", addListDuration(linkedList, tenThousand), getListDuration(linkedList, tenThousand), + containsListDuration(linkedList, tenThousand), removeListDuration(linkedList, tenThousand), "", + iteratorAddListDuration(linkedList, tenThousand), iteratorRemoveListDuration(linkedList, tenThousand)}, + + {"HashSet", addSetDuration(hashSet, tenThousand), "", containsSetDuration(hashSet, tenThousand), + removeSetDuration(hashSet, tenThousand), " ", " ", ""}, + + {"TreeSet", addSetDuration(treeSet, tenThousand), "", containsSetDuration(treeSet, tenThousand), + removeSetDuration(treeSet, tenThousand), " ", " ", ""}}; + + javax.swing.SwingUtilities.invokeLater(new Runnable() { + public void run() { + JFrame.setDefaultLookAndFeelDecorated(true); + createGUI(tableName, columnNames, data); + } + }); + } + + public static String iteratorAddListDuration(AbstractList list, int number) { + ListIterator listIterator = list.listIterator(); + long startTime = System.nanoTime(); + for (int i = 0; i < number; i++) { + listIterator.add(i); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + + return Long.toString(duration); + } + + public static String iteratorRemoveListDuration(AbstractList list, int number) { + ListIterator listIterator = list.listIterator(); + + long startTime = System.nanoTime(); + while (listIterator.hasNext()) { + long s = listIterator.next(); + listIterator.remove(); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + return Long.toString(duration); + } + + public static String addListDuration(AbstractList list, int number) { + long startTime = System.nanoTime(); + + for (int i = 0; i < number; i++) { + list.add(i); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + return Long.toString(duration); + } + + public static String addSetDuration(AbstractSet set, int number) { + long startTime = System.nanoTime(); + + for (int i = 0; i < number; i++) { + set.add(i); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + return Long.toString(duration); + } + + public static String getListDuration(AbstractList list, int number) { + long startTime = System.nanoTime(); + + for (int i = 0; i < number; i++) { + list.get(i); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + return Long.toString(duration); + } + + public static String containsListDuration(AbstractList list, int number) { + long startTime = System.nanoTime(); + + for (int i = 0; i < number; i++) { + list.contains(i); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + return Long.toString(duration); + } + + public static String containsSetDuration(AbstractSet set, int number) { + long startTime = System.nanoTime(); + + for (int i = 0; i < number; i++) { + set.contains(i); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + return Long.toString(duration); + } + + public static String removeSetDuration(AbstractSet set, int number) { + long startTime = System.nanoTime(); + + for (int i = number - 1; i >= 0; i--) { + set.remove(i); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + return Long.toString(duration); + } + + public static String removeListDuration(AbstractList list, int number) { + long startTime = System.nanoTime(); + + for (int i = number - 1; i >= 0; i--) { + list.remove(i); + } + long endTime = System.nanoTime(); + long duration = endTime - startTime; + return Long.toString(duration); + } +} diff --git a/src/practiceTwo/AddNumberBase36.java b/src/practiceTwo/AddNumberBase36.java deleted file mode 100644 index 70dbeec..0000000 --- a/src/practiceTwo/AddNumberBase36.java +++ /dev/null @@ -1,17 +0,0 @@ -package practiceTwo; - -/** - Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. - Повернути суму чисел, також в системі 36. - Наприклад: - "9" + "1" = "a" - "z" + "1" = "10" - */ -public class AddNumberBase36 { - public String add(String a, String b) { -int a2 = Integer.parseInt(a); -int b2 = Integer.parseInt(a); - return null; - } -} - diff --git a/src/practice_five/BSTSearch.java b/src/practice_five/BSTSearch.java new file mode 100644 index 0000000..1eb2002 --- /dev/null +++ b/src/practice_five/BSTSearch.java @@ -0,0 +1,16 @@ +package practice_five; + +/** + * Знайти число в бінарному дереві пошуку і повернути true якщо воно присутнє, інакше повернути false. + */ +public class BSTSearch { + // public boolean exist(TreeNode root, int target) { + + // } +} +/* +class TreeNode { + int value; + TreeNode left, right; +} +*/ \ No newline at end of file diff --git a/src/PracticeOne/FindMaxNumber.java b/src/practice_one/FindMaxNumber.java similarity index 95% rename from src/PracticeOne/FindMaxNumber.java rename to src/practice_one/FindMaxNumber.java index 81e03ad..3cb49d5 100644 --- a/src/PracticeOne/FindMaxNumber.java +++ b/src/practice_one/FindMaxNumber.java @@ -1,4 +1,4 @@ -package practiceOne; +package practice_one; /** * Знайти максимальне число в масиві. diff --git a/src/PracticeOne/FirstOddNumber.java b/src/practice_one/FirstOddNumber.java similarity index 95% rename from src/PracticeOne/FirstOddNumber.java rename to src/practice_one/FirstOddNumber.java index 0ca1a3b..71c25d9 100644 --- a/src/PracticeOne/FirstOddNumber.java +++ b/src/practice_one/FirstOddNumber.java @@ -1,4 +1,4 @@ -package practiceOne; +package practice_one; /** * Знайти перше непарне число і повернути його індекс. diff --git a/src/PracticeOne/JoinCharacters.java b/src/practice_one/JoinCharacters.java similarity index 91% rename from src/PracticeOne/JoinCharacters.java rename to src/practice_one/JoinCharacters.java index 2e86d59..1c313d6 100644 --- a/src/PracticeOne/JoinCharacters.java +++ b/src/practice_one/JoinCharacters.java @@ -1,4 +1,4 @@ -package practiceOne; +package practice_one; public class JoinCharacters { diff --git a/src/PracticeOne/MatrixSnakeTraversal.java b/src/practice_one/MatrixSnakeTraversal.java similarity index 97% rename from src/PracticeOne/MatrixSnakeTraversal.java rename to src/practice_one/MatrixSnakeTraversal.java index e464606..3a04017 100644 --- a/src/PracticeOne/MatrixSnakeTraversal.java +++ b/src/practice_one/MatrixSnakeTraversal.java @@ -1,4 +1,4 @@ -package practiceOne; +package practice_one; /** * Обійти матрицю "змійкою" і повернути всі числа в одномірному масиві. diff --git a/src/practiceOne/MatrixTraversal.java b/src/practice_one/MatrixTraversal.java similarity index 97% rename from src/practiceOne/MatrixTraversal.java rename to src/practice_one/MatrixTraversal.java index 0b2ec28..afa838c 100644 --- a/src/practiceOne/MatrixTraversal.java +++ b/src/practice_one/MatrixTraversal.java @@ -1,6 +1,4 @@ -package practiceOne; - -import java.util.ArrayList; +package practice_one; /*Обійти матрицю по спіралі і записати всі числа в одмірний масив. Для матриці diff --git a/src/PracticeOne/SumDigits.java b/src/practice_one/SumDigits.java similarity index 95% rename from src/PracticeOne/SumDigits.java rename to src/practice_one/SumDigits.java index d7de8af..7a068a9 100644 --- a/src/PracticeOne/SumDigits.java +++ b/src/practice_one/SumDigits.java @@ -1,4 +1,4 @@ -package practiceOne; +package practice_one; /*Обчислити суму цифр числа. Наприклад сума цифр числа 123 дорівнює 6. diff --git a/src/practice_three/RPN.java b/src/practice_three/RPN.java new file mode 100644 index 0000000..affe88d --- /dev/null +++ b/src/practice_three/RPN.java @@ -0,0 +1,57 @@ +package practice_three; +import java.util.LinkedList; + +public class RPN{ + public static void evalRPN(String expr){ + String cleanExpr = cleanExpr(expr); + LinkedList stack = new LinkedList(); + System.out.println("Input\tOperation\tStack after"); + for(String token:cleanExpr.split("\\s")){ + System.out.print(token+"\t"); + Double tokenNum = null; + try{ + tokenNum = Double.parseDouble(token); + }catch(NumberFormatException e){} + if(tokenNum != null){ + System.out.print("Push\t\t"); + stack.push(Double.parseDouble(token+"")); + }else if(token.equals("*")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(firstOperand * secondOperand); + }else if(token.equals("/")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(firstOperand / secondOperand); + }else if(token.equals("-")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(firstOperand - secondOperand); + }else if(token.equals("+")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(firstOperand + secondOperand); + }else if(token.equals("^")){ + System.out.print("Operate\t\t"); + double secondOperand = stack.pop(); + double firstOperand = stack.pop(); + stack.push(Math.pow(firstOperand, secondOperand)); + }else{//just in case + System.out.println("Error"); + return; + } + System.out.println(stack); + } + System.out.println("Final answer: " + stack.pop()); + } + + private static String cleanExpr(String expr){ + //remove all non-operators, non-whitespace, and non digit chars + return expr.replaceAll("[^\\^\\*\\+\\-\\d/\\s]", ""); + } + +} \ No newline at end of file diff --git a/src/practice_three/ReversePolishNotation.java b/src/practice_three/ReversePolishNotation.java new file mode 100644 index 0000000..b9d916f --- /dev/null +++ b/src/practice_three/ReversePolishNotation.java @@ -0,0 +1,66 @@ +package practice_three; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Stack; +import java.util.function.BiFunction; + +/** + * Дано арифметичний вираз у вигляді Польського Інверсного запису. + * Необхідно обчислити значення виразу і повернути його. + * Вираз складається лише з цілих чисел і операцій +, -, *, /. Гарантується, що результат також ціне число. + */ +public class ReversePolishNotation { + public int evaluate(String expression) { + String cleanExpr = cleanExpr(expression); + LinkedList stack = new LinkedList(); + System.out.println("Input\tOperation\tStack after"); + for(String token:cleanExpr.split("\\s")){ + System.out.print(token+"\t"); + Integer tokenNum = null; + try{ + tokenNum = Integer.parseInt(token); + }catch(NumberFormatException e){} + if(tokenNum != null){ + System.out.print("Push\t\t"); + stack.push(Integer.parseInt(token+"")); + }else if(token.equals("*")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push(firstOperand * secondOperand); + }else if(token.equals("/")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push(firstOperand / secondOperand); + }else if(token.equals("-")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push(firstOperand - secondOperand); + }else if(token.equals("+")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push(firstOperand + secondOperand); + }else if(token.equals("^")){ + System.out.print("Operate\t\t"); + int secondOperand = stack.pop(); + int firstOperand = stack.pop(); + stack.push((int) Math.pow(firstOperand, secondOperand)); + }else{//just in case + System.out.println("Error"); + return 0; + } + System.out.println(stack); + } + System.out.println("Final answer: " + stack.pop()); + return Integer.valueOf(stack.pop()); + } + + private static String cleanExpr(String expr){ + //remove all non-operators, non-whitespace, and non digit chars + return expr.replaceAll("[^\\^\\*\\+\\-\\d/\\s]", ""); + } +} \ No newline at end of file diff --git a/src/practice_three/UnixPath.java b/src/practice_three/UnixPath.java new file mode 100644 index 0000000..951f7c4 --- /dev/null +++ b/src/practice_three/UnixPath.java @@ -0,0 +1,33 @@ +package practice_three; + +import java.util.LinkedList; + +/** + * Дано повний шлях до файла в Unix системі. + * Наприклад /home/../var/./lib//file.txt + * Необхідно повернути спрощений варіант. (/var/lib/file.txt) + */ +public class UnixPath { + public String simplify(String input) { + if (input == null || input.length() == 0) return "/"; + + LinkedList list = new LinkedList<>(); + String[] splits = input.trim().trim().split("/"); + for (String s : splits) { + if (s == null || s.length() == 0 || s.equals(".")) continue; + else if (s.equals("..")) { + if (list.size() > 0) list.pop(); + } else { + list.push(s); + } + } + if (list.isEmpty()) return "/"; + StringBuffer stringBuffer = new StringBuffer(); + while (!list.isEmpty()) { + stringBuffer.insert(0, list.pop()); + stringBuffer.insert(0, "/"); + } + return stringBuffer.toString(); + } +} + diff --git a/src/practice_two/AbcNumber.java b/src/practice_two/AbcNumber.java new file mode 100644 index 0000000..f44318a --- /dev/null +++ b/src/practice_two/AbcNumber.java @@ -0,0 +1,21 @@ +package practice_two; + +/** + * Дано рядок отриманий шляхом заміни цифр 0,1,2,...,9 певного числа на букви a,b,c,..,j. + * Необхідно повернути початкове число маючи конвертований рядок. + * Наприклад: + * Для "bcd" повернути 123 + */ +public class AbcNumber { + public int convert(String num) { + String[] alphab = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; + String[] codes = {"0", "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"}; + + String strOut = num; + for (int i = 0; i < alphab.length; i++) { + strOut = strOut.replaceAll(alphab[i], codes[i]); + } + int finalResult = Integer.parseInt(strOut); + return finalResult; + } +} diff --git a/src/practice_two/AddBinary.java b/src/practice_two/AddBinary.java new file mode 100644 index 0000000..b4b7174 --- /dev/null +++ b/src/practice_two/AddBinary.java @@ -0,0 +1,38 @@ +package practice_two; + +/** + * Додайте два беззнакових числа, що передаються як рядки. + * "101" + "100" = "1001" + */ +public class AddBinary { + public String add(String a, String b) { + if (a == null || b == null) return ""; + int first = a.length() - 1; + int second = b.length() - 1; + StringBuilder sb = new StringBuilder(); + int carry = 0; + while (first >= 0 || second >= 0) { + int sum = carry; + if (first >= 0) { + sum += a.charAt(first) - '0'; + first--; + } + if (second >= 0) { + sum += b.charAt(second) - '0'; + second--; + } + carry = sum >> 1; + sum = sum & 1; + sb.append(sum == 0 ? '0' : '1'); + } + if (carry > 0) + sb.append('1'); + + sb.reverse(); + return String.valueOf(sb); + } +} + // Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2)); + + + diff --git a/src/practice_two/AddNumberBase36.java b/src/practice_two/AddNumberBase36.java new file mode 100644 index 0000000..8d16784 --- /dev/null +++ b/src/practice_two/AddNumberBase36.java @@ -0,0 +1,121 @@ +package practice_two; + +import java.util.ArrayList; + +/** + * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. + * Повернути суму чисел, також в системі 36. + * Наприклад: + * "9" + "1" = "a" + * "z" + "1" = "10" + */ +public class AddNumberBase36 { + public final static int base = 36; + + public String add(String a, String b) { + + return intToBase36(base36ToInt(a) + base36ToInt(b)); + } + + public static int base36ToInt(String str) { + + + str = str.toUpperCase(); + + int result = 0; + double frontVal = 0; + double lastVal = 0; + int size = str.length(); + boolean started = false; + + + frontVal = char36ToInt(str.charAt(0)); + for (int i = 0; i < size; i++) { + + if (i + 1 < size && (started || frontVal > 0.0)) { + lastVal = char36ToInt(str.charAt(i + 1)); + frontVal = (frontVal + (lastVal / ((double) base))) * ((double) base); + } else if (!started) { + if (frontVal == 0.0 && i + 1 < size) { + lastVal = char36ToInt(str.charAt(i + 1)); + if (lastVal > 0.0) { + frontVal = lastVal; + started = true; + } + + } + } + + } + result = (int) Math.round(frontVal); + return result; + } + + public static String intToBase36(int n) { + String result = ""; + ArrayList list = new ArrayList(); + int frontVal = 0; + int lastVal = 0; + int val = n; + frontVal = val; + + while (val >= base) { + frontVal = val / base; + lastVal = val % base; + list.add(Character.toString(intToChar36(lastVal))); + val = frontVal; + + } + + if (frontVal > 0) + list.add(Character.toString(intToChar36(frontVal))); + + for (int i = list.size() - 1; i >= 0; i--) + result += list.get(i).toLowerCase(); + + return result; + } + + public static char intToChar36(int n) { + + char result = (char) 0; + + if (n >= 0 && n <= 9) + result = (char) (48 + n); + else if (n > 9 && n < base) { + result = (char) (65 - 10 + n); + } + return result; + } + + public static char intToChar35(int n) { + char result = (char) 0; + if (n >= 0 && n <= 9) + result = (char) (48 + n); + else if (n > 9 && n < 14) { + result = (char) (65 - 10 + n); + } else if (n > 13 && n < 36) + result = (char) (65 - 10 + n + 1); + return result; + } + + public static int char36ToInt(char c) { + + int result = 0; + if (Character.isDigit(c)) + result = (int) c - 48; + else if (Character.isAlphabetic(c)) { + if ((int) c <= 90) { + result = (int) c - (65 - 10); + } + } + return result; + } + + public static int char35ToInt(char c) { + int result = char36ToInt(c); + if (result > 13) + result--; + return result; + } +} \ No newline at end of file diff --git a/src/practiceTwo/AverageNumber.java b/src/practice_two/AverageNumber.java similarity index 94% rename from src/practiceTwo/AverageNumber.java rename to src/practice_two/AverageNumber.java index 2ea61ab..2bddee0 100644 --- a/src/practiceTwo/AverageNumber.java +++ b/src/practice_two/AverageNumber.java @@ -1,4 +1,4 @@ -package practiceTwo; +package practice_two; /* Знайти середнє значення двох цілих чисел. Приклади: diff --git a/src/practiceTwo/CountBits.java b/src/practice_two/CountBits.java similarity index 94% rename from src/practiceTwo/CountBits.java rename to src/practice_two/CountBits.java index 8668468..3cb343c 100644 --- a/src/practiceTwo/CountBits.java +++ b/src/practice_two/CountBits.java @@ -1,4 +1,4 @@ -package practiceTwo; +package practice_two; /** * Для даного числа порахувати кількість біт. diff --git a/src/practiceTwo/PositiveAverageNumber.java b/src/practice_two/PositiveAverageNumber.java similarity index 88% rename from src/practiceTwo/PositiveAverageNumber.java rename to src/practice_two/PositiveAverageNumber.java index 7827c46..49eb5d1 100644 --- a/src/practiceTwo/PositiveAverageNumber.java +++ b/src/practice_two/PositiveAverageNumber.java @@ -1,9 +1,4 @@ -package practiceTwo; - -import org.junit.Assert; -import org.junit.Test; - -import java.math.BigInteger; +package practice_two; /** * Знайти середнє арифметике двух додатніх чисел. diff --git a/src/practice_two/SetZero.java b/src/practice_two/SetZero.java new file mode 100644 index 0000000..10309ca --- /dev/null +++ b/src/practice_two/SetZero.java @@ -0,0 +1,32 @@ +package practice_two; + +/** + * Дано число. Треба замінити i-й біт замінити на нуль. + * Наприклад: + * для числа 6 в бінарному вигляді 110, + * замінивши 2-й біт на нуль отримаємо 100 тобто 4. + * 1<= i <= 32 + */ +public class SetZero { + + public int set(int num, int i) { + char[] arr = new char[32]; + for (int index = 0; index < 32; index++) { + if (index == 32 - i) arr[index] = '0'; + else arr[index] = '1'; + } + String str = new String(arr); + Long mask = Long.parseLong(str, 2); + return num & mask.intValue(); + } +} + + +/* +String binaryString = Integer.toBinaryString(num); + char[] chars = binaryString.toCharArray(); + chars[i - 1] = '0'; + String stringNum = String.valueOf(chars); + int finalResult = Integer.parseInt(stringNum, 2); + return finalResult; + */ \ No newline at end of file diff --git a/src/some/toBase36.java b/src/some/toBase36.java new file mode 100644 index 0000000..b5ae03f --- /dev/null +++ b/src/some/toBase36.java @@ -0,0 +1,257 @@ +package some; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +/** + * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. + * Повернути суму чисел, також в системі 36. + * Наприклад: + * "9" + "1" = "a" + * "z" + "1" = "10" + */ +public class toBase36 { + public static final BigInteger C36 = BigInteger.valueOf(36); + public static void main(String[] args) { + System.out.println(new toBase36().add("zjfghfhdsdfathjjhgjhghjfjfjhjhdsrreqqklhu456hfz5", "wsfgsgds56346263fgfhghfghfhgfsrr5476hjfgdhdhg3N")); + } + public String add(String a, String b) { + BigInteger ad = toDecimal(a.toLowerCase()); + BigInteger bd = toDecimal(b.toLowerCase()); + BigInteger sum = ad.add(bd); + return fromDecimal(sum); + } + + public BigInteger toDecimal(String s){ + BigInteger result = new BigInteger("0"); + char[] chars = s.toCharArray(); + for(char c: chars){ + int diff = c>='0' && c<='9' + ? c-'0' + : c-'a'+10; + result=result.multiply(C36).add(BigInteger.valueOf(diff)); + } + return result; + } + + public String fromDecimal(BigInteger i){ + StringBuilder sb = new StringBuilder(); + + BigInteger n=i; + while(n.compareTo(BigInteger.valueOf(0))>0){ + BigInteger modBI = n.mod(C36); + int mod = modBI.intValue(); + char c = (char)(mod<=9 + ? mod+'0' + : mod+'a'-10); + sb.append(c); + n=n.divide(C36); + }; + + return sb.reverse().toString(); + } +} + + +/* + public String add(String a, String b) { + + return intToBase36(base36ToInt(a) + base36ToInt(b)); + } + + public static int base36ToInt(String str) { + + + //make sure that each case is upper + str = str.toUpperCase(); + //This function will convert a base36 string to it's int equivalent + int result = 0; + double frontVal = 0; + double lastVal = 0; + int size = str.length(); + boolean started = false; + + + frontVal = char36ToInt(str.charAt(0)); + for (int i = 0; i < size; i++) { + //TODO: log this println("frontVal = " + frontVal); + + if (i + 1 < size && (started || frontVal > 0.0)) { + lastVal = char36ToInt(str.charAt(i + 1)); + //TODO: log this println("lastVal = " + lastVal); + //should contain the temp result: + frontVal = (frontVal + (lastVal / ((double) base))) * ((double) base); + //TODO: log this println("new frontVal = " + frontVal); + } else if (!started) { + if (frontVal == 0.0 && i + 1 < size) { + lastVal = char36ToInt(str.charAt(i + 1)); + if (lastVal > 0.0) { + frontVal = lastVal; + started = true; + } + + } + } + + } + result = (int) Math.round(frontVal); + return result; + } + + public static String intToBase36(int n) {//passed test for base36! + //Converts an int value to a base36 string + String result = ""; + ArrayList list = new ArrayList(); + int frontVal = 0; + int lastVal = 0; + int val = n;//preserve input + frontVal = val; + + while (val >= base) { + + //val is greater than the base; so we need to continue loop until it is not + + frontVal = val / base;//store the front part + lastVal = val % base;//store the last part + //TODO log thisprintln("val = " + val + "\tfrontVal = " +frontVal + "\tlastVal = " + lastVal); + list.add(Character.toString(intToChar36(lastVal))); + val = frontVal; + + } + + //add last base36 digit + if (frontVal > 0) + list.add(Character.toString(intToChar36(frontVal))); + + //fill the rest of the string with 0s + // for (int i = list.size(); i < MAX_digits; i++) + // list.add("0"); + + //convert list to string, in order. + for (int i = list.size() - 1; i >= 0; i--) + result += list.get(i).toLowerCase(); + + return result; + } + + public static char intToChar36(int n) {//passed test! + //Converts the integer value to the equivalent base 36 character + char result = (char) 0; + + if (n >= 0 && n <= 9) + result = (char) (48 + n); + else if (n > 9 && n < base) { + result = (char) (65 - 10 + n); + } + return result; + } + + public static char intToChar35(int n) {//passed test! + //Same as intToChar36; however it removes the 'E' char + //Converts the integer value to the equivalent base 36 character + char result = (char) 0; + + if (n >= 0 && n <= 9) + result = (char) (48 + n); + else if (n > 9 && n < 14) { + result = (char) (65 - 10 + n); + } else if (n > 13 && n < 36) + result = (char) (65 - 10 + n + 1); + return result; + } + + public static int char36ToInt(char c) {//passed test! + //Converts a base 36 character into its equivalent value in integer + int result = 0; + if (Character.isDigit(c)) + result = (int) c - 48; + else if (Character.isAlphabetic(c)) { + //-10 because 0-9 are our 1st 10 in base36 + if ((int) c <= 90) { + result = (int) c - (65 - 10); + + } + } + return result; + } + + public static int char35ToInt(char c) {//passed test! + int result = char36ToInt(c); + if (result > 13) + result--; + return result; + + } +} +*/ + + + +/* + public static int base36ToBase10(String text) { + + String code = "0123456789abcdefghijklmnopqrstuvwxyz"; + int num = 0; + int j = text.length(); + for (int i = 0; i < j; i++) { + num += code.indexOf(text.charAt(0)) * Math.pow(code.length(), i); + text = text.substring(1); + } + return num; + } + + + public static String base10ToBase36(int num) { + String code = "0123456789abcdefghijklmnopqrstuvwxyz"; + String text = ""; + int j = (int) Math.ceil(Math.log(num) / Math.log(code.length())); + for (int i = 0; i < j; i++) { + //i goes to log base code.length() of num (using change of base formula) + text += code.charAt(num % code.length()); + num /= code.length(); + } + return text; + } +}*/ + /* public String add(String a, String b){ + return base10ToBase36(base36ToBase10(a) + base36ToBase10(b)); + } + private static String codeBase36 = "0123456789abcdefghijklmnopqrstuvwxyz"; + + //"0123456789 abcdefghij klmnopqrst uvwxyz" + //"0123456789 0123456789 0123456789 012345" + + + private static String max36=base10ToBase36(Integer.MAX_VALUE); + + public static String base10ToBase36(int inNum) { + if(inNum<0) { + throw new NumberFormatException("Value "+inNum +" to small"); + } + int num = inNum; + String text = ""; + int j = (int)Math.ceil(Math.log(num)/Math.log(codeBase36.length())); + for(int i = 0; i < j; i++){ + text = codeBase36.charAt(num%codeBase36.length())+text; + num /= codeBase36.length(); + } + return text; + } + public static int base36ToBase10(String in) { + String text = in.toLowerCase(); + if(text.compareToIgnoreCase(max36)>0) { + throw new NumberFormatException("Value "+text+" to big"); + } + + if(!text.replaceAll("(\\W)","").equalsIgnoreCase(text)){ + throw new NumberFormatException("Value "+text+" false format"); + } + int num=0; + int j = text.length(); + for(int i = 0; i < j; i++){ + num += codeBase36.indexOf(text.charAt(text.length()-1))*Math.pow(codeBase36.length(), i); + text = text.substring(0,text.length()-1); + } + return num; + }*/ diff --git a/src/test/PracticeTwo/AddNumberBase36Test.java b/src/test/PracticeTwo/AddNumberBase36Test.java deleted file mode 100644 index af46594..0000000 --- a/src/test/PracticeTwo/AddNumberBase36Test.java +++ /dev/null @@ -1,18 +0,0 @@ -package test.PracticeTwo; - -import static org.junit.Assert.*; - -/** - Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. - Повернути суму чисел, також в системі 36. - Наприклад: - "9" + "1" = "a" - "z" + "1" = "10" - */ -public class AddNumberBase36Test { - public String add(String a, String b) { - - - return null; -} -} \ No newline at end of file diff --git a/src/test/PracticeTwo/CountBitsTest.java b/src/test/PracticeTwo/CountBitsTest.java deleted file mode 100644 index 7fe7a1f..0000000 --- a/src/test/PracticeTwo/CountBitsTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package test.PracticeTwo; - -import static org.junit.Assert.*; - -/** - Для даного числа порахувати кількість біт. - Наприклад: - Для числа 13 в бінарному вигляді 1101 повернути 3. - */ -public class CountBitsTest { - -} \ No newline at end of file diff --git a/src/test/practice_five/BSTSearchTest.java b/src/test/practice_five/BSTSearchTest.java new file mode 100644 index 0000000..253b171 --- /dev/null +++ b/src/test/practice_five/BSTSearchTest.java @@ -0,0 +1,16 @@ +package test.practice_five; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Знайти число в бінарному дереві пошуку і повернути true якщо воно присутнє, інакше повернути false. + */ +public class BSTSearchTest { + + @Test + public void testExist() throws Exception { + + } +} \ No newline at end of file diff --git a/src/test/PracticeOne/FindMaxNumberTest.java b/src/test/practice_one/FindMaxNumberTest.java similarity index 87% rename from src/test/PracticeOne/FindMaxNumberTest.java rename to src/test/practice_one/FindMaxNumberTest.java index 8dec9d0..609dded 100644 --- a/src/test/PracticeOne/FindMaxNumberTest.java +++ b/src/test/practice_one/FindMaxNumberTest.java @@ -1,6 +1,6 @@ -package test.PracticeOne; +package test.practice_one; -import practiceOne.FindMaxNumber; +import practice_one.FindMaxNumber; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/PracticeOne/FirstOddNumberTest.java b/src/test/practice_one/FirstOddNumberTest.java similarity index 86% rename from src/test/PracticeOne/FirstOddNumberTest.java rename to src/test/practice_one/FirstOddNumberTest.java index 9cafa88..de73d39 100644 --- a/src/test/PracticeOne/FirstOddNumberTest.java +++ b/src/test/practice_one/FirstOddNumberTest.java @@ -1,6 +1,6 @@ -package test.PracticeOne; +package test.practice_one; -import practiceOne.FirstOddNumber; +import practice_one.FirstOddNumber; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/PracticeOne/JoinCharactersTest.java b/src/test/practice_one/JoinCharactersTest.java similarity index 92% rename from src/test/PracticeOne/JoinCharactersTest.java rename to src/test/practice_one/JoinCharactersTest.java index 385747a..12d75c0 100644 --- a/src/test/PracticeOne/JoinCharactersTest.java +++ b/src/test/practice_one/JoinCharactersTest.java @@ -1,6 +1,6 @@ -package test.PracticeOne; +package test.practice_one; -import practiceOne.JoinCharacters; +import practice_one.JoinCharacters; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/PracticeOne/MatrixSnakeTraversalTest.java b/src/test/practice_one/MatrixSnakeTraversalTest.java similarity index 85% rename from src/test/PracticeOne/MatrixSnakeTraversalTest.java rename to src/test/practice_one/MatrixSnakeTraversalTest.java index 3df0332..e8fc501 100644 --- a/src/test/PracticeOne/MatrixSnakeTraversalTest.java +++ b/src/test/practice_one/MatrixSnakeTraversalTest.java @@ -1,11 +1,9 @@ -package test.PracticeOne; +package test.practice_one; -import practiceOne.MatrixSnakeTraversal; +import practice_one.MatrixSnakeTraversal; import org.junit.Assert; import org.junit.Test; -import java.util.Arrays; - public class MatrixSnakeTraversalTest { diff --git a/src/test/PracticeOne/MatrixTraversalTest.java b/src/test/practice_one/MatrixTraversalTest.java similarity index 93% rename from src/test/PracticeOne/MatrixTraversalTest.java rename to src/test/practice_one/MatrixTraversalTest.java index 93d525a..e94950f 100644 --- a/src/test/PracticeOne/MatrixTraversalTest.java +++ b/src/test/practice_one/MatrixTraversalTest.java @@ -1,4 +1,4 @@ -package test.PracticeOne; +package test.practice_one; /*Обійти матрицю по спіралі і записати всі числа в одмірний масив. Для матриці [[1, 2, 3, 4], @@ -10,7 +10,7 @@ import org.junit.Assert; import org.junit.Test; -import practiceOne.MatrixTraversal; +import practice_one.MatrixTraversal; public class MatrixTraversalTest { diff --git a/src/test/PracticeOne/SumDigitsTest.java b/src/test/practice_one/SumDigitsTest.java similarity index 88% rename from src/test/PracticeOne/SumDigitsTest.java rename to src/test/practice_one/SumDigitsTest.java index 12c1250..d0fe01c 100644 --- a/src/test/PracticeOne/SumDigitsTest.java +++ b/src/test/practice_one/SumDigitsTest.java @@ -1,6 +1,6 @@ -package test.PracticeOne; +package test.practice_one; -import practiceOne.SumDigits; +import practice_one.SumDigits; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/practice_three/BinaryHeap.java b/src/test/practice_three/BinaryHeap.java new file mode 100644 index 0000000..a088074 --- /dev/null +++ b/src/test/practice_three/BinaryHeap.java @@ -0,0 +1,145 @@ +package test.practice_three; +import java.util.Arrays; +/** + Реалізуйте структуру даних - Бінарна Купа (Binary Heap). + Конструктор проймає один параметр size. + Методи insert(int) що працює за O(logN) і poll(), + який видаляє і повертає максимальне число з купи і також працює за O(logN). + */ +public class BinaryHeap { + private int[] heap; + private int heapSize; + + public BinaryHeap(int size){ + heap = new int[size]; + heapSize = 0; + Arrays.fill(heap, -1); + } + + public int insert(int val){ + int tmp; + int insertPoint = heapSize; + + if(this.isFull() || val < 0){ + throw new HeapException(); + } + + heap[heapSize] = val; + + for(int i = getHeapSize(); getParent(i) >= 0; i = insertPoint) { + if (val < heap[getParent(i)]) { + tmp = heap[getParent(i)]; + heap[getParent(i)] = heap[i]; + heap[i] = tmp; + insertPoint = getParent(i); + }else if(val == heap[getParent(i)]){ + throw new HeapException(); + } + else{ + insertPoint = i; + break; + } + } + heapSize++; + return insertPoint; + } + + public int poll(){ + if(this.isEmpty()){ + throw new HeapException(); + } + int result = heap[0]; + int key = heap[heapSize - 1]; + int tmp; + int insertPoint; + + heap[0] = key; + heap[heapSize - 1] = -1; + heapSize--; + + for(int i = 0; i < this.getHeapSize() - 1; i = insertPoint){ + if(key > getLeftChild(key)){ + tmp = getLeftChild(key); + heap[i] = tmp; + heap[2 * i + 1] = key; + insertPoint = 2 * i + 1; + }else if(key > getRightChild(key)){ + tmp = getRightChild(key); + heap[i] = tmp; + heap[2 * i + 2] = key; + insertPoint = 2 * i + 2; + }else{ + break; + } + } + + return result; + } + + public int peek(){ + if(this.isEmpty()){ + throw new HeapException(); + } + return heap[0]; + } + + public boolean contains(int key){ + for(int i = 0; i < this.heapSize; i++){ + if(heap[i] == key){ + return true; + } + } + return false; + } + + public boolean isEmpty(){ + if(this.heapSize == 0){ + return true; + } + return false; + } + + public boolean isFull(){ + if(this.heapSize == heap.length){ + return true; + } + return false; + } + + public int getParent(int key){ + int parent = -1; + if(key > 0){ + parent = (key - 1) / 2; + } + return parent; + } + + public int getLeftChild(int key){ + for(int i = 0; (2 * i + 1) < this.heapSize; i++){ + if(heap[i] == key){ + return heap[2 * i + 1]; + } + } + return -1; + } + + public int getRightChild(int key){ + for(int i = 0; (2 * i + 2) < this.heapSize; i++){ + if(heap[i] == key){ + return heap[2 * i + 2]; + } + } + return -1; + } + + public int getHeapSize(){ + return this.heapSize; + } + + public int[] getHeap(){ + return this.heap; + } +} + +class HeapException extends RuntimeException{ +} \ No newline at end of file diff --git a/src/test/practice_three/ReversePolishNotationTest.java b/src/test/practice_three/ReversePolishNotationTest.java new file mode 100644 index 0000000..8080a2f --- /dev/null +++ b/src/test/practice_three/ReversePolishNotationTest.java @@ -0,0 +1,18 @@ +package test.practice_three; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + *Дано арифметичний вираз у вигляді Польського Інверсного запису. + Необхідно обчислити значення виразу і повернути його. + Вираз складається лише з цілих чисел і операцій +, -, *, /. Гарантується, що результат також ціне число. + */ +public class ReversePolishNotationTest { + + @Test + public void testEvaluate() throws Exception { + + } +} \ No newline at end of file diff --git a/src/test/practice_two/AbcNumberTest.java b/src/test/practice_two/AbcNumberTest.java new file mode 100644 index 0000000..ca0ff18 --- /dev/null +++ b/src/test/practice_two/AbcNumberTest.java @@ -0,0 +1,23 @@ +package test.practice_two; + +import org.junit.Assert; +import org.junit.Test; +import practice_two.AbcNumber; + +/** + Дано рядок отриманий шляхом заміни цифр 0,1,2,...,9 певного числа на букви a,b,c,..,j. + Необхідно повернути початкове число маючи конвертований рядок. + Наприклад: + Для "bcd" повернути 123 + */ +public class AbcNumberTest { + + @Test + public void testConvert() throws Exception { + String input = "d"; + int expected = 123; + AbcNumber change = new AbcNumber(); + int extualResult = change.convert(input); + Assert.assertEquals(expected, extualResult); + } +} \ No newline at end of file diff --git a/src/test/practice_two/AddBinaryTest.java b/src/test/practice_two/AddBinaryTest.java new file mode 100644 index 0000000..7fa119b --- /dev/null +++ b/src/test/practice_two/AddBinaryTest.java @@ -0,0 +1,32 @@ +package test.practice_two; + +import org.junit.Assert; +import org.junit.Test; +import practice_two.AddBinary; + +/** + * Додайте два беззнакових числа, що передаються як рядки. + * "101" + "100" = "1001" + */ +public class AddBinaryTest { + @Test + public void AddBinary() throws Exception { + String inputA = "101"; + String inputB = "100"; + String expected = "1001"; + AddBinary addBinary = new AddBinary(); + String extualResult = addBinary.add(inputA, inputB); + Assert.assertEquals(expected, extualResult); + } + + @Test + public void AddBinaryLong() throws Exception { + String inputA = "10000000000000000000000000000000"; + String inputB = "10000000000000000000000000000000"; + String expected = "100000000000000000000000000000000"; + AddBinary addBinary = new AddBinary(); + String extualResult = addBinary.add(inputA, inputB); + Assert.assertEquals(expected, extualResult); + } + +} \ No newline at end of file diff --git a/src/test/practice_two/AddNumberBase36Test.java b/src/test/practice_two/AddNumberBase36Test.java new file mode 100644 index 0000000..5290113 --- /dev/null +++ b/src/test/practice_two/AddNumberBase36Test.java @@ -0,0 +1,19 @@ +package test.practice_two; + +import org.junit.Test; + +/** + * Дано 2 числа в системі числення з основою 36. Будь-яка цифра може бути в межах [0-9a-z]. + * Повернути суму чисел, також в системі 36. + * Наприклад: + * "9" + "1" = "a" + * "z" + "1" = "10" + */ +public class AddNumberBase36Test { + + @Test + public void testAdd() throws Exception { + + + } +} \ No newline at end of file diff --git a/src/test/PracticeTwo/AverageNumberTest.java b/src/test/practice_two/AverageNumberTest.java similarity index 86% rename from src/test/PracticeTwo/AverageNumberTest.java rename to src/test/practice_two/AverageNumberTest.java index 4894cb9..aa3ac57 100644 --- a/src/test/PracticeTwo/AverageNumberTest.java +++ b/src/test/practice_two/AverageNumberTest.java @@ -1,10 +1,8 @@ -package test.PracticeTwo; +package test.practice_two; import org.junit.Assert; import org.junit.Test; -import practiceTwo.AverageNumber; - -import static org.junit.Assert.*; +import practice_two.AverageNumber; /** Знайти середнє значення двох цілих чисел. diff --git a/src/test/PracticeTwo/PositiveAverageNumberTest.java b/src/test/practice_two/PositiveAverageNumberTest.java similarity index 85% rename from src/test/PracticeTwo/PositiveAverageNumberTest.java rename to src/test/practice_two/PositiveAverageNumberTest.java index 0abb3f0..f2cc05f 100644 --- a/src/test/PracticeTwo/PositiveAverageNumberTest.java +++ b/src/test/practice_two/PositiveAverageNumberTest.java @@ -1,10 +1,8 @@ -package test.PracticeTwo; +package test.practice_two; import org.junit.Assert; import org.junit.Test; -import practiceTwo.PositiveAverageNumber; - -import static org.junit.Assert.*; +import practice_two.PositiveAverageNumber; /** Знайти середнє арифметике двух додатніх чисел. diff --git a/src/test/practice_two/SetZeroTest.java b/src/test/practice_two/SetZeroTest.java new file mode 100644 index 0000000..de08118 --- /dev/null +++ b/src/test/practice_two/SetZeroTest.java @@ -0,0 +1,24 @@ +package test.practice_two; + +import org.junit.Assert; +import org.junit.Test; +import practice_two.SetZero; + +/** + Дано число. Треба замінити i-й біт замінити на нуль. + Наприклад: + для числа 6 в бінарному вигляді 110, + замінивши 2-й біт на нуль отримаємо 100 тобто 4. + 1<= i <= 32 + */ +public class SetZeroTest { + @Test + public void set() throws Exception { + int inputA = 6; + int inputB = 2; + int expected = 4; + SetZero change = new SetZero(); + int extualResult = change.set(inputA, inputB); + Assert.assertEquals(expected, extualResult); + } +} \ No newline at end of file From ef168960519edd172e9870a159c229954b902261 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 28 May 2016 16:45:11 +0300 Subject: [PATCH 27/32] modul 2_2 (Generics) --- src/module2_2/DoubleTask.java | 31 +++++++++ src/module2_2/Executor.java | 28 +++++++++ src/module2_2/ExecutorImpl.java | 94 ++++++++++++++++++++++++++++ src/module2_2/GenericsTestDrive.java | 31 +++++++++ src/module2_2/IntegerTask.java | 25 ++++++++ src/module2_2/LongTask.java | 26 ++++++++ src/module2_2/NumberValidator.java | 9 +++ src/module2_2/Task.java | 13 ++++ src/module2_2/Validator.java | 6 ++ 9 files changed, 263 insertions(+) create mode 100644 src/module2_2/DoubleTask.java create mode 100644 src/module2_2/Executor.java create mode 100644 src/module2_2/ExecutorImpl.java create mode 100644 src/module2_2/GenericsTestDrive.java create mode 100644 src/module2_2/IntegerTask.java create mode 100644 src/module2_2/LongTask.java create mode 100644 src/module2_2/NumberValidator.java create mode 100644 src/module2_2/Task.java create mode 100644 src/module2_2/Validator.java diff --git a/src/module2_2/DoubleTask.java b/src/module2_2/DoubleTask.java new file mode 100644 index 0000000..7ca3ddf --- /dev/null +++ b/src/module2_2/DoubleTask.java @@ -0,0 +1,31 @@ +package module2_2; + +public class DoubleTask implements Task { + private Double value; + private Double result; + + public DoubleTask(Double value) { + this.value = value; + } + + @Override + public void execute() { + String s = value.toString(); + int lastNumberAfterPoint = s.charAt(s.length() - 1) - '0'; + if (lastNumberAfterPoint % 2 == 1) { + result = 1.0; + } else { + result = 0.0; + } + } + + @Override + public Double getResult() { + return result; + } + + @Override + public Double getValue() { + return value; + } +} \ No newline at end of file diff --git a/src/module2_2/Executor.java b/src/module2_2/Executor.java new file mode 100644 index 0000000..d084c49 --- /dev/null +++ b/src/module2_2/Executor.java @@ -0,0 +1,28 @@ +package module2_2; + +import java.util.List; + +public interface Executor { + + // Добавить таск на выполнение. Результат таска будет доступен через метод getValidResults(). + // Бросает Эксепшн если уже был вызван метод execute() + void addTask(Task task); + + // Добавить таск на выполнение и валидатор результата. Результат таска будет записан в ValidResults если validator.isValid вернет true для этого результата + // Результат таска будет записан в InvalidResults если validator.isValid вернет false для этого результата + // Бросает Эксепшн если уже был вызван метод execute() + void addTask(Task task, Validator validator); //предполагалось использовать в валидаторе + //но мое мнение - это не принципиально. + + // Выполнить все добавленые таски + void execute(); + + // Получить валидные результаты. Бросает Эксепшн если не был вызван метод execute() + List getValidResults(); + + // Получить невалидные результаты. Бросает Эксепшн если не был вызван метод execute() + List getInvalidResults(); + + // Только для теста + List> getTasks(); +} \ No newline at end of file diff --git a/src/module2_2/ExecutorImpl.java b/src/module2_2/ExecutorImpl.java new file mode 100644 index 0000000..f9ff37b --- /dev/null +++ b/src/module2_2/ExecutorImpl.java @@ -0,0 +1,94 @@ +package module2_2; + +import java.util.ArrayList; +import java.util.List; + +public class ExecutorImpl implements Executor { + private List> tasks; + + private ArrayList validResults; + private ArrayList invalidResults; + + boolean isExecuteActivate; + + { + tasks = new ArrayList<>(); + validResults = new ArrayList<>(); + invalidResults = new ArrayList<>(); + } + + @Override + public void addTask(Task task) { + try { + if (isExecuteActivate) { + throw new Exception("[ERROR]: Method execute() was activated!"); + } + tasks.add(task); + } catch (Exception exception) { + exception.getMessage(); + } + } + + @Override + public void addTask(Task task, Validator validator) { + try { + if (isExecuteActivate) { + throw new Exception("[ERROR]: Method execute() was activated!"); + } + task.execute(); + if (validator.isValid(task.getResult())) { + validResults.add(task.getValue()); + } else { + invalidResults.add(task.getValue()); + } + } catch (Exception exception) { + exception.getMessage(); + } + } + + @Override + public void execute() { + Validator validator = new NumberValidator(); + for (Task task : tasks) { + task.execute(); + if (validator.isValid((Number) task.getResult())) { + validResults.add(task.getValue()); + } else { + invalidResults.add(task.getValue()); + } + } + isExecuteActivate = true; + } + + @Override + public List getValidResults() { + try { + if (isExecuteActivate) { + return validResults; + } else { + throw new Exception("[ERROR]: Method execute() does not activate!"); + } + } catch (Exception exception) { + exception.getMessage(); + } + return null; + } + + @Override + public List getInvalidResults() { + try { + if (isExecuteActivate) { + return invalidResults; + } else { + throw new Exception("[ERROR]: Method execute() does not activate!"); + } + } catch (Exception exception) { + exception.getMessage(); + } + return null; + } + + public List> getTasks() { + return tasks; + } +} \ No newline at end of file diff --git a/src/module2_2/GenericsTestDrive.java b/src/module2_2/GenericsTestDrive.java new file mode 100644 index 0000000..271a4f0 --- /dev/null +++ b/src/module2_2/GenericsTestDrive.java @@ -0,0 +1,31 @@ +package module2_2; + +public class GenericsTestDrive { + public static void main(String[] args) { + Task[] intTasks = new IntegerTask[5]; + intTasks[0] = new IntegerTask(25); + intTasks[1] = new IntegerTask(32); + intTasks[2] = new IntegerTask(47); + intTasks[3] = new IntegerTask(19); + intTasks[4] = new IntegerTask(48); + + Executor numberExecutor = new ExecutorImpl<>(); + + for (Task intTask : intTasks) { + numberExecutor.addTask(intTask); + } + numberExecutor.addTask(new LongTask(10L), new NumberValidator()); + numberExecutor.addTask(new DoubleTask(39.2389)); // if number after point % 2 == 0 than doubleNumber is ValidResult + + numberExecutor.execute(); + + System.out.println("Valid results:"); + for (Number number : numberExecutor.getValidResults()) { + System.out.println(number); + } + System.out.println("Invalid results:"); + for (Number number : numberExecutor.getInvalidResults()) { + System.out.println(number); + } + } +} \ No newline at end of file diff --git a/src/module2_2/IntegerTask.java b/src/module2_2/IntegerTask.java new file mode 100644 index 0000000..62161d4 --- /dev/null +++ b/src/module2_2/IntegerTask.java @@ -0,0 +1,25 @@ +package module2_2; + +public class IntegerTask implements Task { + private Integer value; + private Integer result; + + public IntegerTask(Integer value) { + this.value = value; + } + + @Override + public void execute() { + result = value % 2; + } + + @Override + public Integer getResult() { + return result; + } + + @Override + public Integer getValue() { + return value; + } +} \ No newline at end of file diff --git a/src/module2_2/LongTask.java b/src/module2_2/LongTask.java new file mode 100644 index 0000000..05f58c2 --- /dev/null +++ b/src/module2_2/LongTask.java @@ -0,0 +1,26 @@ +package module2_2; + +public class LongTask implements Task { + private Long value; + private Long result; + + public LongTask(Long value) { + this.value = value; + } + + @Override + public void execute() { + result = value % 2; + } + + @Override + public Long getResult() { + return result; + } + + @Override + public Long getValue() { + return value; + } + +} \ No newline at end of file diff --git a/src/module2_2/NumberValidator.java b/src/module2_2/NumberValidator.java new file mode 100644 index 0000000..6229bc2 --- /dev/null +++ b/src/module2_2/NumberValidator.java @@ -0,0 +1,9 @@ +package module2_2; + + +public class NumberValidator implements Validator { + @Override + public boolean isValid(Number result) { + return result.intValue() <= 0; + } +} \ No newline at end of file diff --git a/src/module2_2/Task.java b/src/module2_2/Task.java new file mode 100644 index 0000000..a21401a --- /dev/null +++ b/src/module2_2/Task.java @@ -0,0 +1,13 @@ +package module2_2; + + +public interface Task { + + // Метода запускает таск на выполнение + void execute(); + + // Возвращает результат выполнения + T getResult(); + + T getValue(); +} \ No newline at end of file diff --git a/src/module2_2/Validator.java b/src/module2_2/Validator.java new file mode 100644 index 0000000..98aaa3b --- /dev/null +++ b/src/module2_2/Validator.java @@ -0,0 +1,6 @@ +package module2_2; + +public interface Validator { + // Валидирует переданое значение + boolean isValid(T result); +} \ No newline at end of file From b0779b0a04e8352375be724bddcfb9a7e90ba142 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sun, 5 Jun 2016 19:15:31 +0300 Subject: [PATCH 28/32] my work --- result.txt | 38 ++++ .../ArrayListToSimpleArrayPage583.java | 24 +++ .../SaveDataCollectionsPage600.java | 43 ++++ .../UseArrayDequePage590.java | 23 +++ .../UseArrayListPage581.java | 25 +++ .../UseForEachPage595.java | 24 +++ .../UseHashSetPage586.java | 19 ++ .../UseIteratorPage594.java | 48 +++++ .../UseLinkedHashSetPage587.java | 18 ++ .../UseLinkedListPage584.java | 35 ++++ src/CollectionFramework/UseSpliterator.java | 30 +++ .../UseTreeMapPage611.java | 30 +++ .../UseTreeSetPage588.java | 22 ++ .../use_Comparator/CompDemo.java | 20 ++ .../use_Comparator/MyComp.java | 15 ++ .../use_Comparator/UseLiambda.java | 15 ++ src/fff/IOUtil.java | 26 +++ src/fff/ListTester.java | 188 ++++++++++++++++++ src/fff/Runner.java | 13 ++ src/fff/SetTester.java | 100 ++++++++++ src/fff/TableConstructionAndFormatting.java | 85 ++++++++ src/module1_1/Performance.java | 159 --------------- src/module2_1/ArrayListMeasurements.java | 85 ++++++++ src/module2_1/HashSetMeasurements.java | 67 +++++++ src/module2_1/LinkedListMeasurements.java | 87 ++++++++ src/module2_1/MainFirstEEmodule.java | 73 +++++++ src/module2_1/Print.java | 79 ++++++++ src/module2_1/TreeSetMeasurements.java | 69 +++++++ src/module2_3_1/MySemaphore.java | 91 +++++++++ src/module2_3_1/Semaphore.java | 25 +++ src/module2_3_1/SemaphoreTestDrive.java | 36 ++++ src/practice_four/WordNumber.java | 16 ++ .../LongestStabilityPeriod.java | 42 ++++ .../LongestStabilityPeriodTest.java | 21 ++ 34 files changed, 1532 insertions(+), 159 deletions(-) create mode 100644 result.txt create mode 100644 src/CollectionFramework/ArrayListToSimpleArrayPage583.java create mode 100644 src/CollectionFramework/SaveDataCollectionsPage600.java create mode 100644 src/CollectionFramework/UseArrayDequePage590.java create mode 100644 src/CollectionFramework/UseArrayListPage581.java create mode 100644 src/CollectionFramework/UseForEachPage595.java create mode 100644 src/CollectionFramework/UseHashSetPage586.java create mode 100644 src/CollectionFramework/UseIteratorPage594.java create mode 100644 src/CollectionFramework/UseLinkedHashSetPage587.java create mode 100644 src/CollectionFramework/UseLinkedListPage584.java create mode 100644 src/CollectionFramework/UseSpliterator.java create mode 100644 src/CollectionFramework/UseTreeMapPage611.java create mode 100644 src/CollectionFramework/UseTreeSetPage588.java create mode 100644 src/CollectionFramework/use_Comparator/CompDemo.java create mode 100644 src/CollectionFramework/use_Comparator/MyComp.java create mode 100644 src/CollectionFramework/use_Comparator/UseLiambda.java create mode 100644 src/fff/IOUtil.java create mode 100644 src/fff/ListTester.java create mode 100644 src/fff/Runner.java create mode 100644 src/fff/SetTester.java create mode 100644 src/fff/TableConstructionAndFormatting.java delete mode 100644 src/module1_1/Performance.java create mode 100644 src/module2_1/ArrayListMeasurements.java create mode 100644 src/module2_1/HashSetMeasurements.java create mode 100644 src/module2_1/LinkedListMeasurements.java create mode 100644 src/module2_1/MainFirstEEmodule.java create mode 100644 src/module2_1/Print.java create mode 100644 src/module2_1/TreeSetMeasurements.java create mode 100644 src/module2_3_1/MySemaphore.java create mode 100644 src/module2_3_1/Semaphore.java create mode 100644 src/module2_3_1/SemaphoreTestDrive.java create mode 100644 src/practice_four/WordNumber.java create mode 100644 src/practice_three/LongestStabilityPeriod.java create mode 100644 src/test/practice_three/LongestStabilityPeriodTest.java diff --git a/result.txt b/result.txt new file mode 100644 index 0000000..dc1e146 --- /dev/null +++ b/result.txt @@ -0,0 +1,38 @@ ++-----------------------------------------------------------------------------------------------+ +| add get remove contains populate iter.add iter.remove | ++-----------------------------------------------------------------------------------------------+ +| ArrayList: 2 3 824 16267 16267 18128 19926 | +| LinkedList: 2 5404 10608 25711 455593 455614 455622 | +| TreeSet: 1 2 3 4 | +| HashSet: 1 5 6 6 | ++-----------------------------------------------------------------------------------------------+ +Collection type add get remove contains populate iterator.add iterator.remove + (Results for 10K elements in the collection) + +ArrayList 15042 2418 18237 273202 658710 25760 550263 +LinkedList 36943 23605 24154 214500 984790 4810 72186 +HashSet 468 n/a 6403 2922 1454461 n/a n/a +TreeSet 1209 n/a 19946 5381 8354638 n/a n/a + + + +Collection type add get remove contains populate iterator.add iterator.remove + (Results for 10K elements in the collection) + +ArrayList 25417 3641 22271 320118 860128 25961 783609 +LinkedList 43315 21548 23841 530790 1873334 6747 108562 +HashSet 1066 n/a 10553 5421 2403901 n/a n/a +TreeSet 2436 n/a 28746 17161 7957590 n/a n/a + + + +Collection type add get remove contains populate iterator.add iterator.remove + (Results for 100K elements in the collection) + +ArrayList 114617 3873 204991 3097672 9024633 268967 36143716 +LinkedList 367360 376632 441848 2209695 34071427 5113 264492 +HashSet 1008 n/a 6309 3355 33759376 n/a n/a +TreeSet 2008 n/a 26157 3748 160855050 n/a n/a + + + diff --git a/src/CollectionFramework/ArrayListToSimpleArrayPage583.java b/src/CollectionFramework/ArrayListToSimpleArrayPage583.java new file mode 100644 index 0000000..e26eb7a --- /dev/null +++ b/src/CollectionFramework/ArrayListToSimpleArrayPage583.java @@ -0,0 +1,24 @@ +package CollectionFramework; + +import java.util.ArrayList; + +public class ArrayListToSimpleArrayPage583 { + public static void main(String[] args) { + ArrayList arrayList = new ArrayList<>(); + + for (int i = 1; i < 5; i++) { + arrayList.add(i); + } + + System.out.println("Содержимое списка массива: " + arrayList); + + Integer[] simpleArray = new Integer[arrayList.size()]; + simpleArray = arrayList.toArray(simpleArray); + + int sum = 0; + + for (int i : simpleArray) sum += i; + System.out.println("Сумма: " + sum); + } +} + diff --git a/src/CollectionFramework/SaveDataCollectionsPage600.java b/src/CollectionFramework/SaveDataCollectionsPage600.java new file mode 100644 index 0000000..be9704f --- /dev/null +++ b/src/CollectionFramework/SaveDataCollectionsPage600.java @@ -0,0 +1,43 @@ +package CollectionFramework; + +import java.util.LinkedList; + +public class SaveDataCollectionsPage600 { + public static void main(String[] args) { + LinkedList
addresses = new LinkedList<>(); + addresses.add(new Address("J.W West", "11 Oak Ave", "Urbana", "1L", "61801")); + addresses.add(new Address("P.D East", "12 Oak Ave", "Urbana", "9L", "61966")); + addresses.add(new Address("O.K South", "13 Oak Ave", "Urbana", "6L", "77777")); + + for (Address element : addresses) { + System.out.print(element + "\n"); + } + } +} + +class Address { + private String name; + private String street; + private String city; + private String state; + private String code; + + public Address(String name, String street, String city, String state, String code) { + this.name = name; + this.street = street; + this.city = city; + this.state = state; + this.code = code; + } + + @Override + public String toString() { + return "Address{" + + "name='" + name + '\'' + + ", street='" + street + '\'' + + ", city='" + city + '\'' + + ", state='" + state + '\'' + + ", code='" + code + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/CollectionFramework/UseArrayDequePage590.java b/src/CollectionFramework/UseArrayDequePage590.java new file mode 100644 index 0000000..5fb78dc --- /dev/null +++ b/src/CollectionFramework/UseArrayDequePage590.java @@ -0,0 +1,23 @@ +package CollectionFramework; + +import java.util.ArrayDeque; + +public class UseArrayDequePage590 { + public static void main(String[] args) { + ArrayDeque arrayDeque = new ArrayDeque<>(); + + arrayDeque.push("A"); + arrayDeque.push("B"); + arrayDeque.push("D"); + arrayDeque.push("E"); + arrayDeque.push("F"); + + System.out.println("Извлечение из стека: "); +//выводится по умолчанию начиная с последнего эллемента + while (arrayDeque.peek() != null) { + System.out.print(arrayDeque.pop() + " "); + + System.out.println(); + } + } +} diff --git a/src/CollectionFramework/UseArrayListPage581.java b/src/CollectionFramework/UseArrayListPage581.java new file mode 100644 index 0000000..849496d --- /dev/null +++ b/src/CollectionFramework/UseArrayListPage581.java @@ -0,0 +1,25 @@ +package CollectionFramework; + + +import java.util.ArrayList; + +public class UseArrayListPage581 { + public static void main(String[] args) { + + ArrayList arrayList = new ArrayList<>(); + System.out.println("Начальный размер списочного массива arrayList: " + arrayList.size()); + arrayList.add("C"); + arrayList.add("A"); + arrayList.add("E"); + arrayList.add("B"); + arrayList.add("D"); + arrayList.add("F"); + arrayList.add(1, "A2"); + System.out.println("Содержимое списочного массива: " + arrayList); + arrayList.remove("F"); + arrayList.remove(2); + System.out.println("Размер списочного массива arrayList после удаления элементов: " + arrayList.size()); + System.out.println("Содержимое списочного массива: " + arrayList); + + } +} diff --git a/src/CollectionFramework/UseForEachPage595.java b/src/CollectionFramework/UseForEachPage595.java new file mode 100644 index 0000000..d60656c --- /dev/null +++ b/src/CollectionFramework/UseForEachPage595.java @@ -0,0 +1,24 @@ +package CollectionFramework; + +import java.util.ArrayList; + +public class UseForEachPage595 { + public static void main(String[] args) { + ArrayList arrayList = new ArrayList<>(); + + for (int i = 1; i < 6; i++) { + arrayList.add(i); + } + //вывод содержимого коллекции + for (int value : arrayList) { + System.out.print(value + " "); + } + System.out.println(); + //сумирование чисел + int sum = 0; + for (int value : arrayList) { + sum+= value; + } + System.out.println(sum); + } +} diff --git a/src/CollectionFramework/UseHashSetPage586.java b/src/CollectionFramework/UseHashSetPage586.java new file mode 100644 index 0000000..859d6a8 --- /dev/null +++ b/src/CollectionFramework/UseHashSetPage586.java @@ -0,0 +1,19 @@ +package CollectionFramework; + +import java.util.HashSet; + +public class UseHashSetPage586 { + public static void main(String[] args) { + HashSet hashSet = new HashSet<>(); + hashSet.add("Бета"); + hashSet.add("Альфа"); + hashSet.add("Эта"); + hashSet.add("Гамма"); + hashSet.add("Эпсилон"); + hashSet.add("Омега"); + + //порядок вызова эллементов может варироваться + System.out.println(hashSet); + + } +} diff --git a/src/CollectionFramework/UseIteratorPage594.java b/src/CollectionFramework/UseIteratorPage594.java new file mode 100644 index 0000000..ca51215 --- /dev/null +++ b/src/CollectionFramework/UseIteratorPage594.java @@ -0,0 +1,48 @@ +package CollectionFramework; + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.ListIterator; + +public class UseIteratorPage594 { + public static void main(String[] args) { + AbstractList arrayList = new ArrayList<>(); + arrayList.add("C"); + arrayList.add("A"); + arrayList.add("E"); + arrayList.add("B"); + arrayList.add("D"); + arrayList.add("F"); + + System.out.print("Исходное содержимое списочного массива: "); + Iterator listIterator = arrayList.listIterator(); + while (listIterator.hasNext()) { + String element = listIterator.next(); + System.out.print(element + " "); + } + System.out.println(); + + + //видоизменить перебираемые эллементы + ListIterator stringListIterator = arrayList.listIterator(); + while (stringListIterator.hasNext()) { + String element = stringListIterator.next(); + System.out.print(element + "+"); + } + System.out.println(); + + while (listIterator.hasNext()) { + String element = listIterator.next(); + System.out.print(element + " "); + } + System.out.println(); + //отобразить список в обратном порядке + System.out.print("Изменить содержимое списочного массива в обратном порядке: "); + while (stringListIterator.hasPrevious()) { + String element = stringListIterator.previous(); + System.out.print(element + " "); + } + System.out.println(); + } +} diff --git a/src/CollectionFramework/UseLinkedHashSetPage587.java b/src/CollectionFramework/UseLinkedHashSetPage587.java new file mode 100644 index 0000000..43beb01 --- /dev/null +++ b/src/CollectionFramework/UseLinkedHashSetPage587.java @@ -0,0 +1,18 @@ +package CollectionFramework; + +import java.util.LinkedHashSet; + +public class UseLinkedHashSetPage587 { + public static void main(String[] args) { + LinkedHashSet hashSet = new LinkedHashSet<>(); + hashSet.add("Бета"); + hashSet.add("Альфа"); + hashSet.add("Эта"); + hashSet.add("Гамма"); + hashSet.add("Эпсилон"); + hashSet.add("Омега"); + + //В отличие от HashSet порядок эллементов отображается так как был введен + System.out.println(hashSet); + } +} diff --git a/src/CollectionFramework/UseLinkedListPage584.java b/src/CollectionFramework/UseLinkedListPage584.java new file mode 100644 index 0000000..52c4913 --- /dev/null +++ b/src/CollectionFramework/UseLinkedListPage584.java @@ -0,0 +1,35 @@ +package CollectionFramework; + +import java.util.LinkedList; + +public class UseLinkedListPage584 { + public static void main(String[] args) { + LinkedList linkedList = new LinkedList<>(); + + linkedList.add("F"); + linkedList.add("B"); + linkedList.add("D"); + linkedList.add("E"); + linkedList.add("C"); + linkedList.addLast("Z"); + linkedList.addFirst("A"); + linkedList.add(1, "A2"); + + System.out.println("Исходное содержимое связаного списка: " + linkedList); + + linkedList.remove("F"); + linkedList.remove(2); + + System.out.println("Содержимое спска после удалления элементов: " + linkedList); + + linkedList.removeFirst(); + linkedList.removeLast(); + + System.out.println("Содержимое спска после удалления первого и последнего элементов: " + linkedList); + + String val = linkedList.get(2); + linkedList.set(2, val + " изменено"); + + System.out.println("Содержимое списка после изменения: " + linkedList); + } +} diff --git a/src/CollectionFramework/UseSpliterator.java b/src/CollectionFramework/UseSpliterator.java new file mode 100644 index 0000000..eb40634 --- /dev/null +++ b/src/CollectionFramework/UseSpliterator.java @@ -0,0 +1,30 @@ +package CollectionFramework; + +import java.util.ArrayList; +import java.util.Spliterator; + +public class UseSpliterator { + public static void main(String[] args) { + ArrayList arrayList = new ArrayList<>(); + arrayList.add(1.0); + arrayList.add(2.0); + arrayList.add(3.0); + arrayList.add(4.0); + arrayList.add(5.0); + + //вызов метода tryAdvance для вывода содержимого списосчного массива + Spliterator spliterator = arrayList.spliterator(); + while (spliterator.tryAdvance((n) -> System.out.println(n))) ; + System.out.println(); + + //создать новый списочный массив содержащий квадратные корни числовых значений из arrayList + spliterator = arrayList.spliterator(); + ArrayList sqrt = new ArrayList<>(); + while (spliterator.tryAdvance((n) -> sqrt.add(Math.sqrt(n)))) ; + System.out.println(); + + //вызвать метод forEachRemaining для вывода содержимого списочного массива + spliterator = sqrt.spliterator(); + spliterator.forEachRemaining((n) -> System.out.println(n)); + } +} diff --git a/src/CollectionFramework/UseTreeMapPage611.java b/src/CollectionFramework/UseTreeMapPage611.java new file mode 100644 index 0000000..6b3be16 --- /dev/null +++ b/src/CollectionFramework/UseTreeMapPage611.java @@ -0,0 +1,30 @@ +package CollectionFramework; + +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +public class UseTreeMapPage611 { + public static void main(String[] args) { + TreeMap tm = new TreeMap<>(); + tm.put("Джон, Доу", new Double(3434.34)); + tm.put("Том, Смит", new Double(99.34)); + tm.put("Джейн, Бейкер", new Double(126.56)); + + //получить множество записей + Set> set = tm.entrySet(); + + //вывести множество + for (Map.Entry me : set) { + System.out.print(me.getKey() + ": "); + System.out.println(me.getValue()); + } + + System.out.println(); + + //внести сумму 1000 на счет Джона Доу + double balance = tm.get("Джон Доу"); + tm.put("Джон Доу", balance + 1000.00); + System.out.println("Новый остаток на счете Джона Доу: " + tm.get("Джон Доу")); + } +} diff --git a/src/CollectionFramework/UseTreeSetPage588.java b/src/CollectionFramework/UseTreeSetPage588.java new file mode 100644 index 0000000..4e43893 --- /dev/null +++ b/src/CollectionFramework/UseTreeSetPage588.java @@ -0,0 +1,22 @@ +package CollectionFramework; + +import java.util.TreeSet; + +public class UseTreeSetPage588 { + public static void main(String[] args) { + TreeSet treeSet = new TreeSet<>(); + + treeSet.add("D"); + treeSet.add("Z"); + treeSet.add("Y"); + treeSet.add("A"); + treeSet.add("W"); + treeSet.add("H"); + treeSet.add("О"); + //Сразу заполняеет и выводит в отсортированом виде. + System.out.println(treeSet); + + //можно выводить отдельное множество + System.out.println(treeSet.subSet("D", "Y")); + } +} diff --git a/src/CollectionFramework/use_Comparator/CompDemo.java b/src/CollectionFramework/use_Comparator/CompDemo.java new file mode 100644 index 0000000..9f53d25 --- /dev/null +++ b/src/CollectionFramework/use_Comparator/CompDemo.java @@ -0,0 +1,20 @@ +package CollectionFramework.use_Comparator; + +import java.util.TreeSet; + +public class CompDemo { + public static void main(String[] args) { + TreeSet treeSet = new TreeSet(new MyComp()); + treeSet.add("A"); + treeSet.add("Z"); + treeSet.add("X"); + treeSet.add("W"); + treeSet.add("K"); + treeSet.add("O"); + + for (String element : treeSet) { + System.out.print(element + " "); + System.out.println(); + } + } +} diff --git a/src/CollectionFramework/use_Comparator/MyComp.java b/src/CollectionFramework/use_Comparator/MyComp.java new file mode 100644 index 0000000..74a334a --- /dev/null +++ b/src/CollectionFramework/use_Comparator/MyComp.java @@ -0,0 +1,15 @@ +package CollectionFramework.use_Comparator; + +import java.util.Comparator; + +class MyComp implements Comparator { + @Override + public int compare(String a, String b) { + String aStr, bStr; + aStr = a; + bStr = b; + //выполнить сравнение в обратном порядке + return bStr.compareTo(aStr); + } +} + diff --git a/src/CollectionFramework/use_Comparator/UseLiambda.java b/src/CollectionFramework/use_Comparator/UseLiambda.java new file mode 100644 index 0000000..fd6d822 --- /dev/null +++ b/src/CollectionFramework/use_Comparator/UseLiambda.java @@ -0,0 +1,15 @@ +package CollectionFramework.use_Comparator; + +import java.util.TreeSet; + +public class UseLiambda { + public static void main(String[] args) { + MyComp aStr = new MyComp(); + MyComp bStr = new MyComp(); + + //передать компаратор с обратным упорядочением древовидному множеству TreeSet + + // TreeSet ts = new TreeSet(aStr, bStr) -> bStr.compareTo(aStr)); + + } +} diff --git a/src/fff/IOUtil.java b/src/fff/IOUtil.java new file mode 100644 index 0000000..c675515 --- /dev/null +++ b/src/fff/IOUtil.java @@ -0,0 +1,26 @@ +package fff; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; + + +public class IOUtil { + + public static void printToConsole (String[] data) { + + for (int i = 0; i < data.length; i++) { + System.out.print(data[i]); + } + } + + public static void saveToFile (String data[], String path ) throws IOException { + PrintWriter fileWriter = new PrintWriter(new FileWriter(path, true)); + + for (int i = 0; i < data.length; i++) { + fileWriter.print(data[i]); + } + + fileWriter.close(); + } +} diff --git a/src/fff/ListTester.java b/src/fff/ListTester.java new file mode 100644 index 0000000..a8a0ae0 --- /dev/null +++ b/src/fff/ListTester.java @@ -0,0 +1,188 @@ +package fff; +import java.util.List; +import java.util.ListIterator; +import java.util.Random; + +public class ListTester { + + public static long testAdd(List list, int elements, int repeats){ + long result; + long sum = 0; + Random randomGenerator = new Random(); + + for (int i = 0; i < elements; i++) { + list.add(i); + } + + for (int k = 0; k < repeats; k++) { + long start = System.nanoTime(); + + list.add(randomGenerator.nextInt(elements),randomGenerator.nextInt(elements)); + + long finish = System.nanoTime(); + long duration = finish - start; + sum +=duration; + } + list.clear(); + + result = sum / repeats; + return result; + } + + + public static long testGet(List list, int elements, int repeats) { + long result; + long sum = 0; + Random randomGenerator = new Random(); + + for (int i = 0; i < elements; i++) { + list.add(i); + } + + for (int k = 0; k < repeats; k++) { + + long start = System.nanoTime(); + + list.get(randomGenerator.nextInt(elements)); + + long finish = System.nanoTime(); + long duration = finish - start; + sum += duration; + } + list.clear(); + + result = sum / repeats; + return result; + } + + public static long testRemove(List list, int elements, int repeats) { + long result; + long sum = 0; + Random randomGenerator = new Random(); + + for (int i = 0; i < elements; i++) { + list.add(i); + } + + for (int k = 0; k < repeats; k++) { + long start = System.nanoTime(); + + list.remove(randomGenerator.nextInt(elements / 2)); + + long finish = System.nanoTime(); + long duration = finish - start; + sum += duration; + } + list.clear(); + + result = sum / repeats; + return result; + } + + public static long testContains(List list, int elements, int repeats) { + long result; + long sum = 0; + Random randomGenerator = new Random(); + + for (int i = 0; i < elements; i++) { + list.add(i); + } + + for (int k = 0; k < repeats; k++) { + long start = System.nanoTime(); + + list.contains(randomGenerator.nextInt(2 * elements)); + + long finish = System.nanoTime(); + long duration = finish - start; + sum += duration; + } + list.clear(); + + result = sum / repeats; + return result; + } + + public static long testPopulate(List list, int elements, int repeats) { + long result; + long sum = 0; + + for (int k = 0; k < repeats; k++) { + + long start = System.nanoTime(); + + for (int i = 0; i < elements; i++) { + list.add(i); + } + + long finish = System.nanoTime(); + long duration = finish - start; + sum += duration; + + list.clear(); + } + + result = sum / repeats; + return result; + } + + public static long testIteratorAdd(List list, int elements, int repeats) { + long result; + long sum = 0; + Random randomGenerator = new Random(); + + for (int i = 0; i < elements; i++) { + list.add(i); + } + + ListIterator iter = list.listIterator(); + + int k = 0; + while (iter.hasNext() && k < repeats) { + + long start = System.nanoTime(); + + iter.add(randomGenerator.nextInt(elements)); + iter.next(); + + long finish = System.nanoTime(); + long duration = finish - start; + sum += duration; + + k++; + } + list.clear(); + + result = sum / repeats; + return result; + } + + public static long testIteratorRemove(List list, int elements, int repeats) { + long result; + long sum = 0; + + + for (int i = 0; i < elements; i++) { + list.add(i); + } + + for (int k = 0; k < repeats; k++) { + ListIterator iter = list.listIterator(); + while (iter.hasNext() && k < repeats) { + + long start = System.nanoTime(); + + iter.next(); + iter.remove(); + + long finish = System.nanoTime(); + long duration = finish - start; + sum += duration; + } + } + list.clear(); + + result = sum / repeats; + return result; + } +} \ No newline at end of file diff --git a/src/fff/Runner.java b/src/fff/Runner.java new file mode 100644 index 0000000..4650577 --- /dev/null +++ b/src/fff/Runner.java @@ -0,0 +1,13 @@ +package fff; + +import java.io.File; +import java.io.IOException; + +public class Runner { + public static void main(String[] args) throws IOException { + + String[] PerformanceResults = TableConstructionAndFormatting.createAndFormateTable(); + IOUtil.printToConsole(PerformanceResults); + IOUtil.saveToFile(PerformanceResults, "result.txt"); + } +} diff --git a/src/fff/SetTester.java b/src/fff/SetTester.java new file mode 100644 index 0000000..a9e301d --- /dev/null +++ b/src/fff/SetTester.java @@ -0,0 +1,100 @@ +package fff; +import java.math.BigInteger; +import java.util.Random; +import java.util.Set; + +public class SetTester { + public static long testAdd(Set set, int elements, int repeats) { + long result; + long sum = 0; + + for (int i = 0; i < elements; i++) { + set.add(i); + } + + for (int k = elements + 1; k < elements + repeats; k++) { + long start = System.nanoTime(); + + set.add(k); + + long finish = System.nanoTime(); + long duration = finish - start; + sum +=duration; + } + + set.clear(); + + result = sum / repeats; + return result; + } + + public static long testRemove(Set set, int elements, int repeats) { + long result; + long sum = 0; + Random randomGenerator = new Random(); + + for (int i = 0; i < elements; i++) { + set.add(i); + } + + for (int k = 0; k < repeats; k++) { + long start = System.nanoTime(); + + set.remove(randomGenerator.nextInt(elements)); + + long finish = System.nanoTime(); + long duration = finish - start; + sum += duration; + } + set.clear(); + + result = sum / repeats; + return result; + } + + public static long testContains(Set set, int elements, int repeats) { + long result; + long sum = 0; + Random randomGenerator = new Random(); + + for (int i = 0; i < elements; i++) { + set.add(i); + } + + for (int k = 0; k < repeats; k++) { + long start = System.nanoTime(); + + set.contains(randomGenerator.nextInt(2 * elements)); + + long finish = System.nanoTime(); + long duration = finish - start; + sum += duration; + } + set.clear(); + + result = sum / repeats; + return result; + } + + public static BigInteger testPopulate(Set set, int elements, int repeats) { + BigInteger result; + BigInteger sum = BigInteger.valueOf(0); + + for (int k = 0; k < repeats; k++) { + + long start = System.nanoTime(); + + for (int i = 0; i < elements; i++) { + set.add(i); + } + + long finish = System.nanoTime(); + BigInteger duration = BigInteger.valueOf(finish - start); + sum = sum.add(duration); + + set.clear(); + } + result = sum.divide(BigInteger.valueOf(repeats)); + return result; + } +} \ No newline at end of file diff --git a/src/fff/TableConstructionAndFormatting.java b/src/fff/TableConstructionAndFormatting.java new file mode 100644 index 0000000..f6ff016 --- /dev/null +++ b/src/fff/TableConstructionAndFormatting.java @@ -0,0 +1,85 @@ +package fff; + +import java.io.*; +import java.util.*; + +public class TableConstructionAndFormatting { + + static List arrayList = new ArrayList<>(); + static List linkedList = new LinkedList<>(); + + static Set hashSet = new HashSet<>(); + static Set treeSet = new TreeSet<>(); + + + public static String[] createAndFormateTable() throws IOException { + String [] formatedResult = new String[5]; + Scanner input = new Scanner(System.in); + System.out.printf("Please select which table you want to print :%n %s %n %s %n %s %n", + " 1. 10000 elements", " 2. 100000 elements", " 3. 1000000 elements"); + int choise = input.nextInt(); + if (choise == 1) { + String header = TableConstructionAndFormatting.printHeader("10K"); + formatedResult[0] = header; + + String arrayListResult1 = String.format("%-18s %-6d %-6d %-9d %-11d %-11d %-15d %d%n", "ArrayList", ListTester.testAdd(arrayList, 10000, 100), ListTester.testGet(arrayList, 10000, 100), ListTester.testRemove(arrayList, 10000, 100), ListTester.testContains(arrayList, 10000, 100), ListTester.testPopulate(arrayList, 10000, 100), ListTester.testIteratorAdd(arrayList, 10000, 100), ListTester.testIteratorRemove(arrayList, 10000, 100)); + formatedResult[1] = arrayListResult1; + + String linkedListResult1 = String.format("%-18s %-6d %-6d %-9d %-11d %-11d %-15d %d%n", "LinkedList", ListTester.testAdd(linkedList, 10000, 100), ListTester.testGet(linkedList, 10000, 100), ListTester.testRemove(linkedList, 10000, 100), ListTester.testContains(linkedList, 10000, 100), ListTester.testPopulate(linkedList, 10000, 100), ListTester.testIteratorAdd(linkedList, 10000, 100), ListTester.testIteratorRemove(linkedList, 10000, 100)); + formatedResult[2] = linkedListResult1; + + String hashSetResult1 = String.format("%-18s %-6d %-6s %-9d %-11d %-11d %-15s %s%n", "HashSet", SetTester.testAdd(hashSet, 10000, 100), "n/a ", SetTester.testRemove(hashSet, 10000, 100), SetTester.testContains(hashSet, 10000, 100), SetTester.testPopulate(hashSet, 10000, 100), "n/a ", "n/a "); + formatedResult[3] = hashSetResult1; + + String treeSetResult1 = String.format("%-18s %-6d %-6s %-9d %-11d %-11d %-15s %s%n%n%n%n", "TreeSet", SetTester.testAdd(treeSet, 10000, 100), "n/a ", SetTester.testRemove(treeSet, 10000, 100), SetTester.testContains(treeSet, 10000, 100), SetTester.testPopulate(treeSet, 10000, 100), "n/a ", "n/a "); + formatedResult[4] = treeSetResult1; + + + } else if (choise == 2) { + String header = TableConstructionAndFormatting.printHeader("100K"); + formatedResult[0] = header; + + String arrayListResult2 = String.format("%-18s %-6d %-6d %-9d %-11d %-11d %-15d %d%n", "ArrayList", ListTester.testAdd(arrayList, 100000, 100), ListTester.testGet(arrayList, 100000, 100), ListTester.testRemove(arrayList, 100000, 100), ListTester.testContains(arrayList, 100000, 100), ListTester.testPopulate(arrayList, 100000, 100), ListTester.testIteratorAdd(arrayList, 100000, 100), ListTester.testIteratorRemove(arrayList, 100000, 100)); + formatedResult[1] = arrayListResult2; + + String linkedListResult2 = String.format("%-18s %-6d %-6d %-9d %-11d %-11d %-15d %d%n", "LinkedList", ListTester.testAdd(linkedList, 100000, 100), ListTester.testGet(linkedList, 100000, 100), ListTester.testRemove(linkedList, 100000, 100), ListTester.testContains(linkedList, 100000, 100), ListTester.testPopulate(linkedList, 100000, 100), ListTester.testIteratorAdd(linkedList, 100000, 100), ListTester.testIteratorRemove(linkedList, 100000, 100)); + formatedResult[2] = linkedListResult2; + + String hashSetResult2 = String.format("%-18s %-6d %-6s %-9d %-11d %-11d %-15s %s%n", "HashSet", SetTester.testAdd(hashSet, 100000, 100), "n/a ", SetTester.testRemove(hashSet, 100000, 100), SetTester.testContains(hashSet, 100000, 100), SetTester.testPopulate(hashSet, 100000, 100), "n/a ", "n/a "); + formatedResult[3] = hashSetResult2; + + String treeSetResult2 = String.format("%-18s %-6d %-6s %-9d %-11d %-11d %-15s %s%n%n%n%n", "TreeSet", SetTester.testAdd(treeSet, 100000, 100), "n/a ", SetTester.testRemove(treeSet, 100000, 100), SetTester.testContains(treeSet, 100000, 100), SetTester.testPopulate(treeSet, 100000, 100), "n/a ", "n/a "); + formatedResult[4] = treeSetResult2; + + + } else if (choise == 3) { + String header = TableConstructionAndFormatting.printHeader("1000K"); + formatedResult[0] = header; + + String arrayListResult3 = String.format("%-18s %-9d %-9d %-12d %-14d %-14d %-18d %d%n", "ArrayList", ListTester.testAdd(arrayList, 1000000, 100), ListTester.testGet(arrayList, 1000000, 100), ListTester.testRemove(arrayList, 1000000, 100), ListTester.testContains(arrayList, 1000000, 100), ListTester.testPopulate(arrayList, 1000000, 100), ListTester.testIteratorAdd(arrayList, 1000000, 100), ListTester.testIteratorRemove(arrayList, 1000000, 100)); + formatedResult[1] = arrayListResult3; + + String linkedListResult3 = String.format("%-18s %-9d %-9d %-12d %-14d %-14d %-18d %d%n", "LinkedList", ListTester.testAdd(linkedList, 1000000, 100), ListTester.testGet(linkedList, 1000000, 100), ListTester.testRemove(linkedList, 1000000, 100), ListTester.testContains(linkedList, 1000000, 100), ListTester.testPopulate(linkedList, 1000000, 100), ListTester.testIteratorAdd(linkedList, 1000000, 100), ListTester.testIteratorRemove(linkedList, 1000000, 100)); + formatedResult[2] = linkedListResult3; + + String hashSetResult3 = String.format("%-18s %-9d %-9s %-12d %-14d %-14d %-18s %s%n", "HashSet", SetTester.testAdd(hashSet, 1000000, 100), "n/a ", SetTester.testRemove(hashSet, 1000000, 100), SetTester.testContains(hashSet, 1000000, 100), SetTester.testPopulate(hashSet, 1000000, 100), "n/a ", "n/a "); + formatedResult[3] = hashSetResult3; + + String treeSetResult3 = String.format("%-18s %-9d %-9s %-12d %-14d %-14d %-18s %s%n%n%n%n", "TreeSet", SetTester.testAdd(treeSet, 1000000, 100), "n/a ", SetTester.testRemove(treeSet, 1000000, 100), SetTester.testContains(treeSet, 1000000, 100), SetTester.testPopulate(treeSet, 1000000, 100), "n/a ", "n/a "); + formatedResult[4] = treeSetResult3; + + + } else { + throw new IllegalArgumentException("Invalid input! Input needs to be 1,2 or 3"); + } + return formatedResult; + } + + + private static String printHeader(String elements) { + + String header = String.format("%-18s %-6s %-6s %-9s %-11s %-11s %-15s %-15s%n %s%n%n","Collection type", "add", "get", "remove", "contains", "populate", "iterator.add", "iterator.remove", "(Results for " + elements + " elements in the collection)"); + + return header; + } +} diff --git a/src/module1_1/Performance.java b/src/module1_1/Performance.java deleted file mode 100644 index 5865607..0000000 --- a/src/module1_1/Performance.java +++ /dev/null @@ -1,159 +0,0 @@ -package module1_1; - -import javax.swing.*; -import java.awt.*; -import java.util.*; - -public class Performance extends JFrame { - public static void createGUI(String nameFrame, String[] columnNames, String[][] data) { - JFrame frame = new JFrame(nameFrame); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - JTable table = new JTable(data, columnNames); - - JScrollPane scrollPane = new JScrollPane(table); - - frame.getContentPane().add(scrollPane); - frame.setPreferredSize(new Dimension(700, 150)); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); - } - - public static void main(String[] args) { - ArrayList arrayList = new ArrayList(); - LinkedList linkedList = new LinkedList(); - HashSet hashSet = new HashSet(); - TreeSet treeSet = new TreeSet(); - - - int tenThousand = 10000; - int hundredThousand = 100000; - int oneMillion = 1000000; - String tableName = "Table 10K"; - String[] columnNames = {"Collections", "add", "get", "contains", "remove", "populate", "iterator.add", "iterator.remove"}; - String[][] data = { - {"ArrayList", addListDuration(arrayList, tenThousand), getListDuration(arrayList, tenThousand), - containsListDuration(arrayList, tenThousand), removeListDuration(arrayList, tenThousand), "", - iteratorAddListDuration(arrayList, tenThousand), iteratorRemoveListDuration(arrayList, tenThousand), ""}, - - {"LinkedList", addListDuration(linkedList, tenThousand), getListDuration(linkedList, tenThousand), - containsListDuration(linkedList, tenThousand), removeListDuration(linkedList, tenThousand), "", - iteratorAddListDuration(linkedList, tenThousand), iteratorRemoveListDuration(linkedList, tenThousand)}, - - {"HashSet", addSetDuration(hashSet, tenThousand), "", containsSetDuration(hashSet, tenThousand), - removeSetDuration(hashSet, tenThousand), " ", " ", ""}, - - {"TreeSet", addSetDuration(treeSet, tenThousand), "", containsSetDuration(treeSet, tenThousand), - removeSetDuration(treeSet, tenThousand), " ", " ", ""}}; - - javax.swing.SwingUtilities.invokeLater(new Runnable() { - public void run() { - JFrame.setDefaultLookAndFeelDecorated(true); - createGUI(tableName, columnNames, data); - } - }); - } - - public static String iteratorAddListDuration(AbstractList list, int number) { - ListIterator listIterator = list.listIterator(); - long startTime = System.nanoTime(); - for (int i = 0; i < number; i++) { - listIterator.add(i); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - - return Long.toString(duration); - } - - public static String iteratorRemoveListDuration(AbstractList list, int number) { - ListIterator listIterator = list.listIterator(); - - long startTime = System.nanoTime(); - while (listIterator.hasNext()) { - long s = listIterator.next(); - listIterator.remove(); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - return Long.toString(duration); - } - - public static String addListDuration(AbstractList list, int number) { - long startTime = System.nanoTime(); - - for (int i = 0; i < number; i++) { - list.add(i); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - return Long.toString(duration); - } - - public static String addSetDuration(AbstractSet set, int number) { - long startTime = System.nanoTime(); - - for (int i = 0; i < number; i++) { - set.add(i); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - return Long.toString(duration); - } - - public static String getListDuration(AbstractList list, int number) { - long startTime = System.nanoTime(); - - for (int i = 0; i < number; i++) { - list.get(i); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - return Long.toString(duration); - } - - public static String containsListDuration(AbstractList list, int number) { - long startTime = System.nanoTime(); - - for (int i = 0; i < number; i++) { - list.contains(i); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - return Long.toString(duration); - } - - public static String containsSetDuration(AbstractSet set, int number) { - long startTime = System.nanoTime(); - - for (int i = 0; i < number; i++) { - set.contains(i); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - return Long.toString(duration); - } - - public static String removeSetDuration(AbstractSet set, int number) { - long startTime = System.nanoTime(); - - for (int i = number - 1; i >= 0; i--) { - set.remove(i); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - return Long.toString(duration); - } - - public static String removeListDuration(AbstractList list, int number) { - long startTime = System.nanoTime(); - - for (int i = number - 1; i >= 0; i--) { - list.remove(i); - } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - return Long.toString(duration); - } -} diff --git a/src/module2_1/ArrayListMeasurements.java b/src/module2_1/ArrayListMeasurements.java new file mode 100644 index 0000000..916c7af --- /dev/null +++ b/src/module2_1/ArrayListMeasurements.java @@ -0,0 +1,85 @@ +package module2_1; + +import java.util.ArrayList; +import java.util.ListIterator; +import java.util.Random; + +public class ArrayListMeasurements { + + private static final int COUNT_LIST_TEST_METHODS = 7; + private static final int NUMBER_OF_TESTS = 10; + + private long[][] measurementsArrayList = new long[COUNT_LIST_TEST_METHODS][NUMBER_OF_TESTS]; + private long[] resultTimersArrayList = new long[COUNT_LIST_TEST_METHODS]; + + private ArrayList arrayList = new ArrayList<>(); + + void initialisation(int size) { + + for (int i = 0; i < size; i++) { + arrayList.add(i); + } + + measureArrayList(); + + MainFirstEEmodule.temp = calculateArrayListTimers(); + } + + private long[] calculateArrayListTimers() { + long res = measurementsArrayList[0][0]; + + for (int j = 0; j < measurementsArrayList.length; j++) { + for (int i = 1; i < NUMBER_OF_TESTS - 1; i++) { + + res += measurementsArrayList[j][i]; + } + resultTimersArrayList[j] = res / NUMBER_OF_TESTS; + } + return resultTimersArrayList; + } + + public long[] getResultTimersArrayList() { + return resultTimersArrayList; + } + + private void measureArrayList() { + Random randomNumber = new Random(); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + + int rnd = randomNumber.nextInt(arrayList.size() + 1); + + long timerAdd = System.nanoTime(); + arrayList.add(rnd); + measurementsArrayList[0][i] = System.nanoTime() - timerAdd; + + long timerGet = System.nanoTime(); + arrayList.get(rnd); + measurementsArrayList[1][i] = System.nanoTime() - timerGet; + + long timerRemove = System.nanoTime(); + arrayList.remove(rnd); + measurementsArrayList[2][i] = System.nanoTime() - timerRemove; + + long timerContains = System.nanoTime(); + arrayList.contains(rnd); + measurementsArrayList[3][i] = System.nanoTime() - timerContains; + + long timerPopulate = System.nanoTime(); + measurementsArrayList[4][i] = System.nanoTime() - timerPopulate; + + long timerIterAdd = System.nanoTime(); + ListIterator iterator = arrayList.listIterator(); + iterator.next(); + iterator.add(rnd); + + measurementsArrayList[5][i] = System.nanoTime() - timerIterAdd; + + long timerIterRemove = System.nanoTime(); + ListIterator iter = arrayList.listIterator(); + iter.next(); + iter.remove(); + + measurementsArrayList[6][i] = System.nanoTime() - timerIterRemove; + } + } +} diff --git a/src/module2_1/HashSetMeasurements.java b/src/module2_1/HashSetMeasurements.java new file mode 100644 index 0000000..99d0dfc --- /dev/null +++ b/src/module2_1/HashSetMeasurements.java @@ -0,0 +1,67 @@ +package module2_1; + +import java.util.HashSet; +import java.util.Random; +import java.util.Set; + +public class HashSetMeasurements { + + private static final int COUNT_SET_TEST_METHODS = 4; + private static final int NUMBER_OF_TESTS = 10; + + private long[][] measurementsHashSet = new long[COUNT_SET_TEST_METHODS][NUMBER_OF_TESTS]; + private long[] resultTimersHashSet = new long[COUNT_SET_TEST_METHODS]; + + private final Set hashSet = new HashSet<>(); + + void initialization(int size) { + for (int i = 0; i < size; i++) { + hashSet.add(i); + } + + measureHashSet(); + + MainFirstEEmodule.temp = calculateHashSetTimers(); + } + + private long[] calculateHashSetTimers() { + long res = measurementsHashSet[0][0]; + + for (int j = 0; j < measurementsHashSet.length; j++) { + for (int i = 1; i < NUMBER_OF_TESTS - 1; i++) { + + res += measurementsHashSet[j][i]; + } + resultTimersHashSet[j] = res / NUMBER_OF_TESTS; + } + return resultTimersHashSet; + } + + long[] getResultTimersHashSet() { + return resultTimersHashSet; + } + + private void measureHashSet() { + Random randomNumber = new Random(); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + + int rnd = randomNumber.nextInt(hashSet.size() + 1); + + long timerAdd = System.nanoTime(); + hashSet.add(rnd); + measurementsHashSet[0][i] = System.nanoTime() - timerAdd; + + long timerRemove = System.nanoTime(); + hashSet.remove(rnd); + measurementsHashSet[1][i] = System.nanoTime() - timerRemove; + + long timerContains = System.nanoTime(); + hashSet.contains(rnd); + measurementsHashSet[2][i] = System.nanoTime() - timerContains; + + hashSet.clear(); + long timerPopulate = System.nanoTime(); + measurementsHashSet[3][i] = System.nanoTime() - timerPopulate; + } + } +} \ No newline at end of file diff --git a/src/module2_1/LinkedListMeasurements.java b/src/module2_1/LinkedListMeasurements.java new file mode 100644 index 0000000..e5fd396 --- /dev/null +++ b/src/module2_1/LinkedListMeasurements.java @@ -0,0 +1,87 @@ +package module2_1; + +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; +import java.util.Random; + +class LinkedListMeasurements { + + private static final int COUNT_LIST_TEST_METHODS = 7; + private static final int NUMBER_OF_TESTS = 10; + + private long[][] measurementsLinkedList = new long[COUNT_LIST_TEST_METHODS][NUMBER_OF_TESTS]; + private long[] resultTimersLinkedList = new long[COUNT_LIST_TEST_METHODS]; + + private LinkedList linkedList = new LinkedList<>(); + + void initialisation(int size) { + + for (int i = 0; i < size; i++) { + linkedList.add(i); + } + + measureLinkedList(); + + MainFirstEEmodule.temp = calculateLinkedListTimers(); + } + + private long[] calculateLinkedListTimers() { + long res = measurementsLinkedList[0][0]; + + for (int j = 0; j < measurementsLinkedList.length; j++) { + for (int i = 1; i < NUMBER_OF_TESTS; i++) { + + res += measurementsLinkedList[j][i]; + } + resultTimersLinkedList[j] = res / NUMBER_OF_TESTS; + } + return resultTimersLinkedList; + } + + long[] getResultTimersLinkedList() { + return resultTimersLinkedList; + } + + private void measureLinkedList() { + Random randomNumber = new Random(); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + + int rnd = randomNumber.nextInt(linkedList.size() + 1); + + long timerAdd = System.nanoTime(); + linkedList.add(rnd); + measurementsLinkedList[0][i] = System.nanoTime() - timerAdd; + + long timerGet = System.nanoTime(); + linkedList.get(rnd); + measurementsLinkedList[1][i] = System.nanoTime() - timerGet; + + long timerRemove = System.nanoTime(); + linkedList.remove(rnd); + measurementsLinkedList[2][i] = System.nanoTime() - timerRemove; + + long timerContains = System.nanoTime(); + linkedList.contains(rnd); + measurementsLinkedList[3][i] = System.nanoTime() - timerContains; + + long timerPopulate = System.nanoTime(); + List newLinkedList = new LinkedList(linkedList); + measurementsLinkedList[4][i] = System.nanoTime() - timerPopulate; + + long timerIterAdd = System.nanoTime(); + ListIterator iterator = linkedList.listIterator(); + iterator.next(); + iterator.add(rnd); + + measurementsLinkedList[5][i] = System.nanoTime() - timerIterAdd; + + long timerIterRemove = System.nanoTime(); + iterator = linkedList.listIterator(); + iterator.next(); + iterator.remove(); + + measurementsLinkedList[6][i] = System.nanoTime() - timerIterRemove; + } + } +} diff --git a/src/module2_1/MainFirstEEmodule.java b/src/module2_1/MainFirstEEmodule.java new file mode 100644 index 0000000..436b6d7 --- /dev/null +++ b/src/module2_1/MainFirstEEmodule.java @@ -0,0 +1,73 @@ +package module2_1; + + +public class MainFirstEEmodule { + private static final int COUNT_LIST_TEST_METHODS = 7; + private static final int COUNT_SET_TEST_METHODS = 4; + + private static final int NUM10K = 10000; + private static final int NUM100K = 100000; + private static final int NUM1000K = 1000000; + + + static long[] temp = new long[7]; + + public static void main(String[] args) { + long[] resArray = new long[COUNT_LIST_TEST_METHODS]; + long[] resLinked = new long[COUNT_LIST_TEST_METHODS]; + long[] resTree = new long[COUNT_SET_TEST_METHODS]; + long[] resHash = new long[COUNT_SET_TEST_METHODS]; + + LinkedListMeasurements linkedListMeasurements = new LinkedListMeasurements(); + ArrayListMeasurements arrayListMeasurements = new ArrayListMeasurements(); + TreeSetMeasurements treeSetMeasurements = new TreeSetMeasurements(); + HashSetMeasurements hashSetMeasurements = new HashSetMeasurements(); + + linkedListMeasurements.initialisation(NUM10K); + long[] resTemp10k = linkedListMeasurements.getResultTimersLinkedList(); + linkedListMeasurements.initialisation(NUM100K); + long[] resTemp100k = linkedListMeasurements.getResultTimersLinkedList(); + linkedListMeasurements.initialisation(NUM1000K); + long[] resTemp1000k = linkedListMeasurements.getResultTimersLinkedList(); + + for (int i = 0; i < resLinked.length; i++) { + resLinked[i] = (resTemp10k[i] + resTemp100k[i] + resTemp1000k[i]) / 3; + } + + arrayListMeasurements.initialisation(NUM10K); + resTemp10k = arrayListMeasurements.getResultTimersArrayList(); + arrayListMeasurements.initialisation(NUM100K); + resTemp100k = arrayListMeasurements.getResultTimersArrayList(); + arrayListMeasurements.initialisation(NUM1000K); + resTemp1000k = arrayListMeasurements.getResultTimersArrayList(); + + for (int i = 0; i < resArray.length; i++) { + resArray[i] = (resTemp10k[i] + resTemp100k[i] + resTemp1000k[i]) / 3; + } + treeSetMeasurements.Initialization(NUM10K); + resTemp10k = treeSetMeasurements.getResultTimersTreeSet(); + treeSetMeasurements.Initialization(NUM100K); + resTemp100k = treeSetMeasurements.getResultTimersTreeSet(); + treeSetMeasurements.Initialization(NUM1000K); + resTemp1000k = treeSetMeasurements.getResultTimersTreeSet(); + + for (int i = 0; i < resTree.length; i++) { + resTree[i] = (resTemp10k[i] + resTemp100k[i] + resTemp1000k[i]) / 3; + } + hashSetMeasurements.initialization(NUM10K); + resTemp10k = hashSetMeasurements.getResultTimersHashSet(); + hashSetMeasurements.initialization(NUM100K); + resTemp100k = hashSetMeasurements.getResultTimersHashSet(); + hashSetMeasurements.initialization(NUM1000K); + resTemp1000k = hashSetMeasurements.getResultTimersHashSet(); + + for (int i = 0; i < resHash.length; i++) { + resHash[i] = (resTemp10k[i] + resTemp100k[i] + resTemp1000k[i]) / 3; + } + + Print.printToConsole(resArray, resLinked, resTree, resHash); + Print.printToFile(resArray,resLinked,resTree,resHash); + } + + +} diff --git a/src/module2_1/Print.java b/src/module2_1/Print.java new file mode 100644 index 0000000..28b03a3 --- /dev/null +++ b/src/module2_1/Print.java @@ -0,0 +1,79 @@ +package module2_1; +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.Writer; + +public class Print { + static private String strip = "+-----------------------------------------------------------------------------------------------+"; + + static void printToConsole(long[] arrayList, long[] linkedList, long[] treeSet, long[] hashSet) { + System.out.println(strip); + printHead(); + + System.out.println(strip); + printArrayList("ArrayList", arrayList); + printLinkedList("LinkedList", linkedList); + + printSet("TreeSet", treeSet); + printSet("HashSet", hashSet); + + System.out.println(strip); + + } + + static void printToFile(long[] arrayList, long[] linkedList, long[] treeSet, long[] hashSet) { + + try (Writer writer = new BufferedWriter(new FileWriter("result.txt", true))) { + writer.flush(); + writer.write(strip + "\n"); + writer.write("|\t\t\t\t" + "add" + "\t\t" + "get" + "\t\t\t" + "remove" + "\t\t" + + "contains" + "\t" + "populate" + "\t" + "iter.add" + "\t" + "iter.remove" + " | \n"); + writer.write(strip + "\n"); + + writer.write("| " + "ArrayList" + ":\t" + arrayList[0] / 1000 + "\t\t" + arrayList[1] / 1000 + "\t\t\t" + + arrayList[2] / 1000 + "\t\t\t" + arrayList[3] / 1000 + "\t\t" + arrayList[4] / 1000 + "\t\t" + + arrayList[5] / 1000 + "\t\t" + arrayList[6] / 1000 + "\t\t| \n"); + + writer.write("| " + "LinkedList" + ":\t" + linkedList[0] / 1000 + "\t\t" + linkedList[1] / 1000 + "\t\t" + + linkedList[2] / 1000 + "\t\t" + linkedList[3] / 1000 + "\t\t" + linkedList[4] / 1000 + "\t\t" + + linkedList[5] / 1000 + "\t\t" + linkedList[6] / 1000 + "\t\t| \n"); + + writer.write("| " + "TreeSet" + ":\t\t" + treeSet[0] / 1000 + "\t\t\t\t\t" + treeSet[1] / 1000 + "\t\t\t" + + treeSet[2] / 1000 + "\t\t\t" + treeSet[3] / 1000 + "\t\t\t\t\t\t\t\t\t" + "| \n"); + + writer.write("| " + "HashSet" + ":\t\t" + hashSet[0] / 1000 + "\t\t\t\t\t" + hashSet[1] / 1000 + "\t\t\t" + + hashSet[2] / 1000 + "\t\t\t" + hashSet[3] / 1000 + "\t\t\t\t\t\t\t\t\t" + "| \n"); + + writer.write(strip + "\n"); + + } catch (Exception ex) { + System.out.println("Error saving data to file Result.txt"); + } + } + + + private static void printHead() { + System.out.println("|\t\t\t\t" + "add" + "\t\t" + "get" + "\t\t\t" + "remove" + "\t\t" + + "contains" + "\t" + "populate" + "\t" + "iter.add" + "\t" + "iter.remove" + " |"); + } + + private static void printArrayList(String name, long[] result) { + System.out.print("| " + name + ":\t" + result[0] / 1000 + "\t\t" + result[1] / 1000 + "\t\t\t" + + result[2] / 1000 + "\t\t\t" + result[3] / 1000 + "\t\t" + result[4] / 1000 + "\t\t" + + result[5] / 1000 + "\t\t" + result[6] / 1000 + "\t\t|"); + System.out.println(); + } + + private static void printLinkedList(String name, long[] result) { + System.out.print("| " + name + ":\t" + result[0] / 1000 + "\t\t" + result[1] / 1000 + "\t\t" + + result[2] / 1000 + "\t\t" + result[3] / 1000 + "\t\t" + result[4] / 1000 + "\t\t" + + result[5] / 1000 + "\t\t" + result[6] / 1000 + "\t\t|"); + System.out.println(); + } + + private static void printSet(String name, long[] result) { + System.out.print("| " + name + ":\t\t" + result[0] / 1000 + "\t\t\t\t\t" + result[1] / 1000 + "\t\t\t" + + result[2] / 1000 + "\t\t\t" + result[3] / 1000 + "\t\t\t\t\t\t\t\t\t" + "|"); + System.out.println(); + } +} \ No newline at end of file diff --git a/src/module2_1/TreeSetMeasurements.java b/src/module2_1/TreeSetMeasurements.java new file mode 100644 index 0000000..e7d8d3d --- /dev/null +++ b/src/module2_1/TreeSetMeasurements.java @@ -0,0 +1,69 @@ +package module2_1; + +import java.util.Random; +import java.util.Set; +import java.util.TreeSet; + +class TreeSetMeasurements { + + private static final int COUNT_SET_TEST_METHODS = 4; + private static final int NUMBER_OF_TESTS = 10; + + private long[][] measurementsTreeSet = new long[COUNT_SET_TEST_METHODS][NUMBER_OF_TESTS]; + private long[] resultTimersTreeSet = new long[COUNT_SET_TEST_METHODS]; + + private final Set treeSet = new TreeSet<>(); + + void Initialization(int size) { + for (int i = 0; i < size; i++) { + treeSet.add(i); + } + + measureTreeSet(); + + MainFirstEEmodule.temp = calculateTreeSetTimers(); + } + + + private long[] calculateTreeSetTimers() { + long res = measurementsTreeSet[0][0]; + + for (int j = 0; j < measurementsTreeSet.length; j++) { + for (int i = 1; i < NUMBER_OF_TESTS - 1; i++) { + + res += measurementsTreeSet[j][i]; + } + resultTimersTreeSet[j] = res / NUMBER_OF_TESTS; + } + return resultTimersTreeSet; + } + + long[] getResultTimersTreeSet() { + return resultTimersTreeSet; + } + + private void measureTreeSet() { + Random randomNumber = new Random(); + for (int i = 0; i < NUMBER_OF_TESTS; i++) { + + int rnd = randomNumber.nextInt(treeSet.size() + 1); + + long timerAdd = System.nanoTime(); + treeSet.add(rnd); + measurementsTreeSet[0][i] = System.nanoTime() - timerAdd; + + long timerRemove = System.nanoTime(); + treeSet.remove(rnd); + measurementsTreeSet[1][i] = System.nanoTime() - timerRemove; + + long timerContains = System.nanoTime(); + treeSet.contains(rnd); + measurementsTreeSet[2][i] = System.nanoTime() - timerContains; + + treeSet.clear(); + long timerPopulate = System.nanoTime(); + measurementsTreeSet[3][i] = System.nanoTime() - timerPopulate; + } + + } +} \ No newline at end of file diff --git a/src/module2_3_1/MySemaphore.java b/src/module2_3_1/MySemaphore.java new file mode 100644 index 0000000..048f14b --- /dev/null +++ b/src/module2_3_1/MySemaphore.java @@ -0,0 +1,91 @@ +package module2_3_1; + +class MySemaphore implements Semaphore { + private volatile int permitsAvailable; + private final int ACQUIRE = 1; + private final Object lock; + private String threadName = Thread.currentThread().getName(); + + + MySemaphore(int permitsAvailable) { + this.permitsAvailable = permitsAvailable; + this.lock = new Object(); + } + + @Override + public void acquire() throws InterruptedException { + synchronized (lock) { + while (true) { + System.out.println(threadName + " checking available acquire."); + + + if (tryAcquire(ACQUIRE)) { + System.out.println(threadName + " was acquired."); + permitsAvailable--; + Thread.sleep(5000); + break; + } else { + System.out.println(threadName + " is waiting."); + Thread.currentThread().wait(); /// + System.out.println(threadName + " woke up"); + Thread.sleep(1000); + } + } + } + } + + @Override + public void acquire(int permits) throws InterruptedException { + synchronized (lock) { + while (true) { + System.out.println(threadName + " checking available acquire."); + if (tryAcquire(permits)) { + System.out.println(threadName + " was acquired."); + permitsAvailable -= permits; + Thread.sleep(5000); + break; + } else { + System.out.println(threadName + " is waiting."); + lock.wait(); + System.out.println(threadName + " woke up."); + Thread.sleep(1000); + } + } + } + } + + private boolean tryAcquire(int perm) { + return permitsAvailable - perm >= 0; + } + + @Override + public void release() { + synchronized (lock) { + if (permitsAvailable + 1 > 0) { + permitsAvailable++; + lock.notify(); + System.out.println("Threads was notified by " + threadName); + } else { + System.out.println("Threads did not notify, available permits: " + permitsAvailable); + } + } + } + + @Override + public void release(int permits) { + synchronized (lock) { + if (permitsAvailable + permits > 0) { + permitsAvailable += permits; + lock.notifyAll(); + System.out.println("All threads was notified by " + threadName); + } else { + System.out.println("Threads did not notify, available permits: " + permitsAvailable); + } + } + } + + @Override + public int getAvailablePermits() { + return permitsAvailable; + } +} \ No newline at end of file diff --git a/src/module2_3_1/Semaphore.java b/src/module2_3_1/Semaphore.java new file mode 100644 index 0000000..ec01bcd --- /dev/null +++ b/src/module2_3_1/Semaphore.java @@ -0,0 +1,25 @@ +package module2_3_1; + +public interface Semaphore { + // Запрашивает разрешение. Если есть свободное захватывает его. Если нет - приостанавливает поток до тех пор пока не появится свободное разрешение. + + public void acquire() throws InterruptedException; + + // Запрашивает переданое количество разрешений. Если есть переданое количество свободных разрешений захватывает их. + + // Если нет - приостанавливает поток до тех пор пока не появится переданое колтчество свободных разрешений. + + public void acquire(int permits) throws InterruptedException; + + // Отпускает разрешение возвращая его семафору. + + public void release(); + + // Отпускает переданое количество разрешений возварщая их семафору. + + public void release(int permits); + + // Возвращает количество свободных разрешений на данный момент. + + public int getAvailablePermits(); +} diff --git a/src/module2_3_1/SemaphoreTestDrive.java b/src/module2_3_1/SemaphoreTestDrive.java new file mode 100644 index 0000000..4bd5b6d --- /dev/null +++ b/src/module2_3_1/SemaphoreTestDrive.java @@ -0,0 +1,36 @@ +package module2_3_1; + +public class SemaphoreTestDrive { + private static MySemaphore mySemaphore; + + public static void main(String[] args) throws InterruptedException { + + int threads = 3; + mySemaphore = new MySemaphore(5); + + for (int i = 0; i < threads; i++) { + new Thread(new WorkerForParametrizedAcquire()).start(); + } + + while (WorkerForParametrizedAcquire.counter < threads) { + Thread.sleep(3000); + } + } + + private static class WorkerForParametrizedAcquire implements Runnable { + static int counter = 0; + private int acquireIsNeeded = 5; + + @Override + public void run() { + try { + mySemaphore.acquire(acquireIsNeeded); + Thread.sleep(3000); + mySemaphore.release(acquireIsNeeded); + counter++; + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/practice_four/WordNumber.java b/src/practice_four/WordNumber.java new file mode 100644 index 0000000..0575423 --- /dev/null +++ b/src/practice_four/WordNumber.java @@ -0,0 +1,16 @@ +package practice_four; + +import java.util.Arrays; +import java.util.List; + +/** + Злічити Слова + + Дано рядок. Порахувати кількість слів. + Словом вважається послідовність символів англійського алфавіту [a-zA-Z]. + + Алгоритм повинен працювати за O(N) часу, тому RegExp використовувати не можна. + */ +public class WordNumber { + +} diff --git a/src/practice_three/LongestStabilityPeriod.java b/src/practice_three/LongestStabilityPeriod.java new file mode 100644 index 0000000..5a680eb --- /dev/null +++ b/src/practice_three/LongestStabilityPeriod.java @@ -0,0 +1,42 @@ +package practice_three; + +/** + * Найдовший Період Стабільності + *

+ * Дано масив чисел в якому знаходяться значення ВВП за кожен місяць в мільярдах доларів США. + * Необхідно знайти найдовший період стабільності. + * Період стабільності - період часу де всі значення ВВП попарно відрізняються один від одного максимум на 1. + * Повернути кількість місяців. + */ +public class LongestStabilityPeriod { + public int count(int[] gdp) { + if (gdp.length == 0) return 0; + if (gdp.length == 1) return 1; + + int max = 0; + + for (int i = 0; i < gdp.length; i++) { + int countA = goWithDiff(gdp, i, 1); + int countB = goWithDiff(gdp, i, -1); + int count = countA > countB ? countA + 1 : countB + 1; + if (count > max) max = count; + } + + return max; + } + + private int goWithDiff(int[] gdp, int i, int diff) { + int j; + int countB = 0; + j = i + diff; + int inc = 0; + while (j >= 0 && j < gdp.length) { + if (Math.abs(gdp[j] - gdp[i]) > 1) break; + if (inc == 0) inc = gdp[j] - gdp[i]; + else if (gdp[j] - gdp[i] == -1 * inc) break; + countB++; + j += diff; + } + return countB; + } +} diff --git a/src/test/practice_three/LongestStabilityPeriodTest.java b/src/test/practice_three/LongestStabilityPeriodTest.java new file mode 100644 index 0000000..631d1df --- /dev/null +++ b/src/test/practice_three/LongestStabilityPeriodTest.java @@ -0,0 +1,21 @@ +package test.practice_three; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** +Найдовший Період Стабільності + + Дано масив чисел в якому знаходяться значення ВВП за кожен місяць в мільярдах доларів США. + Необхідно знайти найдовший період стабільності. + Період стабільності - період часу де всі значення ВВП попарно відрізняються один від одного максимум на 1. + Повернути кількість місяців. + */ +public class LongestStabilityPeriodTest { + + @Test + public void testCount() throws Exception { + + } +} \ No newline at end of file From ec9134e6a8c71be648ee6dea5513b194ff4adaec Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Thu, 9 Jun 2016 21:30:04 +0300 Subject: [PATCH 29/32] add Pr. 5 --- src/practice_five/BSTSearch.java | 31 +++++++++++++----- src/practice_five/KmpSmallestPeriod.java | 29 +++++++++++++++++ src/practice_five/KmpSubMove.java | 40 ++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 8 deletions(-) create mode 100644 src/practice_five/KmpSmallestPeriod.java create mode 100644 src/practice_five/KmpSubMove.java diff --git a/src/practice_five/BSTSearch.java b/src/practice_five/BSTSearch.java index 1eb2002..4aa9eca 100644 --- a/src/practice_five/BSTSearch.java +++ b/src/practice_five/BSTSearch.java @@ -4,13 +4,28 @@ * Знайти число в бінарному дереві пошуку і повернути true якщо воно присутнє, інакше повернути false. */ public class BSTSearch { - // public boolean exist(TreeNode root, int target) { - - // } + public boolean exist(TreeNode root, int target) { + boolean result = false; + if(root != null){ + if(root.value == target){ + result = true; + } else if(root.value > target){ + result = exist(root.left, target); + } else { + result = exist(root.right, target); + } + } + return result; + } } -/* + class TreeNode { - int value; - TreeNode left, right; -} -*/ \ No newline at end of file + int value; + TreeNode left, right; + + public TreeNode(int value, TreeNode left, TreeNode right) { + this.value = value; + this.left = left; + this.right = right; + } +} \ No newline at end of file diff --git a/src/practice_five/KmpSmallestPeriod.java b/src/practice_five/KmpSmallestPeriod.java new file mode 100644 index 0000000..2453d08 --- /dev/null +++ b/src/practice_five/KmpSmallestPeriod.java @@ -0,0 +1,29 @@ +package practice_five; + +/** + Найменший Період + + A character string is said to have period k if it can be formed by concatenating one or more repetitions of another string of length k. + For example, the string "abcabcabcabc" has period 3, since it is formed by 4 repetitions of the string "abc". + It also has periods 6 (two repetitions of "abcabc") and 12 (one repetition of "abcabcabcabc"). + Write a program to read a character string and determine its smallest period + Return (String) substring; + */ +public class KmpSmallestPeriod { + public String findSmalletstPeriod(String input) { + String result; + int start = 0; + int end = 1; + + while (true){ + result = input.substring(start, end); + String stringToCompare = input.substring(end, end + result.length()); + if(result.equals(stringToCompare)){ + break; + } else { + end++; + } + } + return result; + } +} diff --git a/src/practice_five/KmpSubMove.java b/src/practice_five/KmpSubMove.java new file mode 100644 index 0000000..447b86d --- /dev/null +++ b/src/practice_five/KmpSubMove.java @@ -0,0 +1,40 @@ +package practice_five; + +/** + Циклічний Зсув + + Дается строка в которой делается несколько циклических сдвигов + (под циклическим сдвигом понимается перенос последней буквы в начало) + Дается также получившаяся строка + нужно вернуть минимальное количество сдвигов(int) которым можно получить из 1-й строки итоговую + если строку получить циклическим сдвигом нельзя то вывести -1 + + Например + Дано: + abcd + cdab + + ответ: 2 + */ +public class KmpSubMove { + public int subMoveQuantity(String inputStr, String resultStr) { + int count = 0; + + StringBuilder str = new StringBuilder(inputStr); + + while (count < inputStr.length()){ + if(inputStr.equals(resultStr)){ + return count; + } else { + str.delete(0, str.length()); + str.append(inputStr.substring(inputStr.length()-1)); + str.append(inputStr.substring(0, inputStr.length() - 1)); + + inputStr = str.toString(); + count++; + } + } + + return -1; + } +} From 2109810c3685d4103bd4079196395da4d17880e9 Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sun, 12 Jun 2016 12:04:55 +0300 Subject: [PATCH 30/32] added homework module 3.2 --- src/module2_3_2/MySquareSumImpl.java | 66 ++++++++++++++++++++++++ src/module2_3_2/MySquareSumImplTest.java | 14 +++++ src/module2_3_2/SquareSum.java | 6 +++ 3 files changed, 86 insertions(+) create mode 100644 src/module2_3_2/MySquareSumImpl.java create mode 100644 src/module2_3_2/MySquareSumImplTest.java create mode 100644 src/module2_3_2/SquareSum.java diff --git a/src/module2_3_2/MySquareSumImpl.java b/src/module2_3_2/MySquareSumImpl.java new file mode 100644 index 0000000..39dab5c --- /dev/null +++ b/src/module2_3_2/MySquareSumImpl.java @@ -0,0 +1,66 @@ +package module2_3_2; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.*; +import java.util.stream.IntStream; +/* +Домашнее задание к модулю 3.2 +Grade: N/A +View Grade Information. Opens a dialogue +Используя Phaser и Executors реализовать класс, который бы считал сумму квадратов элементов массива параллельно в заданном количестве потоков + +interface SquareSum { + long getSquareSum(int[] values, int numberOfThreads); +} +Идея в том, чтобы разбить массив на равные части и найти сумму квадратов в каждом кусочке в отдельном потоке параллельно. +Используя Phaser, дождаться результатов всех вычислений и сложить их, получив конечный результат. + */ + +public class MySquareSumImpl implements SquareSum { + private List> tasks = new ArrayList<>(); + private List> sums = new ArrayList<>(); + private final Phaser phaser = new Phaser(); + private long finalSum; + + @Override + public long getSquareSum(int[] values, int numberOfThreads) { + IntStream.range(0, numberOfThreads).forEach(i -> tasks.add(() -> { + long sum = 0; + + phaser.register(); + + int from = (i * values.length) / numberOfThreads; + int to = ((i + 1) * values.length) / numberOfThreads; + + for (int k = from; k < to; k++) { + sum += StrictMath.pow(values[k], 2); + } + + phaser.arriveAndAwaitAdvance(); + phaser.arriveAndDeregister(); + return sum; + })); + + ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); + + try { + sums = executorService.invokeAll(tasks); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + for (Future sum : sums) { + try { + finalSum += (long) sum.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } + executorService.shutdown(); + + return finalSum; + } +} + + diff --git a/src/module2_3_2/MySquareSumImplTest.java b/src/module2_3_2/MySquareSumImplTest.java new file mode 100644 index 0000000..7e0a92a --- /dev/null +++ b/src/module2_3_2/MySquareSumImplTest.java @@ -0,0 +1,14 @@ +package module2_3_2; + +public class MySquareSumImplTest { + public static void main(String[] args) { + int[] array1 = {9, 2, 3, 3, 4, 1, 5, 5, 8}; + int[] array2 = {6, 2, 1, 3, 9, 4, 9, 7, 9}; + + long squareSum1 = new MySquareSumImpl().getSquareSum(array1, 3); + long squareSum2 = new MySquareSumImpl().getSquareSum(array2, 4); + + System.out.println(squareSum1); + System.out.println(squareSum2); + } +} \ No newline at end of file diff --git a/src/module2_3_2/SquareSum.java b/src/module2_3_2/SquareSum.java new file mode 100644 index 0000000..dd6242f --- /dev/null +++ b/src/module2_3_2/SquareSum.java @@ -0,0 +1,6 @@ +package module2_3_2; + + +interface SquareSum { + long getSquareSum(int[] values, int numberOfThreads); +} From 4e0aa6c96fe78eadf3bb4f0e3dd0a60af4a5d1de Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sun, 12 Jun 2016 12:30:05 +0300 Subject: [PATCH 31/32] added practice 4 --- src/practice_four/ColorChain.java | 24 ++++++++++++++++++++ src/practice_four/JoinCharacters.java | 14 ++++++++++++ src/practice_four/WordNumber.java | 32 ++++++++++++++++++++------- 3 files changed, 62 insertions(+), 8 deletions(-) create mode 100644 src/practice_four/ColorChain.java create mode 100644 src/practice_four/JoinCharacters.java diff --git a/src/practice_four/ColorChain.java b/src/practice_four/ColorChain.java new file mode 100644 index 0000000..ddcc03d --- /dev/null +++ b/src/practice_four/ColorChain.java @@ -0,0 +1,24 @@ +package practice_four; + +/* +Условие: +Дано цепи трёх цветов: белого длиной 1 м, желтого - 2 м и красного - 3 м. Каким количеством способов можно собрать из них цепь длиной N. +Количество цепей каждого цвета считать бесконечным. +Результат задачи: ссылка на задачу, которая успешно прошла все тесты в системе Codegym, загружена как ответ на это задание. + */ +public class ColorChain { + public int count(int N) { + int[] results = new int[N + 1]; + results[0] = 1; + if (N >= 1) results[1] = 1; + if (N >= 2) results[2] = 2; + if (N >= 3) results[3] = 4; + if (N >= 4) results[4] = 7; + if (N >= 5) { + for (int i = 5; i <= N; i++) { + results[i] = results[i - 1] + results[i - 2] + results[i - 3]; + } + } + return results[N]; + } +} \ No newline at end of file diff --git a/src/practice_four/JoinCharacters.java b/src/practice_four/JoinCharacters.java new file mode 100644 index 0000000..b8f2e00 --- /dev/null +++ b/src/practice_four/JoinCharacters.java @@ -0,0 +1,14 @@ +package practice_four; + +/** + * Злиття Цифр + * З'єднати масив символів в число. + * Приклад: + * Для [ '1', '2', '3'] повернути 123 + */ +public class JoinCharacters { + public int join(char[] input) { + String s = new String(input); + return Integer.parseInt(s); + } +} \ No newline at end of file diff --git a/src/practice_four/WordNumber.java b/src/practice_four/WordNumber.java index 0575423..fa33c28 100644 --- a/src/practice_four/WordNumber.java +++ b/src/practice_four/WordNumber.java @@ -4,13 +4,29 @@ import java.util.List; /** - Злічити Слова - - Дано рядок. Порахувати кількість слів. - Словом вважається послідовність символів англійського алфавіту [a-zA-Z]. - - Алгоритм повинен працювати за O(N) часу, тому RegExp використовувати не можна. + * Злічити Слова + *

+ * Дано рядок. Порахувати кількість слів. + * Словом вважається послідовність символів англійського алфавіту [a-zA-Z]. + *

+ * Алгоритм повинен працювати за O(N) часу, тому RegExp використовувати не можна. */ public class WordNumber { - -} + public int count(String input) { + input = input.toLowerCase(); + System.out.println(input); + char[] inputsChar = input.toCharArray(); + int res = 0; + boolean word = false; + for (char c : inputsChar) { + if (c >= 'a' && c <= 'z') { + word = true; + } else if (word) { + word = false; + res++; + } + } + if (word) res++; + return res; + } +} \ No newline at end of file From 1de70845116a758830ab6661ed2039ca200ef68a Mon Sep 17 00:00:00 2001 From: Dima Parkhomenko Date: Sat, 2 Jul 2016 16:21:02 +0300 Subject: [PATCH 32/32] work with ANT --- src/fff/IOUtil.java | 26 --- src/fff/ListTester.java | 188 ------------------ src/fff/Runner.java | 13 -- src/fff/SetTester.java | 100 ---------- src/fff/TableConstructionAndFormatting.java | 85 -------- src/module2_1/build.xml | 30 +++ src/module2_2/ExecutorImpl.java | 6 +- .../{GenericsTestDrive.java => Run.java} | 2 +- src/module2_2/build.xml | 31 +++ src/module2_3_1/build.xml | 31 +++ src/module2_3_2/build.xml | 31 +++ src/some/Test.java | 17 ++ src/test/module2_2/ExecutorImplTest.java | 30 +++ 13 files changed, 174 insertions(+), 416 deletions(-) delete mode 100644 src/fff/IOUtil.java delete mode 100644 src/fff/ListTester.java delete mode 100644 src/fff/Runner.java delete mode 100644 src/fff/SetTester.java delete mode 100644 src/fff/TableConstructionAndFormatting.java create mode 100644 src/module2_1/build.xml rename src/module2_2/{GenericsTestDrive.java => Run.java} (97%) create mode 100644 src/module2_2/build.xml create mode 100644 src/module2_3_1/build.xml create mode 100644 src/module2_3_2/build.xml create mode 100644 src/some/Test.java create mode 100644 src/test/module2_2/ExecutorImplTest.java diff --git a/src/fff/IOUtil.java b/src/fff/IOUtil.java deleted file mode 100644 index c675515..0000000 --- a/src/fff/IOUtil.java +++ /dev/null @@ -1,26 +0,0 @@ -package fff; - -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; - - -public class IOUtil { - - public static void printToConsole (String[] data) { - - for (int i = 0; i < data.length; i++) { - System.out.print(data[i]); - } - } - - public static void saveToFile (String data[], String path ) throws IOException { - PrintWriter fileWriter = new PrintWriter(new FileWriter(path, true)); - - for (int i = 0; i < data.length; i++) { - fileWriter.print(data[i]); - } - - fileWriter.close(); - } -} diff --git a/src/fff/ListTester.java b/src/fff/ListTester.java deleted file mode 100644 index a8a0ae0..0000000 --- a/src/fff/ListTester.java +++ /dev/null @@ -1,188 +0,0 @@ -package fff; -import java.util.List; -import java.util.ListIterator; -import java.util.Random; - -public class ListTester { - - public static long testAdd(List list, int elements, int repeats){ - long result; - long sum = 0; - Random randomGenerator = new Random(); - - for (int i = 0; i < elements; i++) { - list.add(i); - } - - for (int k = 0; k < repeats; k++) { - long start = System.nanoTime(); - - list.add(randomGenerator.nextInt(elements),randomGenerator.nextInt(elements)); - - long finish = System.nanoTime(); - long duration = finish - start; - sum +=duration; - } - list.clear(); - - result = sum / repeats; - return result; - } - - - public static long testGet(List list, int elements, int repeats) { - long result; - long sum = 0; - Random randomGenerator = new Random(); - - for (int i = 0; i < elements; i++) { - list.add(i); - } - - for (int k = 0; k < repeats; k++) { - - long start = System.nanoTime(); - - list.get(randomGenerator.nextInt(elements)); - - long finish = System.nanoTime(); - long duration = finish - start; - sum += duration; - } - list.clear(); - - result = sum / repeats; - return result; - } - - public static long testRemove(List list, int elements, int repeats) { - long result; - long sum = 0; - Random randomGenerator = new Random(); - - for (int i = 0; i < elements; i++) { - list.add(i); - } - - for (int k = 0; k < repeats; k++) { - long start = System.nanoTime(); - - list.remove(randomGenerator.nextInt(elements / 2)); - - long finish = System.nanoTime(); - long duration = finish - start; - sum += duration; - } - list.clear(); - - result = sum / repeats; - return result; - } - - public static long testContains(List list, int elements, int repeats) { - long result; - long sum = 0; - Random randomGenerator = new Random(); - - for (int i = 0; i < elements; i++) { - list.add(i); - } - - for (int k = 0; k < repeats; k++) { - long start = System.nanoTime(); - - list.contains(randomGenerator.nextInt(2 * elements)); - - long finish = System.nanoTime(); - long duration = finish - start; - sum += duration; - } - list.clear(); - - result = sum / repeats; - return result; - } - - public static long testPopulate(List list, int elements, int repeats) { - long result; - long sum = 0; - - for (int k = 0; k < repeats; k++) { - - long start = System.nanoTime(); - - for (int i = 0; i < elements; i++) { - list.add(i); - } - - long finish = System.nanoTime(); - long duration = finish - start; - sum += duration; - - list.clear(); - } - - result = sum / repeats; - return result; - } - - public static long testIteratorAdd(List list, int elements, int repeats) { - long result; - long sum = 0; - Random randomGenerator = new Random(); - - for (int i = 0; i < elements; i++) { - list.add(i); - } - - ListIterator iter = list.listIterator(); - - int k = 0; - while (iter.hasNext() && k < repeats) { - - long start = System.nanoTime(); - - iter.add(randomGenerator.nextInt(elements)); - iter.next(); - - long finish = System.nanoTime(); - long duration = finish - start; - sum += duration; - - k++; - } - list.clear(); - - result = sum / repeats; - return result; - } - - public static long testIteratorRemove(List list, int elements, int repeats) { - long result; - long sum = 0; - - - for (int i = 0; i < elements; i++) { - list.add(i); - } - - for (int k = 0; k < repeats; k++) { - ListIterator iter = list.listIterator(); - while (iter.hasNext() && k < repeats) { - - long start = System.nanoTime(); - - iter.next(); - iter.remove(); - - long finish = System.nanoTime(); - long duration = finish - start; - sum += duration; - } - } - list.clear(); - - result = sum / repeats; - return result; - } -} \ No newline at end of file diff --git a/src/fff/Runner.java b/src/fff/Runner.java deleted file mode 100644 index 4650577..0000000 --- a/src/fff/Runner.java +++ /dev/null @@ -1,13 +0,0 @@ -package fff; - -import java.io.File; -import java.io.IOException; - -public class Runner { - public static void main(String[] args) throws IOException { - - String[] PerformanceResults = TableConstructionAndFormatting.createAndFormateTable(); - IOUtil.printToConsole(PerformanceResults); - IOUtil.saveToFile(PerformanceResults, "result.txt"); - } -} diff --git a/src/fff/SetTester.java b/src/fff/SetTester.java deleted file mode 100644 index a9e301d..0000000 --- a/src/fff/SetTester.java +++ /dev/null @@ -1,100 +0,0 @@ -package fff; -import java.math.BigInteger; -import java.util.Random; -import java.util.Set; - -public class SetTester { - public static long testAdd(Set set, int elements, int repeats) { - long result; - long sum = 0; - - for (int i = 0; i < elements; i++) { - set.add(i); - } - - for (int k = elements + 1; k < elements + repeats; k++) { - long start = System.nanoTime(); - - set.add(k); - - long finish = System.nanoTime(); - long duration = finish - start; - sum +=duration; - } - - set.clear(); - - result = sum / repeats; - return result; - } - - public static long testRemove(Set set, int elements, int repeats) { - long result; - long sum = 0; - Random randomGenerator = new Random(); - - for (int i = 0; i < elements; i++) { - set.add(i); - } - - for (int k = 0; k < repeats; k++) { - long start = System.nanoTime(); - - set.remove(randomGenerator.nextInt(elements)); - - long finish = System.nanoTime(); - long duration = finish - start; - sum += duration; - } - set.clear(); - - result = sum / repeats; - return result; - } - - public static long testContains(Set set, int elements, int repeats) { - long result; - long sum = 0; - Random randomGenerator = new Random(); - - for (int i = 0; i < elements; i++) { - set.add(i); - } - - for (int k = 0; k < repeats; k++) { - long start = System.nanoTime(); - - set.contains(randomGenerator.nextInt(2 * elements)); - - long finish = System.nanoTime(); - long duration = finish - start; - sum += duration; - } - set.clear(); - - result = sum / repeats; - return result; - } - - public static BigInteger testPopulate(Set set, int elements, int repeats) { - BigInteger result; - BigInteger sum = BigInteger.valueOf(0); - - for (int k = 0; k < repeats; k++) { - - long start = System.nanoTime(); - - for (int i = 0; i < elements; i++) { - set.add(i); - } - - long finish = System.nanoTime(); - BigInteger duration = BigInteger.valueOf(finish - start); - sum = sum.add(duration); - - set.clear(); - } - result = sum.divide(BigInteger.valueOf(repeats)); - return result; - } -} \ No newline at end of file diff --git a/src/fff/TableConstructionAndFormatting.java b/src/fff/TableConstructionAndFormatting.java deleted file mode 100644 index f6ff016..0000000 --- a/src/fff/TableConstructionAndFormatting.java +++ /dev/null @@ -1,85 +0,0 @@ -package fff; - -import java.io.*; -import java.util.*; - -public class TableConstructionAndFormatting { - - static List arrayList = new ArrayList<>(); - static List linkedList = new LinkedList<>(); - - static Set hashSet = new HashSet<>(); - static Set treeSet = new TreeSet<>(); - - - public static String[] createAndFormateTable() throws IOException { - String [] formatedResult = new String[5]; - Scanner input = new Scanner(System.in); - System.out.printf("Please select which table you want to print :%n %s %n %s %n %s %n", - " 1. 10000 elements", " 2. 100000 elements", " 3. 1000000 elements"); - int choise = input.nextInt(); - if (choise == 1) { - String header = TableConstructionAndFormatting.printHeader("10K"); - formatedResult[0] = header; - - String arrayListResult1 = String.format("%-18s %-6d %-6d %-9d %-11d %-11d %-15d %d%n", "ArrayList", ListTester.testAdd(arrayList, 10000, 100), ListTester.testGet(arrayList, 10000, 100), ListTester.testRemove(arrayList, 10000, 100), ListTester.testContains(arrayList, 10000, 100), ListTester.testPopulate(arrayList, 10000, 100), ListTester.testIteratorAdd(arrayList, 10000, 100), ListTester.testIteratorRemove(arrayList, 10000, 100)); - formatedResult[1] = arrayListResult1; - - String linkedListResult1 = String.format("%-18s %-6d %-6d %-9d %-11d %-11d %-15d %d%n", "LinkedList", ListTester.testAdd(linkedList, 10000, 100), ListTester.testGet(linkedList, 10000, 100), ListTester.testRemove(linkedList, 10000, 100), ListTester.testContains(linkedList, 10000, 100), ListTester.testPopulate(linkedList, 10000, 100), ListTester.testIteratorAdd(linkedList, 10000, 100), ListTester.testIteratorRemove(linkedList, 10000, 100)); - formatedResult[2] = linkedListResult1; - - String hashSetResult1 = String.format("%-18s %-6d %-6s %-9d %-11d %-11d %-15s %s%n", "HashSet", SetTester.testAdd(hashSet, 10000, 100), "n/a ", SetTester.testRemove(hashSet, 10000, 100), SetTester.testContains(hashSet, 10000, 100), SetTester.testPopulate(hashSet, 10000, 100), "n/a ", "n/a "); - formatedResult[3] = hashSetResult1; - - String treeSetResult1 = String.format("%-18s %-6d %-6s %-9d %-11d %-11d %-15s %s%n%n%n%n", "TreeSet", SetTester.testAdd(treeSet, 10000, 100), "n/a ", SetTester.testRemove(treeSet, 10000, 100), SetTester.testContains(treeSet, 10000, 100), SetTester.testPopulate(treeSet, 10000, 100), "n/a ", "n/a "); - formatedResult[4] = treeSetResult1; - - - } else if (choise == 2) { - String header = TableConstructionAndFormatting.printHeader("100K"); - formatedResult[0] = header; - - String arrayListResult2 = String.format("%-18s %-6d %-6d %-9d %-11d %-11d %-15d %d%n", "ArrayList", ListTester.testAdd(arrayList, 100000, 100), ListTester.testGet(arrayList, 100000, 100), ListTester.testRemove(arrayList, 100000, 100), ListTester.testContains(arrayList, 100000, 100), ListTester.testPopulate(arrayList, 100000, 100), ListTester.testIteratorAdd(arrayList, 100000, 100), ListTester.testIteratorRemove(arrayList, 100000, 100)); - formatedResult[1] = arrayListResult2; - - String linkedListResult2 = String.format("%-18s %-6d %-6d %-9d %-11d %-11d %-15d %d%n", "LinkedList", ListTester.testAdd(linkedList, 100000, 100), ListTester.testGet(linkedList, 100000, 100), ListTester.testRemove(linkedList, 100000, 100), ListTester.testContains(linkedList, 100000, 100), ListTester.testPopulate(linkedList, 100000, 100), ListTester.testIteratorAdd(linkedList, 100000, 100), ListTester.testIteratorRemove(linkedList, 100000, 100)); - formatedResult[2] = linkedListResult2; - - String hashSetResult2 = String.format("%-18s %-6d %-6s %-9d %-11d %-11d %-15s %s%n", "HashSet", SetTester.testAdd(hashSet, 100000, 100), "n/a ", SetTester.testRemove(hashSet, 100000, 100), SetTester.testContains(hashSet, 100000, 100), SetTester.testPopulate(hashSet, 100000, 100), "n/a ", "n/a "); - formatedResult[3] = hashSetResult2; - - String treeSetResult2 = String.format("%-18s %-6d %-6s %-9d %-11d %-11d %-15s %s%n%n%n%n", "TreeSet", SetTester.testAdd(treeSet, 100000, 100), "n/a ", SetTester.testRemove(treeSet, 100000, 100), SetTester.testContains(treeSet, 100000, 100), SetTester.testPopulate(treeSet, 100000, 100), "n/a ", "n/a "); - formatedResult[4] = treeSetResult2; - - - } else if (choise == 3) { - String header = TableConstructionAndFormatting.printHeader("1000K"); - formatedResult[0] = header; - - String arrayListResult3 = String.format("%-18s %-9d %-9d %-12d %-14d %-14d %-18d %d%n", "ArrayList", ListTester.testAdd(arrayList, 1000000, 100), ListTester.testGet(arrayList, 1000000, 100), ListTester.testRemove(arrayList, 1000000, 100), ListTester.testContains(arrayList, 1000000, 100), ListTester.testPopulate(arrayList, 1000000, 100), ListTester.testIteratorAdd(arrayList, 1000000, 100), ListTester.testIteratorRemove(arrayList, 1000000, 100)); - formatedResult[1] = arrayListResult3; - - String linkedListResult3 = String.format("%-18s %-9d %-9d %-12d %-14d %-14d %-18d %d%n", "LinkedList", ListTester.testAdd(linkedList, 1000000, 100), ListTester.testGet(linkedList, 1000000, 100), ListTester.testRemove(linkedList, 1000000, 100), ListTester.testContains(linkedList, 1000000, 100), ListTester.testPopulate(linkedList, 1000000, 100), ListTester.testIteratorAdd(linkedList, 1000000, 100), ListTester.testIteratorRemove(linkedList, 1000000, 100)); - formatedResult[2] = linkedListResult3; - - String hashSetResult3 = String.format("%-18s %-9d %-9s %-12d %-14d %-14d %-18s %s%n", "HashSet", SetTester.testAdd(hashSet, 1000000, 100), "n/a ", SetTester.testRemove(hashSet, 1000000, 100), SetTester.testContains(hashSet, 1000000, 100), SetTester.testPopulate(hashSet, 1000000, 100), "n/a ", "n/a "); - formatedResult[3] = hashSetResult3; - - String treeSetResult3 = String.format("%-18s %-9d %-9s %-12d %-14d %-14d %-18s %s%n%n%n%n", "TreeSet", SetTester.testAdd(treeSet, 1000000, 100), "n/a ", SetTester.testRemove(treeSet, 1000000, 100), SetTester.testContains(treeSet, 1000000, 100), SetTester.testPopulate(treeSet, 1000000, 100), "n/a ", "n/a "); - formatedResult[4] = treeSetResult3; - - - } else { - throw new IllegalArgumentException("Invalid input! Input needs to be 1,2 or 3"); - } - return formatedResult; - } - - - private static String printHeader(String elements) { - - String header = String.format("%-18s %-6s %-6s %-9s %-11s %-11s %-15s %-15s%n %s%n%n","Collection type", "add", "get", "remove", "contains", "populate", "iterator.add", "iterator.remove", "(Results for " + elements + " elements in the collection)"); - - return header; - } -} diff --git a/src/module2_1/build.xml b/src/module2_1/build.xml new file mode 100644 index 0000000..faf3103 --- /dev/null +++ b/src/module2_1/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/module2_2/ExecutorImpl.java b/src/module2_2/ExecutorImpl.java index f9ff37b..3b76f91 100644 --- a/src/module2_2/ExecutorImpl.java +++ b/src/module2_2/ExecutorImpl.java @@ -4,10 +4,10 @@ import java.util.List; public class ExecutorImpl implements Executor { - private List> tasks; + private List> tasks = new ArrayList<>(); - private ArrayList validResults; - private ArrayList invalidResults; + private ArrayList validResults = new ArrayList<>(); + private ArrayList invalidResults = new ArrayList<>(); boolean isExecuteActivate; diff --git a/src/module2_2/GenericsTestDrive.java b/src/module2_2/Run.java similarity index 97% rename from src/module2_2/GenericsTestDrive.java rename to src/module2_2/Run.java index 271a4f0..3ff1908 100644 --- a/src/module2_2/GenericsTestDrive.java +++ b/src/module2_2/Run.java @@ -1,6 +1,6 @@ package module2_2; -public class GenericsTestDrive { +public class Run { public static void main(String[] args) { Task[] intTasks = new IntegerTask[5]; intTasks[0] = new IntegerTask(25); diff --git a/src/module2_2/build.xml b/src/module2_2/build.xml new file mode 100644 index 0000000..79caa8c --- /dev/null +++ b/src/module2_2/build.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/module2_3_1/build.xml b/src/module2_3_1/build.xml new file mode 100644 index 0000000..3edc153 --- /dev/null +++ b/src/module2_3_1/build.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/module2_3_2/build.xml b/src/module2_3_2/build.xml new file mode 100644 index 0000000..d666b80 --- /dev/null +++ b/src/module2_3_2/build.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/some/Test.java b/src/some/Test.java new file mode 100644 index 0000000..b5d7ab0 --- /dev/null +++ b/src/some/Test.java @@ -0,0 +1,17 @@ +package some; + + +import java.util.Random; +import java.util.concurrent.*; +import java.util.stream.IntStream; + +public class Test { + public static void main(String[] args) { +new Test().test(); + } + public void test () { + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + System.out.println("Task scheduled"); + executorService.scheduleAtFixedRate(() -> System.out.println("Task executed"), 1, 1, TimeUnit.SECONDS); + } + } diff --git a/src/test/module2_2/ExecutorImplTest.java b/src/test/module2_2/ExecutorImplTest.java new file mode 100644 index 0000000..f5bc2d6 --- /dev/null +++ b/src/test/module2_2/ExecutorImplTest.java @@ -0,0 +1,30 @@ +package test.module2_2; + +import module2_2.*; +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ExecutorImplTest { + + + @Test + public void testExecuteWithoutValidator() throws Exception { + ExecutorImpl executor = new ExecutorImpl<>(); + Task[] intTasks = new IntegerTask[1]; + intTasks[0] = new IntegerTask(2); + Executor numberExecutor = new ExecutorImpl<>(); + + for (Task intTask : intTasks) { + numberExecutor.addTask(intTask); + } + + numberExecutor.addTask(new LongTask(10L), new NumberValidator()); + numberExecutor.addTask(new DoubleTask(39.2389)); // if number after point % 2 == 0 than doubleNumber is ValidResult + + Assert.assertEquals(numberExecutor.getValidResults().get(1), Integer.valueOf(0)); + } + + +} \ No newline at end of file