├── .gitignore ├── 12-SmallProject ├── ref │ ├── 2048 │ │ ├── a │ │ ├── src │ │ │ └── com │ │ │ │ └── hackbulgaria │ │ │ │ └── corejava │ │ │ │ └── game2048 │ │ │ │ ├── Random.java │ │ │ │ ├── Main.java │ │ │ │ ├── GlobalRandom.java │ │ │ │ ├── ConsoleVisualizer.java │ │ │ │ └── GameBoard.java │ │ ├── .gitignore │ │ ├── .classpath │ │ ├── README.md │ │ ├── build.xml │ │ ├── .project │ │ ├── .externalToolBuilders │ │ │ └── New_Builder.launch │ │ └── LICENSE │ └── ConsoleTicTacToe │ │ ├── src │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ └── tictactoe │ │ │ ├── GameState.java │ │ │ ├── UserInputFetcher.java │ │ │ ├── UserInput.java │ │ │ ├── ConsoleVisualizer.java │ │ │ ├── Main.java │ │ │ ├── ConsoleInputFetcher.java │ │ │ └── GameBoard.java │ │ ├── bin │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ └── tictactoe │ │ │ ├── Main.class │ │ │ ├── GameBoard.class │ │ │ ├── GameState.class │ │ │ ├── UserInput.class │ │ │ ├── UserInputFetcher.class │ │ │ ├── ConsoleVisualizer.class │ │ │ ├── ConsoleInputFetcher.class │ │ │ └── UserInput$InputType.class │ │ ├── .classpath │ │ ├── .project │ │ └── .settings │ │ └── org.eclipse.jdt.core.prefs └── problems.md ├── 18-ThreadsParallel ├── WebCrawler │ ├── .attach_pid5957 │ ├── bin │ │ ├── Main.class │ │ ├── WebCrawler.class │ │ ├── RESTConsumer$1.class │ │ └── RESTConsumer.class │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── target │ │ └── classes │ │ │ ├── META-INF │ │ │ ├── MANIFEST.MF │ │ │ └── maven │ │ │ │ └── URLvsURI │ │ │ │ └── URLvsURI │ │ │ │ ├── pom.properties │ │ │ │ └── pom.xml │ │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ ├── Main.class │ │ │ └── WebCrawler.class │ ├── src │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ ├── Main.java │ │ │ └── WebCrawler.java │ ├── .project │ ├── .classpath │ └── pom.xml ├── materials.md └── problems.md ├── 02-DebuggingFun ├── DebuggingFun │ ├── bin │ │ └── .gitignore │ ├── libs │ │ └── commons-io-2.4.jar │ ├── src │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ ├── FaultyProblem1.java │ │ │ ├── FaultyProblem2.java │ │ │ ├── FaultyProblem6.java │ │ │ ├── FaultyProblem5.java │ │ │ ├── FaultyProblem3.java │ │ │ ├── FaultyProblem7.java │ │ │ ├── FaultyProblem4.java │ │ │ └── Utils.java │ ├── .project │ ├── test │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ ├── FaultyProblem5Test.java │ │ │ ├── FaultyProblem6Test.java │ │ │ ├── FaultyProblem3Test.java │ │ │ ├── FaultyProblem7Test.java │ │ │ ├── FaultyProblem2Test.java │ │ │ ├── FaultyProblem1Test.java │ │ │ └── FaultyProblem4Test.java │ ├── .classpath │ └── .settings │ │ └── org.eclipse.jdt.core.prefs ├── agenda2.md ├── pre2.md └── problems2.md ├── 11-OOP2 ├── references │ └── ConsoleTicTacToe │ │ ├── .gitignore │ │ └── .project ├── materials.md └── problems.md ├── 07-Files1 ├── testData.zip ├── pre.md └── problems.md ├── 15-Networking3 ├── jdom-1.1.3.zip ├── rome-1.0.jar ├── materials.md └── problems.md ├── 17-JavaTooling ├── links.md └── problems.md ├── Extra-JDBCvsORM └── Java_database_presentation.1.ppt ├── 10-StructuredData ├── testData │ └── links.md ├── materials.md ├── pre.md └── problems.md ├── 01-TypesArraysStrings ├── Project1 │ ├── bin │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ ├── Problems2.class │ │ │ ├── Problems2Impl.class │ │ │ ├── Problems2Factory.class │ │ │ └── tests │ │ │ └── Problems2Tests.class │ ├── src │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ ├── Problems2Factory.java │ │ │ ├── Problems2.java │ │ │ └── Problems2Impl.java │ ├── .classpath │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ └── test │ │ └── com │ │ └── hackbulgaria │ │ └── corejava │ │ └── tests │ │ └── Problems2Tests.java ├── agenda1.md ├── pre1.md └── problems1.md ├── 19-ThreadsConcurrent ├── WaitNotifyMechanism │ ├── bin │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava │ │ │ ├── WaitNotifyMechanism.class │ │ │ ├── WaitNotifyMechanism$1.class │ │ │ └── WaitNotifyMechanism$2.class │ ├── .classpath │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ └── src │ │ └── com │ │ └── hackbulgaria │ │ └── corejava │ │ └── WaitNotifyMechanism.java └── problems.md ├── 13-Networking1 ├── materials.md └── problems.md ├── 14-Networking2 ├── materials.md └── problems.md ├── 16-Generics2 ├── materials.md └── problems.md ├── attachSources.md ├── 03-OOP1 ├── agenda3.md ├── pre3.md └── problems3.md ├── 05-Exceptions ├── pre5.md └── problems5.md ├── 06-Exam1 ├── solution │ ├── Main.java │ ├── DateLogger.java │ ├── ListUtils.java │ └── Logger.java └── tasks.md ├── courseProgress.md ├── 04-CollectionsAndGenerics1 ├── pre4.md └── problems4.md ├── 00-JavaPlatformIntroduction ├── agenda0.md └── problems0.md ├── README.md ├── 000-StartHere └── start-here.md ├── 08-WorkingWithLibraries └── problems.md └── 20-Exam2 └── problems.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.*~ 2 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/a: -------------------------------------------------------------------------------- 1 | babababaa 2 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/.attach_pid5957: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/bin/.gitignore: -------------------------------------------------------------------------------- 1 | /com 2 | -------------------------------------------------------------------------------- /11-OOP2/references/ConsoleTicTacToe/.gitignore: -------------------------------------------------------------------------------- 1 | /bin 2 | -------------------------------------------------------------------------------- /07-Files1/testData.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/07-Files1/testData.zip -------------------------------------------------------------------------------- /15-Networking3/jdom-1.1.3.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/15-Networking3/jdom-1.1.3.zip -------------------------------------------------------------------------------- /15-Networking3/rome-1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/15-Networking3/rome-1.0.jar -------------------------------------------------------------------------------- /17-JavaTooling/links.md: -------------------------------------------------------------------------------- 1 | *mvn site* 2 | https://www.youtube.com/watch?feature=player_detailpage&v=ZnPkpwrj2E8#t=341 3 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/bin/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/18-ThreadsParallel/WebCrawler/bin/Main.class -------------------------------------------------------------------------------- /Extra-JDBCvsORM/Java_database_presentation.1.ppt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/Extra-JDBCvsORM/Java_database_presentation.1.ppt -------------------------------------------------------------------------------- /10-StructuredData/testData/links.md: -------------------------------------------------------------------------------- 1 | *Latest stub articles from wikipedia* 2 | http://dumps.wikimedia.org/metawiki/latest/metawiki-latest-stub-articles.xml.gz 3 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/bin/WebCrawler.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/18-ThreadsParallel/WebCrawler/bin/WebCrawler.class -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/libs/commons-io-2.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/02-DebuggingFun/DebuggingFun/libs/commons-io-2.4.jar -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/bin/RESTConsumer$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/18-ThreadsParallel/WebCrawler/bin/RESTConsumer$1.class -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/bin/RESTConsumer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/18-ThreadsParallel/WebCrawler/bin/RESTConsumer.class -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/target/classes/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Built-By: georgi 3 | Build-Jdk: 1.7.0_55 4 | Created-By: Maven Integration for Eclipse 5 | 6 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/bin/com/hackbulgaria/corejava/Problems2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/01-TypesArraysStrings/Project1/bin/com/hackbulgaria/corejava/Problems2.class -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/src/com/hackbulgaria/corejava/game2048/Random.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.game2048; 2 | public interface Random { 3 | int nextInt(int n); 4 | boolean nextBoolean(); 5 | } 6 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/bin/com/hackbulgaria/corejava/Problems2Impl.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/01-TypesArraysStrings/Project1/bin/com/hackbulgaria/corejava/Problems2Impl.class -------------------------------------------------------------------------------- /02-DebuggingFun/agenda2.md: -------------------------------------------------------------------------------- 1 | - A little recap on our previous meetings 2 | - How to debug in Eclipse 3 | - Debugging problems 4 | - Finish all String problems 5 | - Declaring (static) methods 6 | - Introduction to JUnit 7 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/target/classes/com/hackbulgaria/corejava/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/18-ThreadsParallel/WebCrawler/target/classes/com/hackbulgaria/corejava/Main.class -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/bin/com/hackbulgaria/corejava/Problems2Factory.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/01-TypesArraysStrings/Project1/bin/com/hackbulgaria/corejava/Problems2Factory.class -------------------------------------------------------------------------------- /02-DebuggingFun/pre2.md: -------------------------------------------------------------------------------- 1 | *On Enums in Java* 2 | http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html 3 | 4 | *A video for Junit and Eclipse* 5 | http://www.intertech.com/Blog/express-junit-training-video/ -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/src/com/hackbulgaria/corejava/tictactoe/GameState.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tictactoe; 2 | 3 | public enum GameState { 4 | PLAYING, PLAYER_1_WON, PLAYER_2_WON, DRAW 5 | } 6 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/bin/com/hackbulgaria/corejava/tests/Problems2Tests.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/01-TypesArraysStrings/Project1/bin/com/hackbulgaria/corejava/tests/Problems2Tests.class -------------------------------------------------------------------------------- /10-StructuredData/materials.md: -------------------------------------------------------------------------------- 1 | JAXB and annotations 2 | http://www.vogella.com/tutorials/JAXB/article.html 3 | 4 | Jettison/JAXB integration 5 | http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison-namespace.html 6 | 7 | 8 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/Main.class -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/target/classes/com/hackbulgaria/corejava/WebCrawler.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/18-ThreadsParallel/WebCrawler/target/classes/com/hackbulgaria/corejava/WebCrawler.class -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/src/com/hackbulgaria/corejava/tictactoe/UserInputFetcher.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tictactoe; 2 | 3 | 4 | public interface UserInputFetcher { 5 | public UserInput fetchUserInput(); 6 | } 7 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/GameBoard.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/GameBoard.class -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/GameState.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/GameState.class -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/UserInput.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/UserInput.class -------------------------------------------------------------------------------- /19-ThreadsConcurrent/WaitNotifyMechanism/bin/com/hackbulgaria/corejava/WaitNotifyMechanism.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/19-ThreadsConcurrent/WaitNotifyMechanism/bin/com/hackbulgaria/corejava/WaitNotifyMechanism.class -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/UserInputFetcher.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/UserInputFetcher.class -------------------------------------------------------------------------------- /19-ThreadsConcurrent/WaitNotifyMechanism/bin/com/hackbulgaria/corejava/WaitNotifyMechanism$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/19-ThreadsConcurrent/WaitNotifyMechanism/bin/com/hackbulgaria/corejava/WaitNotifyMechanism$1.class -------------------------------------------------------------------------------- /19-ThreadsConcurrent/WaitNotifyMechanism/bin/com/hackbulgaria/corejava/WaitNotifyMechanism$2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/19-ThreadsConcurrent/WaitNotifyMechanism/bin/com/hackbulgaria/corejava/WaitNotifyMechanism$2.class -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/ConsoleVisualizer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/ConsoleVisualizer.class -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/ConsoleInputFetcher.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/ConsoleInputFetcher.class -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/UserInput$InputType.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Core-Java-1/HEAD/12-SmallProject/ref/ConsoleTicTacToe/bin/com/hackbulgaria/corejava/tictactoe/UserInput$InputType.class -------------------------------------------------------------------------------- /15-Networking3/materials.md: -------------------------------------------------------------------------------- 1 | *What is a servlet according to Oracle* 2 | http://docs.oracle.com/javaee/5/tutorial/doc/bnafe.html 3 | 4 | *And now read a normal answer from stack overflow* 5 | http://stackoverflow.com/questions/7213541/what-is-java-servlet 6 | 7 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/src/com/hackbulgaria/corejava/game2048/Main.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.game2048; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | ConsoleVisualizer visualizer = new ConsoleVisualizer(new GameBoard()); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/agenda1.md: -------------------------------------------------------------------------------- 1 | 2 | ### Agenda #2 ### 3 | -Welcome to Eclipse 4 | -Coding style format import 5 | -Import Preferences and Quick Keys setup (Refactor Menu, Create getter, setter) 6 | -Hello world from Eclipse 7 | -Packages,Eclipse Views 8 | -Primitive types, arrays 9 | -if/for/while, switch 10 | -------------------------------------------------------------------------------- /13-Networking1/materials.md: -------------------------------------------------------------------------------- 1 | *InetAddress class in java* 2 | http://www.codeproject.com/Tips/553321/InetAddress-Java-Class 3 | 4 | *Working with urls* 5 | http://docs.oracle.com/javase/tutorial/networking/urls/index.html 6 | 7 | *All abouts sockets* 8 | http://docs.oracle.com/javase/tutorial/networking/sockets/ 9 | -------------------------------------------------------------------------------- /14-Networking2/materials.md: -------------------------------------------------------------------------------- 1 | *URL vs URI* 2 | http://stackoverflow.com/questions/176264/whats-the-difference-between-a-uri-and-a-url 3 | 4 | *Reading directly from a URL* 5 | http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html 6 | 7 | *Apache HTTP Client* 8 | http://hc.apache.org/httpclient-3.x/tutorial.html 9 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/target/classes/META-INF/maven/URLvsURI/URLvsURI/pom.properties: -------------------------------------------------------------------------------- 1 | #Generated by Maven Integration for Eclipse 2 | #Wed Jul 30 19:32:34 EEST 2014 3 | version=0.0.1-SNAPSHOT 4 | groupId=URLvsURI 5 | m2e.projectName=WebCrawler 6 | m2e.projectLocation=/home/georgi/Dev/workspace/WebCrawler 7 | artifactId=URLvsURI 8 | -------------------------------------------------------------------------------- /16-Generics2/materials.md: -------------------------------------------------------------------------------- 1 | **Oracle's trail and example on generics** 2 | http://docs.oracle.com/javase/tutorial/java/generics/index.html 3 | 4 | **Oracle's trail on annotations** 5 | http://docs.oracle.com/javase/tutorial/java/annotations/index.html 6 | 7 | **MKYoung custom annotation tutorial** 8 | http://www.mkyong.com/java/java-custom-annotations-example/ 9 | -------------------------------------------------------------------------------- /19-ThreadsConcurrent/WaitNotifyMechanism/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem1.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem1 { 4 | public long getLargestPalindrome(long N) { 5 | N--; 6 | if (Utils.isPalindrome(N)) { 7 | return N; 8 | } else { 9 | return getLargestPalindrome(N-1); 10 | } 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem2.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem2 { 4 | 5 | public int getNearestPowerOf2(int x) { 6 | int i = 1; 7 | while (x != 1) { 8 | x /= 2; 9 | i++; 10 | } 11 | 12 | return (int) Math.pow(2, i); 13 | } 14 | 15 | 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /attachSources.md: -------------------------------------------------------------------------------- 1 | ###Attaching JDK 7 sources to Eclipse### 2 | 3 | 1. First, download the sources zip from 4 | http://www.java.net/download/openjdk/jdk7/promoted/b147/openjdk-7-fcs-src-b147-27_jun_2011.zip 5 | 6 | 2. Window -> Prefernces -> Java -> Installed JRES. 7 | Select your active one and click 'Edit' 8 | Then choose 'rt.jar' from the list below. 9 | Click on 'Source Attachment'. 10 | Point Eclipse to your .zip file 11 | -------------------------------------------------------------------------------- /10-StructuredData/pre.md: -------------------------------------------------------------------------------- 1 | What is XML? The tutorial at W3Schools: 2 | http://www.w3schools.com/xml/default.asp 3 | 4 | What is JSON? The tutorial at W3Schools: 5 | http://www.w3schools.com/json/ 6 | 7 | Comparison between the two: 8 | http://stackoverflow.com/questions/2636245/choosing-between-json-and-xml 9 | http://stackoverflow.com/questions/15154049/xml-vs-json-which-one-is-better-for-storing-small-chunk-of-data 10 | -------------------------------------------------------------------------------- /11-OOP2/materials.md: -------------------------------------------------------------------------------- 1 | The KISS principle : ) 2 | http://en.wikipedia.org/wiki/KISS_principle 3 | 4 | DRY code vs WET code 5 | http://en.wikipedia.org/wiki/Don%27t_repeat_yourself 6 | 7 | SOLID acronym exaplanation 8 | http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29 9 | 10 | StackOveflow on high cohesion, loose coupling and decoupling 11 | http://stackoverflow.com/questions/3085285/cohesion-coupling 12 | -------------------------------------------------------------------------------- /03-OOP1/agenda3.md: -------------------------------------------------------------------------------- 1 | - Everything is OOP! 2 | - What is a class? What is an object? 3 | - Method overloading, method overriding, virtual functions? 4 | - State/behaviour 5 | - Data Encapsulation, Subtype polymorphism, Liskov Principle 6 | - Object, equals, hashCode, getClass, toString, wait, notify, notifyAll 7 | - Constructors, on object construction in java, what happens on new()... 8 | - Subtyping (extending class) 9 | - interfaces/abstract classes -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/README.md: -------------------------------------------------------------------------------- 1 | 2048 2 | ==== 3 | 4 | 2048 game implemented in Java, in order to test whether it is good homework @ Core-Java-1 course. 5 | Idea based on http://gabrielecirulli.github.io/2048/ 6 | 7 | ### Running the game 8 | Just download the `build/2048.jar` jar file, and run `java -jar ` 9 | Left arrow for moving everything to the left 10 | Right arrow for moving everything to the right, etc. 11 | -------------------------------------------------------------------------------- /03-OOP1/pre3.md: -------------------------------------------------------------------------------- 1 | *On OOP in General* 2 | https://www.youtube.com/watch?v=lbXsrHGhBAU 3 | 4 | *OOP Trail @ Oracle* 5 | http://docs.oracle.com/javase/tutorial/java/concepts/index.html 6 | 7 | *Class and Objects @ Oracle (Those pages are actually Sun's property!)* 8 | http://docs.oracle.com/javase/tutorial/java/javaOO/ 9 | 10 | *More on Classes and objects* 11 | http://www.javaworld.com/article/2075202/core-java/object-oriented-language-basics-part-1.html?page=1 -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/src/com/hackbulgaria/corejava/Problems2Factory.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class Problems2Factory { 4 | String OATH_TOKEN = "THIS IS MY DEAR PASSWORD"; 5 | 6 | public static Problems2 createProblems2Instance() { 7 | return new Problems2Impl(); 8 | } 9 | 10 | public static void main(String[] args) { 11 | } 12 | 13 | public static void meh(Integer k) { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /05-Exceptions/pre5.md: -------------------------------------------------------------------------------- 1 | *Exceptions hierarch in Java* 2 | http://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml 3 | 4 | *Try/catch/finally example* 5 | http://www.tutorialspoint.com/java/java_exceptions.htm 6 | 7 | *Try with resources in Java 7* 8 | http://www.mkyong.com/java/try-with-resources-example-in-jdk-7/ 9 | 10 | *Overriding methods with Exceptions in java* 11 | http://stackoverflow.com/questions/5875414/method-overriding-and-exceptions 12 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem6.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem6 { 4 | public static long pow(int a, int b) { 5 | if (b == 1){ 6 | return a; 7 | } 8 | if (b % 2 == 1) { 9 | return a * pow(a, b - 1); 10 | } else { 11 | long power = pow(a, b / 2); 12 | return power * power; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/src/com/hackbulgaria/corejava/game2048/GlobalRandom.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.game2048; 2 | public enum GlobalRandom implements Random { 3 | INSTANCE; 4 | 5 | private final java.util.Random random = new java.util.Random(12345); 6 | 7 | @Override 8 | public int nextInt(int n) { 9 | return random.nextInt(n); 10 | } 11 | 12 | @Override 13 | public boolean nextBoolean() { 14 | return random.nextBoolean(); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | DebuggingFun 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /18-ThreadsParallel/materials.md: -------------------------------------------------------------------------------- 1 | *Oracle's concurency trail* 2 | http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html 3 | 4 | *Multithreading example* 5 | http://www.tutorialspoint.com/java/java_multithreading.htm 6 | 7 | *Lars Vogel's threading tutorial* 8 | http://www.vogella.com/tutorials/JavaConcurrency/article.html#forkjoin 9 | 10 | *Paralel execution with Executor, Future and Completion Service* 11 | http://www.javapractices.com/topic/TopicAction.do?Id=247 12 | -------------------------------------------------------------------------------- /11-OOP2/references/ConsoleTicTacToe/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | ConsoleTicTacToe 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | ConsoleTicTacToe 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /19-ThreadsConcurrent/WaitNotifyMechanism/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | WaitNotifyMechanism 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem5Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class FaultyProblem5Test { 8 | 9 | @Test 10 | public void test() { 11 | assertEquals(1, FaultyProblem5.kthFac(0, 1)); 12 | 13 | assertEquals(2, FaultyProblem5.kthFac(1, 2)); 14 | 15 | assertEquals(720, FaultyProblem5.kthFac(2, 3)); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem5.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | 4 | public class FaultyProblem5 { 5 | public static long kthFac(int k, int n) { 6 | long res = 1; 7 | long limit = n; 8 | for (long i = 2; i <= limit; i++) { 9 | res *= i; 10 | if (i == limit && k > 0) { 11 | k--; 12 | limit = res; 13 | } 14 | } 15 | return res; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem6Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class FaultyProblem6Test { 8 | 9 | @Test 10 | public void test() { 11 | assertEquals(1, FaultyProblem6.pow(1, 999999999)); 12 | assertEquals(8, FaultyProblem6.pow(2, 3)); 13 | assertEquals(16, FaultyProblem6.pow(2, 4)); 14 | assertEquals(1, FaultyProblem6.pow(4, 0)); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem3.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem3 { 4 | 5 | public String reverseEveryWordInString(String sentence){ 6 | String[] words = sentence.split(" "); 7 | for (String word: words){ 8 | sentence = sentence.replace(word, reverse(word)); 9 | } 10 | return sentence; 11 | } 12 | 13 | private CharSequence reverse(String word) { 14 | return Utils.reverseMe(word); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /06-Exam1/solution/Main.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.exam1; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | Logger logger = new Logger(); 6 | logger.log("This should get printed"); 7 | logger.log(4, "This should not get printed"); 8 | 9 | logger.log(1, "This is very important"); 10 | 11 | DateLogger dateLogger = new DateLogger(); 12 | dateLogger.log("prints everything, so I get printed"); 13 | 14 | dateLogger.setLevel(1); 15 | dateLogger.log(2,"won't get printed"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/src/com/hackbulgaria/corejava/Main.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.net.URISyntaxException; 6 | import java.util.concurrent.ExecutionException; 7 | 8 | public class Main { 9 | public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException, 10 | ExecutionException { 11 | WebCrawler crawler = new WebCrawler(); 12 | 13 | URI startLocation = new URI("http://9gag.com/"); 14 | URI result = crawler.crawl(startLocation, "junk"); 15 | System.out.println("result :" + result.toString()); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebCrawler 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.m2e.core.maven2Nature 21 | org.eclipse.jdt.core.javanature 22 | 23 | 24 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /19-ThreadsConcurrent/WaitNotifyMechanism/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /06-Exam1/solution/DateLogger.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.exam1; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | 6 | public class DateLogger extends Logger { 7 | private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("hh:mm:ss dd.mm.yyyy"); 8 | 9 | public DateLogger() { 10 | this(Integer.MAX_VALUE); 11 | } 12 | 13 | public DateLogger(int logLevel) { 14 | super(logLevel); 15 | } 16 | 17 | @Override 18 | protected void print(int msgLevel, String message) { 19 | String date = DATE_FORMAT.format(new Date()); 20 | System.out.print(String.format("|%s| ", date)); 21 | super.print(msgLevel, message); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 12 | org.eclipse.jdt.core.compiler.source=1.7 13 | -------------------------------------------------------------------------------- /courseProgress.md: -------------------------------------------------------------------------------- 1 | - ~~Java, javac, jar, PATH, classpath, Java's ecosystem~~ 2 | - ~~IDE's, Eclipse, Hello World~~ 3 | - ~~Linking and using libraries from Eclipse~~ 4 | - ~~Debugging (level 1)~~ 5 | - Debugging (level 2) 6 | - ~~Working with unit tests~~ 7 | - ~~Writing unit tests~~ 8 | - ~~OOP (level 1)~~ 9 | - ~~OOP (level 2)~~ 10 | - OOP (level 3) 11 | - ~~Collections and generics (level 1)~~ 12 | - ~~Collections and generics (level 2)~~ 13 | - ~~Working with Files~~ 14 | - ~~Defensive Programming~~ 15 | - ~~Working with XML and JSON~~ 16 | - ~~Network Programming~~ 17 | - ~~Multithreaded Programming~~ 18 | - Working with annotations 19 | - Ant 20 | - ~~Maven~~ 21 | - Regular Expressions 22 | - Advanced IDE usages Level 1 23 | - Advanced IDE usages Level 2 24 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem3Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | public class FaultyProblem3Test { 9 | 10 | private FaultyProblem3 faultyProblem3; 11 | 12 | @Before 13 | public void setUp() { 14 | this.faultyProblem3 = new FaultyProblem3(); 15 | } 16 | 17 | @Test 18 | public void test() { 19 | assertEquals("gnikrow", faultyProblem3.reverseEveryWordInString("working")); 20 | assertEquals("tahw dluoc", faultyProblem3.reverseEveryWordInString("what could")); 21 | assertEquals("si siht laer efil", faultyProblem3.reverseEveryWordInString("is this real life")); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /06-Exam1/solution/ListUtils.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.exam1; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class ListUtils { 8 | public static List reverse(List list) { 9 | ArrayList arrayList = new ArrayList(list); 10 | Collections.reverse(arrayList); 11 | return arrayList; 12 | } 13 | 14 | public static List sort(List list) { 15 | ArrayList arrayList = new ArrayList(list); 16 | Collections.sort(arrayList); 17 | return arrayList; 18 | } 19 | 20 | public static boolean isMonotonic(List list) { 21 | return list.equals(sort(list)) || list.equals(reverse(sort(list))); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/src/com/hackbulgaria/corejava/tictactoe/UserInput.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tictactoe; 2 | 3 | import java.awt.Point; 4 | 5 | public class UserInput { 6 | public enum InputType { 7 | NORMAL, QUIT, UNDO, REDO; 8 | } 9 | 10 | private static final Point INVALID_POINT = new Point(-1, -1); 11 | 12 | private final Point inputPoint; 13 | private final InputType type; 14 | 15 | public UserInput(int x, int y) { 16 | inputPoint = new Point(x, y); 17 | type = InputType.NORMAL; 18 | } 19 | 20 | public UserInput(InputType type) { 21 | inputPoint = INVALID_POINT; 22 | this.type = type; 23 | } 24 | 25 | public Point getPoint() { 26 | return inputPoint; 27 | } 28 | 29 | public InputType getType() { 30 | return this.type; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem7Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import org.junit.Test; 6 | 7 | public class FaultyProblem7Test { 8 | 9 | @Test 10 | public void test() { 11 | // Code code = new Code("System.out.println(\"Hello World\");"); 12 | // Utils.eval(code, "Eval"); 13 | 14 | assertEquals(2, FaultyProblem7.binarySearch(3, 1, 2, 3, 4, 5, 6, 7, 8)); 15 | assertEquals(7, FaultyProblem7.binarySearch(8, 1, 2, 3, 4, 5, 6, 7, 8)); 16 | assertEquals(0, FaultyProblem7.binarySearch(1, 1, 2, 3, 4, 5, 6, 7, 8)); 17 | assertEquals(-1, FaultyProblem7.binarySearch(9, 1, 2, 3, 4, 5, 6, 7, 8)); 18 | 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | 2048 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.ui.externaltools.ExternalToolBuilder 15 | full,incremental, 16 | 17 | 18 | LaunchConfigHandle 19 | <project>/.externalToolBuilders/New_Builder.launch 20 | 21 | 22 | 23 | 24 | 25 | org.eclipse.jdt.core.javanature 26 | 27 | 28 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem2Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | public class FaultyProblem2Test { 9 | 10 | private FaultyProblem2 faultyProblem2; 11 | 12 | @Before 13 | public void setUp() { 14 | this.faultyProblem2 = new FaultyProblem2(); 15 | } 16 | 17 | @Test 18 | public void test() { 19 | assertEquals(128, faultyProblem2.getNearestPowerOf2(129)); 20 | assertEquals(128, faultyProblem2.getNearestPowerOf2(240)); 21 | assertEquals(2, faultyProblem2.getNearestPowerOf2(2)); 22 | assertEquals(16, faultyProblem2.getNearestPowerOf2(20)); 23 | assertEquals(1, faultyProblem2.getNearestPowerOf2(1)); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /07-Files1/pre.md: -------------------------------------------------------------------------------- 1 | *Always close streams* 2 | http://www.javapractices.com/topic/TopicAction.do;jsessionid=8DC1E976F93832427DBF51B275870889?Id=8 3 | 4 | *try-with-resources recap* 5 | http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html 6 | 7 | *Buffered reading from File - java* 8 | http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/ 9 | 10 | *Buffered writing in File - java* 11 | http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/ 12 | 13 | *Class/Interface Index in java.io* 14 | http://docs.oracle.com/javase/7/docs/api/java/io/package-tree.html 15 | 16 | *Closeable's hierarchy (not quite, but well, sort of ...) in java* 17 | http://ttp.essex.ac.uk/images/examples/io_closeable/5.png 18 | 19 | *IO trail @ Oracle* 20 | http://docs.oracle.com/javase/tutorial/essential/io/index.html 21 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem1Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | public class FaultyProblem1Test { 9 | 10 | private FaultyProblem1 faultyProgram; 11 | 12 | @Before 13 | public void setUp(){ 14 | this.faultyProgram = new FaultyProblem1(); 15 | } 16 | 17 | //F5 -> IN! 18 | //F6 19 | // | 20 | // next line 21 | //F7 <-- out 22 | 23 | @Test 24 | public void test() { 25 | assertEquals(1, faultyProgram.getLargestPalindrome(2)); 26 | assertEquals(535, faultyProgram.getLargestPalindrome(544)); 27 | assertEquals(121, faultyProgram.getLargestPalindrome(126)); 28 | assertEquals(898, faultyProgram.getLargestPalindrome(908)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/src/com/hackbulgaria/corejava/tictactoe/ConsoleVisualizer.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tictactoe; 2 | 3 | public class ConsoleVisualizer { 4 | 5 | private final GameBoard gameBoard; 6 | 7 | public ConsoleVisualizer(GameBoard gameBoard) { 8 | this.gameBoard = gameBoard; 9 | } 10 | 11 | public void printGame() { 12 | final StringBuilder board = new StringBuilder(); 13 | for (int y = 0; y < GameBoard.BOARD_LENGTH; y++) { 14 | for (int x = 0; x < GameBoard.BOARD_LENGTH; x++) { 15 | if (gameBoard.isOwnedByP1(y, x)) { 16 | board.append("X"); 17 | } 18 | if (gameBoard.isOwnedByP2(y, x)) { 19 | board.append("O"); 20 | } else if (gameBoard.isEmpty(y, x)) { 21 | board.append("."); 22 | } 23 | } 24 | board.append(System.lineSeparator()); 25 | } 26 | System.out.println(board); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem7.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import java.lang.Thread.State; 4 | 5 | public class FaultyProblem7 { 6 | public static int binarySearch(int element, int... array) { 7 | // Utils.killMeIfIGetStuck(); 8 | 9 | int low = 0; 10 | int high = array.length - 1; 11 | 12 | int mid = (low + high) / 2; 13 | while (high - low > 1) { 14 | 15 | if (element == array[mid]) { 16 | return mid; 17 | } 18 | if (element < array[mid]) { 19 | high = mid; 20 | } else { 21 | low = mid; 22 | } 23 | } 24 | 25 | if (array[high] == element) 26 | return high; 27 | if (array[low] == element) 28 | return low; 29 | 30 | return -1; // not found 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/FaultyProblem4.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class FaultyProblem4 { 4 | public static boolean areEqual(Integer e, Integer k) { 5 | k++; 6 | k--; 7 | return e == k; 8 | } 9 | 10 | public static boolean areEqual(float a, float b) { 11 | return a == b; 12 | } 13 | 14 | /** 15 | * Return whether there is an index i, 16 | * such that a[i,a.length] equals b[i, a.length]; 17 | * @param a 18 | * @param b 19 | * @return 20 | */ 21 | public static boolean haveEqualSubstrings(String a, String b) { 22 | for (int i = 0; i < a.length(); i++) { 23 | String substringA = a.substring(i, a.length() - 1); 24 | String substringB = b.substring(i, a.length() - 1); 25 | if (substringA.equals(substringB)){ 26 | return true; 27 | } 28 | } 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/.externalToolBuilders/New_Builder.launch: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/src/com/hackbulgaria/corejava/tictactoe/Main.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tictactoe; 2 | 3 | import com.hackbulgaria.corejava.tictactoe.UserInput.InputType; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | UserInputFetcher inputFetcher = new ConsoleInputFetcher(); 8 | GameBoard gameBoard = new GameBoard(); 9 | ConsoleVisualizer visualizer = new ConsoleVisualizer(gameBoard); 10 | 11 | UserInput input; 12 | do { 13 | visualizer.printGame(); 14 | input = inputFetcher.fetchUserInput(); 15 | GameState gameState = gameBoard.play(input); 16 | if (gameState != GameState.PLAYING) { 17 | System.out.println(pickMessage(gameState)); 18 | return; 19 | } 20 | 21 | } while (input.getType() != InputType.QUIT); 22 | } 23 | 24 | private static String pickMessage(GameState gameState) { 25 | switch (gameState) { 26 | case PLAYER_1_WON: 27 | return "Player 1 won!"; 28 | case PLAYER_2_WON: 29 | return "Player 2 won!"; 30 | case DRAW: 31 | return "Its a draw!"; 32 | default: 33 | return ""; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | URLvsURI 4 | URLvsURI 5 | 0.0.1-SNAPSHOT 6 | 7 | src 8 | 9 | 10 | maven-compiler-plugin 11 | 3.1 12 | 13 | 1.7 14 | 1.7 15 | 16 | 17 | 18 | 19 | 20 | 21 | commons-io 22 | commons-io 23 | 20030203.000550 24 | 25 | 26 | org.apache.httpcomponents 27 | httpclient 28 | 4.3 29 | 30 | 31 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/target/classes/META-INF/maven/URLvsURI/URLvsURI/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | URLvsURI 4 | URLvsURI 5 | 0.0.1-SNAPSHOT 6 | 7 | src 8 | 9 | 10 | maven-compiler-plugin 11 | 3.1 12 | 13 | 1.7 14 | 1.7 15 | 16 | 17 | 18 | 19 | 20 | 21 | commons-io 22 | commons-io 23 | 20030203.000550 24 | 25 | 26 | org.apache.httpcomponents 27 | httpclient 28 | 4.3 29 | 30 | 31 | -------------------------------------------------------------------------------- /04-CollectionsAndGenerics1/pre4.md: -------------------------------------------------------------------------------- 1 | *Simplest use of an ArrayList* 2 | http://www.mkyong.com/java/how-to-loop-arraylist-in-java/ 3 | 4 | *Check out some of the public methods of ArrayList* 5 | See its behaviour, what it can and can't do :) 6 | http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html 7 | 8 | *Some examples of the most used collections class in Java: ArrayList* 9 | http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html 10 | 11 | *Difference between Iterator and ListIterator* (if you are unfamiliar with iterators, skip this one for now : ) 12 | http://stackoverflow.com/questions/10977992/difference-between-iterator-and-listiterator 13 | 14 | *Diagram of ALL of java's collections framework:* 15 | http://www.codejava.net/java-core/collections/overview-of-java-collections-framework-api-uml-diagram 16 | 17 | ####Part 2#### 18 | *A HashMap example* 19 | http://www.tutorialspoint.com/java/java_hashmap_class.htm 20 | 21 | *HashMap vs Hashtable vs TreeMap in Java* 22 | http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/ 23 | 24 | *Equals and hashcode in java* 25 | http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java 26 | 27 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/src/com/hackbulgaria/corejava/Problems2.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public interface Problems2 { 4 | boolean isOdd(int number); 5 | 6 | boolean isPrime(int number); 7 | 8 | int min(int... array); 9 | 10 | int kthMin(int k, int[] array); 11 | 12 | float getAverage(int[] array); 13 | 14 | long getSmallestMultiple(int upperBound); 15 | 16 | long getLargestPalindrome(long N); 17 | 18 | int[] histogram(short[][] image); 19 | 20 | long doubleFac(int n); 21 | 22 | long kthFac(int k, int n); 23 | 24 | int getOddOccurrence(int[] array); 25 | 26 | long pow(int a, int b); 27 | 28 | long maximalScalarSum(int[] a, int[] b); 29 | 30 | int maxSpan(int[] array); 31 | 32 | boolean canBalance(int[] array); 33 | 34 | int[][] rescale(int[][] original, int newWidth, int newHeight); 35 | 36 | String reverseMe(String argument); 37 | 38 | String copyEveryChar(String input, int k); 39 | 40 | String reverseEveryWord(String arg); 41 | 42 | boolean isPalindrome(String argument); 43 | 44 | boolean isPalindrome(int number); 45 | 46 | int getPalindromeLength(String input); 47 | 48 | int countOcurrences(String needle, String haystack); 49 | 50 | String decodeURL(String input); 51 | 52 | int sumOfNumbers(String input); 53 | 54 | boolean areAnagrams(String A, String B); 55 | 56 | boolean hasAnagramOf(String string, String string2); 57 | } 58 | -------------------------------------------------------------------------------- /00-JavaPlatformIntroduction/agenda0.md: -------------------------------------------------------------------------------- 1 | ### Agenda #1 ### 2 | - Представете се 3 | - Малко организационно: 4 | - как ще протече курса: Решаваме неща тук, после ви давам за четене/гледане домашно (материали за следващия път) 5 | - в началото ще преговарям/обобщавам нещата, които съм ви дал 6 | - решаваме още задачи 7 | - Java - a little history 8 | + started as 'Oak' in 1991 => дъб 9 | + Created by Sun 10 | + renamed to 'java', due to large ammounts of coffee the team used in development 11 | + released 1996 12 | + Java 13 | + Compile once, run everywhere 14 | #1 Development Platform 15 | 9 Millions Developers 16 | 1 Billion Java Downloads per Year 17 | 3 Billion devices run Java 18 | 97% of Enterprise Desktops run Java 19 | 100% of BLU-RAY Disc Players ship with Java 20 | http://www.javacodegeeks.com/2014/03/java-facts-to-blow-your-mind.html 21 | Jit Compiler in J2SE (Java 1.2) 22 | - Java, JRE, JVM, JDK 23 | - JSR, JCP 24 | - JSE, J2EE, J2ME 25 | - Sun, Oracle, Google 26 | - Cross-platform, compatibility 27 | - Javac 28 | - classpath 29 | 30 | //what IDE does for us 31 | C:\>javac -sourcepath src -classpath classes;lib\Banners.jar ^ 32 | src\farewells\GoodBye.java -d classes 33 | //source and target explanations 34 | C\:>javac -sodurce 1.6 -target 1.6 -bootclasspath C:\jdk1.6.0\lib\rt.jar ^ 35 | -extdirs "" OldCode.java 36 | 37 | //bootclasspath option 38 | 39 | - javap 40 | - the javadoc tool 41 | - jar format 42 | - Common VM Arguments 43 | 44 | 45 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/src/com/hackbulgaria/corejava/tictactoe/ConsoleInputFetcher.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tictactoe; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.InputMismatchException; 7 | import java.util.Scanner; 8 | 9 | import com.hackbulgaria.corejava.tictactoe.UserInput.InputType; 10 | 11 | public class ConsoleInputFetcher implements UserInputFetcher { 12 | 13 | private final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); 14 | 15 | @Override 16 | public UserInput fetchUserInput() { 17 | String userInput; 18 | try { 19 | userInput = bufferedReader.readLine(); 20 | if (userInput.trim().equals("u")) { 21 | return new UserInput(InputType.UNDO); 22 | } else if (userInput.trim().equals("r")) { 23 | return new UserInput(InputType.REDO); 24 | } else if (userInput.trim().equals("q")) { 25 | return new UserInput(InputType.QUIT); 26 | } 27 | 28 | Scanner scanner = new Scanner(userInput); 29 | int y = scanner.nextInt(); 30 | int x = scanner.nextInt(); 31 | scanner.close(); // just a good style, but this is not necessary 32 | // here. 33 | 34 | return new UserInput(x, y); 35 | } catch (InputMismatchException badInput) { 36 | badInput.printStackTrace(); 37 | return new UserInput(InputType.QUIT); 38 | } catch (IOException e) { 39 | e.printStackTrace(); 40 | return new UserInput(InputType.QUIT); 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /06-Exam1/solution/Logger.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.exam1; 2 | 3 | import java.util.logging.Level; 4 | 5 | public class Logger { 6 | private static final int DEFAULT_LOG_LEVEL = 3; 7 | private static final int DEFAULT_MESSAGE_LEVEL = 3; 8 | private int logLevel; 9 | 10 | public Logger() { 11 | this(DEFAULT_LOG_LEVEL); 12 | } 13 | 14 | public Logger(int level) { 15 | setLevel(level); 16 | } 17 | public void setLevel(int level) { 18 | 19 | validateLevel(level); 20 | this.logLevel = level; 21 | } 22 | 23 | public void log(int msgLevel, String message) { 24 | validateLevel(msgLevel); 25 | if (msgLevel <= logLevel) { 26 | print(msgLevel, message); 27 | } 28 | } 29 | 30 | protected void print(int msgLevel, String message) { 31 | System.out.println(msgLevel + " => " + message); 32 | } 33 | 34 | private void validateLevel(int msgLevel) { 35 | if (msgLevel <= 0) { 36 | throw new InvalidLogLevelException(msgLevel); 37 | } 38 | } 39 | 40 | public void log(String message) { 41 | log(DEFAULT_MESSAGE_LEVEL, message); 42 | } 43 | 44 | public static class InvalidLogLevelException extends RuntimeException { 45 | private static final long serialVersionUID = 1L; 46 | 47 | public InvalidLogLevelException(int msgLevel) { 48 | super("Invalid level given! Level should be > 0, given " + msgLevel); 49 | } 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /02-DebuggingFun/problems2.md: -------------------------------------------------------------------------------- 1 | ###Some debugging fun### 2 | 1) Get latest changes from HackBulgaria repo 3 | `git pull` 4 | or 5 | `git clone https://github.com/HackBulgaria/Core-Java-1.git` 6 | 7 | 2) Import the DebuggingFun project in Eclipse 8 | - if you use 'import existing projects Eclipse it will not copy it in your workspace 9 | - if you use 'import from file system' 10 | 11 | 12 | //The ProjectName for all of the three problems below should be 'TDDIntro' 13 | 14 | ###JUnit Hello world### 15 | Implement a method 'getNumberOfDigits(int)' which just counts the number of digits. 16 | 17 | 1) Write the signature of the method 18 | 2) Write the test, make sure it fails beautifully. Think of some edge cases. 19 | 3) Implement the method 20 | 4) Pass your own test! Woohoo! 21 | 22 | 23 | ###Implement a join method### 24 | Java does not have a String join method. Apache StringUtils does have, but, well, that's not an excuse. 25 | 26 | Make a method that joins strings, with a **glue** given from the caller of your method. 27 | 28 | Can you think of a way for it to work with every object, not just string? Even primitives? 29 | 30 | //Glue is the first argument => " " 31 | `stichMeUp(" ", "Днес", "видях", 5, "ходещи", "медузи") => "Днес видях 5 ходещи медузи"` 32 | 33 | 1) Think of a good name for this method 34 | 2) Make a test class 35 | 3) Make several test cases, see that your tests fail mightily : ) 36 | 4) Implement! 37 | 38 | ###Reduce file path! In Java. In a test-driven way. ### 39 | See Problem 27 @ https://github.com/HackBulgaria/Programming101/blob/master/week0/simple_problems2.md 40 | -------------------------------------------------------------------------------- /19-ThreadsConcurrent/problems.md: -------------------------------------------------------------------------------- 1 | ### A demonstration of a race condition 2 | Create a project 'Threads'. 3 | 4 | Create a static variable `counter`. 5 | Create two threads - A and B. 6 | In their `run()` methods just increment the shared variable 2_000_000 times. 7 | 8 | Start the two threads, join them, and print out `counter`. What happens? Why? 9 | Print out the time needed. 10 | 11 | ##### Introduce critical blocks 12 | Now wrap the incrementing in a synchronized block in each thread. (They should be **synchronized on the same monitor**). 13 | First, wrap the whole `for` statements in a synchronized blocks. 14 | 15 | See the result is now correct, and observe the minor performance penalty. 16 | 17 | Now, move the synochronized block `inside` the `for` statements. 18 | Notice the increased performance penalty. 19 | 20 | 21 | ##### Replace the synchronized blocks with a call to a synchronized method increment() 22 | 23 | ##### Replace the synchronized stuff with an AtomicInteger. Notice the performance penalty! 24 | 25 | ##### Replace the Atomic Integer with wait/notify + mutex variable mechanism 26 | The scenario we want is the following: 27 | - Thread A obtains the mutex (`wait()`s until the mutex is available) 28 | - Works (increments the integer) 29 | - Then calls `notify` on the monitor 30 | - Which fires the Thread B, which does the same 31 | 32 | 33 | ### Implement a simple blocking queue. 34 | A blocking queue is just like a regular queue, with the difference that if someone calls `poll()` and the queue is empty, the call is blocked until somebody adds an element to the queue. After an element is added, the caller (the one who called `poll()`) gets unblocked and the `poll()` call returns. 35 | -------------------------------------------------------------------------------- /00-JavaPlatformIntroduction/problems0.md: -------------------------------------------------------------------------------- 1 | ### Verify java is working and is in $PATH ### 2 | ```java -version``` 3 | 4 | ```javac -version``` 5 | 6 | ```javap -version``` 7 | 8 | Friendly advice: These should be the same version, or you might have a bad time :) 9 | 10 | ### Compiling fun with javac and java### 11 | - Open a terminal. Navigate to any folder whatsoever. Make a new Empty.java file. Try to compile it with javac. See what happens. 12 | - Make a class named Program. Try to compile it with javac. 13 | - Rename the class to Empty. Compile it. 14 | - Make a main method. Make it print "Hello world!". Compile it and run it. 15 | - Make the main method print its arguments (String[] args). Make the for loop as you would make one in C or C++, and use the System.out.println method for printing to the console. 16 | 17 | ### Getting to know what classpath is### 18 | - Open a terminal, navigate to some folder. Make a new A.java file with a legitimate class A declared in it. 19 | - Do the same for a file/class named B. 20 | - Declare a public method in B. 21 | - In class A, make a *main method* 22 | - Instantiate B in it and call B's public method. 23 | - Try, compile and run A. Does it run? Why? How does it know about B? What about import statements? 24 | 25 | - Now move B up one folder to '..' 26 | - Try compiling and running it. 27 | 28 | - Add -cp ".." to your javac command and try again. 29 | 30 | ###Bundle them both### 31 | - jar -c A.class 32 | - Does this command look familiar to you? : ) 33 | 34 | ### Disassembly with javap ### 35 | - Disassemble Empty.class 36 | - Does this look familiar to you? This is what Eclipse is doing when you open a look up a class file with no source attached. 37 | 38 | 39 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/test/com/hackbulgaria/corejava/FaultyProblem4Test.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class FaultyProblem4Test { 8 | 9 | @Test 10 | public void testFloats() { 11 | for (int i = 2; i < 97; i++) { 12 | for (int j = 3; j < i * 17; j++) { 13 | float a = (float) i / j; 14 | float b = 1 / ((float) j / i); 15 | System.out.println(a + ", " + b); 16 | assertTrue(FaultyProblem4.areEqual(a, b)); 17 | } 18 | } 19 | } 20 | 21 | @Test 22 | public void testAgainFloats(){ 23 | assertTrue(FaultyProblem4.areEqual(0/6, 0/5)); 24 | assertTrue(FaultyProblem4.areEqual(401/399, 1/(399/401))); 25 | } 26 | 27 | @Test 28 | public void testInts() { 29 | assertTrue(FaultyProblem4.areEqual(4, 4)); 30 | assertTrue(FaultyProblem4.areEqual(0, 0)); 31 | assertTrue(FaultyProblem4.areEqual(500, 500)); 32 | 33 | // Защо са верни горните, а този тест фейлва? ^^^ 34 | assertTrue(FaultyProblem4.areEqual(new Integer(511), (Integer) 511)); 35 | } 36 | 37 | @Test 38 | public void testSubstringEquality() throws Exception { 39 | String a = "how do you do"; 40 | String b = "how do you do"; 41 | 42 | assertTrue(FaultyProblem4.haveEqualSubstrings(a, b)); 43 | 44 | a = "Bearded Man"; 45 | b = "Non-bearded Man"; 46 | assertFalse(FaultyProblem4.haveEqualSubstrings(a, b)); 47 | 48 | a = "Speaks"; 49 | b = "Freaky"; 50 | assertFalse(FaultyProblem4.haveEqualSubstrings(a, b)); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /18-ThreadsParallel/problems.md: -------------------------------------------------------------------------------- 1 | ### Paralel minimal point calculations 2 | 3 | Create a static method `generatePoints()` which returns a `List` - `java.awt.Point` 4 | Implement it, generating a 100 000 points (in java that is written `100_000`) points with random coordinates - ranging from 0 to 10_000. 5 | 6 | Now, for each of those points, I'd like you to find it's nearest point. Do this in a method `Map getNearestPoints(List generatedPoints)` 7 | 8 | As you can see, it takes a while. By my calculations, it should take like 100-250 seconds to complete (depending on your CPU speed). 9 | 10 | Now introduce some multithreading to speed it up. 11 | Declare and implement a method `doCalculations(List inPoints, int indexFrom, int indexTo, Map outMap)`. 12 | Move your calculations logic from `getNearestPoints` to `doCalculations`, but work strictly from `indexFrom`, to `indexTo`. 13 | 14 | Now in your `getNearestPoints(List generatedPoints)` method, start two Threads that call `doCalculations`, in their run methods, one from 0 to half of the elements, the other from half of the elements to the last of them. 15 | 16 | Measure speedup between the two implementations (See `System.currentTimeMillis()`). 17 | 18 | Introduce a third and forth thread. Does your implementation go faster? 19 | 20 | ### Paralel web crawler 21 | 22 | You remember your webcrawler project, right? 23 | There is a bottleneck in it - while you are waiting for an answer from the server, your CPU does nothing. 24 | Now, if you were to make several requests at once, it would be better. 25 | 26 | Try io crawl 9gag.com, for instance, and print every page you've visited. See the speed is not that great. 27 | Now Introduce parallelisation and speed up in your solution. Use an approach similiar to the approach for task #1. 28 | 29 | If your web crawler project is not working, use the one in this github folder instead. (It's a Maven project, you will need to fetch all dependencies). 30 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/src/com/hackbulgaria/corejava/game2048/ConsoleVisualizer.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.game2048; 2 | 3 | import java.io.IOException; 4 | 5 | import jline.Terminal; 6 | 7 | import com.hackbulgaria.corejava.game2048.GameBoard.GameResult; 8 | import com.hackbulgaria.corejava.game2048.GameBoard.MoveDirection; 9 | 10 | public class ConsoleVisualizer { 11 | private static final int VIRTUAL_DOWN = 14; 12 | private static final int VIRTUAL_UP = 16; 13 | private static final int VIRTUAL_RIGHT = 6; 14 | private static final int VIRTUAL_LEFT = 2; 15 | private final GameBoard gameBoard; 16 | 17 | public ConsoleVisualizer(GameBoard gameBoard) { 18 | this.gameBoard = gameBoard; 19 | 20 | printBoard(); 21 | GameResult result = GameResult.UNDETERMINED; 22 | 23 | while (result == GameResult.UNDETERMINED) { 24 | MoveDirection direction = getPlayerMove(); 25 | 26 | if (gameBoard.canMove(direction)) { 27 | result = gameBoard.move(direction); 28 | } 29 | printBoard(); 30 | } 31 | 32 | if (result == GameResult.WIN) { 33 | System.out.println("You won!"); 34 | } else { 35 | System.out.println("Sorry, you lost :("); 36 | } 37 | } 38 | 39 | private MoveDirection getPlayerMove() { 40 | MoveDirection moveDirection = null; 41 | try { 42 | Terminal terminal = Terminal.setupTerminal(); 43 | int c = terminal.readVirtualKey(System.in); 44 | if (c == VIRTUAL_LEFT) { 45 | moveDirection = MoveDirection.MOVE_LEFT; 46 | } else if (c == VIRTUAL_RIGHT) { 47 | moveDirection = MoveDirection.MOVE_RIGHT; 48 | } else if (c == VIRTUAL_UP) { 49 | moveDirection = MoveDirection.MOVE_UP; 50 | } else if (c == VIRTUAL_DOWN) { 51 | moveDirection = MoveDirection.MOVE_DOWN; 52 | } 53 | } catch (IOException e) { 54 | e.printStackTrace(); 55 | } 56 | return moveDirection; 57 | } 58 | 59 | private void printBoard() { 60 | for (int y = 0; y < GameBoard.BOARD_SIZE; y++) { 61 | for (int x = 0; x < GameBoard.BOARD_SIZE; x++) { 62 | System.out.print(gameBoard.getValue(y, x) + " "); 63 | } 64 | System.out.println(); 65 | } 66 | System.out.println(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Core-Java-1 2 | =========== 3 | 4 | This is the official GitHub repo for Core Java Course in [Hack Bulgaria](http://hackbulgaria.com) - http://hackbulgaria.com/course/Java-1/ 5 | 6 | The course launched on May 27-th. 7 | Information about the course can be found at http://hackbulgaria.com/course/Java-1/ (Bulgarian) 8 | 9 | You would likely want to check the start-here/start-here.md for information on the stuff you should do/install prior to course launch : ) 10 | 11 | If you have never programmed before, this is a not a course for you. If you want to learn programming the right way, see http://hackbulgaria.com and look for "Programming 101" : ) 12 | 13 | 14 | ### About this repo 15 | Every folder in the repo starting with a number contains links/problems/materials about a specific subject/theme/area. 16 | They are usually named named: 17 | - `problems.md` - for the tasks you need to solve 18 | - `pre.md` - for the prereading you should do **beforehand** 19 | - `materials.md` if you'd likely need to use the links/resources *while solving tasks from* `problems.md` . 20 | 21 | ### Outline 22 | 23 | - **Week 0** - Java Platform Introduction, Eclipse/JDK installings and configurations, Types, Arrays, Strings in Java 24 | - **Week 1** - Introduction to debugging, 'Find-the-error-in-the-code-via-debugging' problems, Classes/Overloading/Overriding/OOP 25 | - **Week 2** - Collections and Generics (usage), Defensive Programming/Error Handling and first "feedback-exam" 26 | - **Week 3** - Working with the filesystem, working with foreign code, linking libraries 27 | - **Week 4** - Practical Teamwork - pair programming, working in a team using git/github, working with XML/JSON 28 | - **Week 5** - Working with XML/JSON, a small team project 29 | - **Week 6** - Networking1 - Client/Server socket-based remote execution protocol 30 | - **Week 7** - Networking2 - HTTP, Consuming REST services, downloading stuff, crawling web sites 31 | - **Week 8** - Networking3 - Servlets, Consuming RSS, Generics in Java 2, Deploy-on-app-server-with-maven 32 | - **(Bonus) Week 9** - Multithreading - Parallel Execution, Java concurrency mechanisms, job-interview-like exam 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /19-ThreadsConcurrent/WaitNotifyMechanism/src/com/hackbulgaria/corejava/WaitNotifyMechanism.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class WaitNotifyMechanism { 4 | public static long startTime = System.currentTimeMillis(); 5 | public static Integer counter = 0; 6 | public static final Object monitor = new Object(); 7 | private static int turn = 0; 8 | 9 | public static void increment() { 10 | System.out.println("Incrementing from Thread : " + Thread.currentThread().getName() + " " + counter ); 11 | counter++; 12 | } 13 | 14 | public static void main(String[] args) throws InterruptedException { 15 | Thread t1 = new Thread() { 16 | public void run() { 17 | for (int i = 0; i < 2_000_000; i++) { 18 | synchronized (monitor) { 19 | while (turn != 1) { 20 | try { 21 | monitor.wait(); 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | 26 | } 27 | increment(); 28 | 29 | turn = (turn + 1) % 2; 30 | monitor.notify(); 31 | } 32 | 33 | } 34 | } 35 | }; 36 | Thread t2 = new Thread() { 37 | 38 | public void run() { 39 | for (int i = 0; i < 2_000_000; i++) { 40 | synchronized (monitor) { 41 | while (turn != 0) { 42 | try { 43 | monitor.wait(); 44 | } catch (InterruptedException e) { 45 | e.printStackTrace(); 46 | } 47 | } 48 | 49 | increment(); 50 | 51 | turn = (turn + 1) % 2; 52 | monitor.notify(); 53 | } 54 | } 55 | } 56 | }; 57 | t1.setName("T1"); 58 | t2.setName("T2"); 59 | t1.start(); 60 | t2.start(); 61 | t1.join(); 62 | t2.join(); 63 | System.out.println(counter); 64 | System.out.println(System.currentTimeMillis() - startTime); 65 | } 66 | } -------------------------------------------------------------------------------- /01-TypesArraysStrings/pre1.md: -------------------------------------------------------------------------------- 1 | ###Recap of what we did the last time:### 2 | 3 | The 'git/github'/recap article (if you are not familiar with git/github) 4 | https://github.com/HackBulgaria/Programming101/blob/master/week1/git.md 5 | 6 | 7 | JRE, JDK, JVM (if you still don't know what they are) 8 | http://stackoverflow.com/questions/11547458/what-is-differences-between-jvm-jdk-jre-openjdk 9 | 10 | Path and classpath (if you are having trouble differentiating those two) 11 | http://docs.oracle.com/javase/tutorial/essential/environment/paths.html 12 | 13 | On debugging with Eclipse 14 | https://blog.codecentric.de/en/2013/04/again-10-tips-on-java-debugging-with-eclipse/ 15 | 16 | Primitive Data types in Java 17 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html 18 | 19 | Arrays in Java 20 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html 21 | http://stackoverflow.com/questions/2267790/how-are-arrays-implemented-in-java 22 | http://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.8 23 | 24 | Some Q&A 25 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/QandE/questions_variables.html 26 | 27 | Operators 28 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html 29 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html 30 | 31 | On Control flow - if, for, while, do-while, switch 32 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html 33 | 34 | 35 | 36 | ###For our second meeting : ) ### 37 | 38 | 39 | Wrapper Classes 40 | http://en.wikipedia.org/wiki/Primitive_wrapper_class 41 | 42 | On autoboxing and unboxing in Java 43 | http://javarevisited.blogspot.com/2012/07/auto-boxing-and-unboxing-in-java-be.html 44 | 45 | On instanceof and isAssignableFrom 46 | http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom 47 | 48 | Most important stuff on String 49 | http://javarevisited.blogspot.com/2013/07/java-string-tutorial-and-examples-beginners-programming.html 50 | 51 | StringBuilder vs StringBuffer? 52 | http://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html 53 | 54 | On Unicode (Joel on Software) 55 | http://www.joelonsoftware.com/articles/Unicode.html 56 | 57 | On String interning 58 | http://en.wikipedia.org/wiki/String_interning 59 | http://java-performance.info/string-intern-in-java-6-7-8/ 60 | 61 | Introduction to JUnit 62 | http://courses.cs.washington.edu/courses/cse143/11wi/eclipse-tutorial/junit.shtml -------------------------------------------------------------------------------- /000-StartHere/start-here.md: -------------------------------------------------------------------------------- 1 | ##Start Here!## 2 | 3 | Welcome :) 4 | 5 | Here are a few things you should probably get done before the start of the core java course: 6 | 7 | **1)** Install JDK 7 8 | 9 | *Windows:* use Oracle's JDK from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html 10 | or 11 | 12 | *Linux:* use your distribution's jdk-7 package: 13 | (Check http://openjdk.java.net/install/) 14 | 15 | *Mac OS X:* Use the native updater to update Java to a release > 7u25. 16 | 7u25 is disabled by Apple because of severe security issues. 17 | 18 | **2)** Make sure java binaries are registered in PATH 19 | and that they are **the same version** 20 | 21 | ``` 22 | java -version 23 | 24 | java version "1.7.0_51" 25 | OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.12.04.2) 26 | OpenJDK Server VM (build 24.45-b08, mixed mode) 27 | ``` 28 | ``` 29 | javac -version 30 | javac 1.7.0_51 31 | ``` 32 | 33 | **3)** Install Eclipse Kepler from Eclipse site: 34 | https://www.eclipse.org/downloads/packages/eclipse-ide-java-developers/keplersr2-with-java8-patches 35 | Do not use your Linux distribution's Eclipse distribution. It would most likely be outdated. 36 | 37 | **4)** Read the Google style-guide for Java source code: 38 | http://google-styleguide.googlecode.com/svn/trunk/javaguide.html 39 | 40 | We will be using very similiar style guide, but with the following modifications: 41 | - 4 spaces for identation instead of 2. 42 | - 120 lines for line-wrapping instead of 80. 43 | 44 | **5)** Import eclipse preferences (the .epf file) in Eclipse 45 | `File->Import->General->Preferences` 46 | 47 | **6)** Import the code formatter (the .xml file) in Eclipse 48 | `Window->Preferences-> Write 'Format' in the search field up left-> Select the one below 'Java' -> Click on Import` 49 | 50 | **7)** Create yourself a GitHub account! 51 | If you have never worked with git or GitHub, see the excellent article from 52 | HackBulgaria's programming 101 course: 53 | https://github.com/HackBulgaria/Programming101/tree/master/week1/git.md 54 | 55 | ##But why aren't we using java 8 VM?## 56 | Because the community is not quite ready: 57 | - Eclipse is not exactly java8 ready: http://www.eclipse.org/downloads/java8/ 58 | - Maven and m2eclipse are not java8 ready : https://bugs.eclipse.org/bugs/show_bug.cgi?id=420848 59 | - Ant in Eclipse is not java8 ready: http://wiki.eclipse.org/Ant/Java8 60 | - No deployment packages for OpenJDK 8 for most Linux distributions. 61 | 62 | And so on and so on. You will likely run into quite some problems, as the community is not ready with the tooling, support and guidance. Of course, one can install java 8 vm and take it for a test-drive, but serious development needs tools. And at the present moment, they are in transition. Give it a little time. -------------------------------------------------------------------------------- /15-Networking3/problems.md: -------------------------------------------------------------------------------- 1 | ### Servlet/HelloWorld 2 | - Create an Http Servlet. Override the `doGet` method, and write 'HelloWorld!' to the response's outputStream. 3 | - Run your application on Eclipse ('Run as Server'). 4 | - See your own message at 'localhost:8080/YourAppName/YourServletName' 5 | - Make your servlet respond at 'localhost:8080/YourAppName/' (Edit the @WebServlet annotation path to '/') 6 | - See that your servlet now responds at 'localhost:8080/YourAppName/' 7 | - Now undo your change (restore the @WebServlet annotation path). 8 | - Right click on your project -> Java EE tools -> Generate Deployment descriptor stub. 9 | - - You will now have a 'web.xml' file. It is called a deployment descriptor. 10 | - - Edit the deployment descriptor, and add a first welcome-file tag pointing to 'YourServletName'. We want to register the servlet as a welcome page for your server :) 11 | - Check the 'html source code' returned by your servlet. You will see no HTML tags. Why? 12 | - Write an HTML response to your client. For instance `

Now that's a big title!

` 13 | 14 | Congratulations. You've just witnessed what ASP/JSP/PHP is all about. We are not going to do any of that ~~sh**~~ stuff. 15 | 16 | 17 | ### Simple news agregator 18 | Do you know what an [RSS](http://en.wikipedia.org/wiki/RSS) is? 19 | It is a simple format for describing **content** (just the content, and not it's visualization). It is an XML-based format. 20 | 21 | [This is an RSS](http://www.sportal.bg/uploads/rss_category_2.xml) 22 | Your task is simple - create a service (using just a servlet), that shows the latest news **in bulgarian** in the following categories: 23 | - General/Bulgaria 24 | - Technology 25 | - Sport 26 | 27 | Write the ~~ugliest~~ simplest html output you possibly can. 28 | Something like is completely OK. 29 | ![this](http://i.imgur.com/uZvmOlRl.jpg) 30 | 31 | 32 | If you don't know HTML, it's okay, just check http://www.w3schools.com/html/html_basic.asp You'll learn a few tricks in no time. 33 | 34 | Hints: 35 | - Pick some RSS feed links from popular news websites. Dnevnik.bg, sportal.bg, etc have RSS feed functionality. Maybe even FMI had one? 36 | - Do not parse the XML yourself. There are libraries for that, use the ones given in this github folder (the ROME library). 37 | - Add both jars in the WEB-INF/lib folder. Don't do anything after that, Eclipse will automatically add them to the project's build path. 38 | - Use this ROME tutorial: http://blog.manishchhabra.com/2011/10/rome-library-example-for-parsing-rss-and-atom-feeds/ 39 | 40 | 41 | ### Simple JSON pretty printer service. 42 | Just look at the JSON at http://hackbulgaria.com/api/checkins . It is horrible - completely unreadable. What are the elements? What are the JSON objects? You cannot easily tell. 43 | 44 | - Deploy a servlet, that accepts a named "POST" parameter "json". 45 | - Read the json as a POST parameter given to the request (as a parameter from the `HttpServletRequest` via the `getParameter` method.) 46 | - Use google gson to pretty-print the json given. 47 | - See how to it here: http://stackoverflow.com/questions/4105795/pretty-print-json-in-java 48 | -------------------------------------------------------------------------------- /18-ThreadsParallel/WebCrawler/src/com/hackbulgaria/corejava/WebCrawler.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import java.io.IOException; 4 | import java.net.MalformedURLException; 5 | import java.net.URI; 6 | import java.net.URISyntaxException; 7 | import java.util.ArrayList; 8 | import java.util.Collections; 9 | import java.util.HashSet; 10 | import java.util.List; 11 | import java.util.Set; 12 | import java.util.concurrent.ExecutionException; 13 | import java.util.regex.Matcher; 14 | import java.util.regex.Pattern; 15 | 16 | import org.apache.commons.io.IOUtil; 17 | import org.apache.http.HttpResponse; 18 | import org.apache.http.client.HttpClient; 19 | import org.apache.http.client.methods.HttpGet; 20 | import org.apache.http.client.utils.URIUtils; 21 | import org.apache.http.impl.client.DefaultHttpClient; 22 | 23 | public class WebCrawler { 24 | private final Set visitedUrls = Collections.synchronizedSet(new HashSet()); 25 | 26 | public URI crawl(URI currentLocation, final String needle) throws URISyntaxException, MalformedURLException, 27 | InterruptedException, ExecutionException { 28 | String urlContents = downloadContents(currentLocation); 29 | visitedUrls.add(currentLocation); 30 | 31 | if (urlContents.contains(needle)) { 32 | return currentLocation; 33 | } else { 34 | for (String link : getAllLinks(urlContents)) { 35 | final URI asUri = normalizeLink(currentLocation, link); 36 | if (!visitedUrls.contains(asUri) && isInsideDomain(currentLocation, asUri)) { 37 | URI result = crawl(asUri, needle); 38 | if (result != null) { 39 | return result; 40 | } 41 | } 42 | } 43 | } 44 | return null; 45 | } 46 | 47 | private static boolean isInsideDomain(URI currentLocation, URI asUrl) throws URISyntaxException { 48 | return currentLocation.getHost().equals(asUrl.getHost()); 49 | } 50 | 51 | private URI normalizeLink(URI currentLocation, String link) throws MalformedURLException, URISyntaxException { 52 | URI uri = new URI(link); 53 | if (uri.getScheme() != null && uri.getHost() != null) { 54 | return uri; 55 | } 56 | return URIUtils.resolve(currentLocation, uri); 57 | } 58 | 59 | private static String downloadContents(URI startLocation) throws URISyntaxException { 60 | HttpClient httpClient = new DefaultHttpClient(); 61 | System.out.println("Currently crawling : " + startLocation); 62 | HttpGet get = new HttpGet(startLocation); 63 | try { 64 | HttpResponse response = httpClient.execute(get); 65 | String contents = IOUtil.toString(response.getEntity().getContent()); 66 | return contents; 67 | } catch (IOException e) { 68 | e.printStackTrace(); 69 | // IO Error when connecting to the server, whatever, just return 70 | // empty contents 71 | return ""; 72 | } 73 | } 74 | 75 | private static List getAllLinks(String content) { 76 | ArrayList resultList = new ArrayList<>(); 77 | String regex = ""; 78 | Pattern pattern = Pattern.compile(regex); 79 | Matcher matcher = pattern.matcher(content); 80 | while (matcher.find()) { 81 | resultList.add(matcher.group(1)); 82 | } 83 | return resultList; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /02-DebuggingFun/DebuggingFun/src/com/hackbulgaria/corejava/Utils.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | import java.io.File; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.io.Writer; 7 | import java.lang.Thread.State; 8 | import java.net.MalformedURLException; 9 | import java.net.URL; 10 | import java.net.URLClassLoader; 11 | 12 | import javax.tools.JavaCompiler; 13 | import javax.tools.ToolProvider; 14 | 15 | import org.apache.commons.io.FileUtils; 16 | 17 | public class Utils { 18 | public static String reverseMe(String argument) { 19 | return new StringBuilder(argument).reverse().toString(); 20 | } 21 | 22 | public static boolean isPalindrome(String argument) { 23 | return argument.equals(reverseMe(argument)); 24 | } 25 | 26 | public static boolean isPalindrome(long number) { 27 | return isPalindrome(String.valueOf(number)); 28 | } 29 | 30 | public static void killMeIfIGetStuck() { 31 | final Thread threadToKill = Thread.currentThread(); 32 | new Thread(new Runnable() { 33 | 34 | @Override 35 | public void run() { 36 | try { 37 | Thread.sleep(2000); 38 | if (threadToKill.getState().equals(State.RUNNABLE) && "binarySearch".equals(threadToKill.getStackTrace()[0].getMethodName())) { 39 | 40 | // every time you do this Barekov gets another vote! 41 | threadToKill.stop(); 42 | } 43 | } catch (final InterruptedException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | }).start(); 48 | } 49 | 50 | 51 | 52 | public static Class eval(Code code, String fileName) { 53 | File root = new File(isWindows()? "C:\\" : "/tmp/java-fun/"); 54 | File sourceFile = new File(root, fileName + ".java"); 55 | root.mkdirs(); 56 | 57 | try { 58 | FileUtils.write(sourceFile, code.wrappedCode); 59 | } catch (IOException e) { 60 | e.printStackTrace(); 61 | } 62 | 63 | JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); 64 | javaCompiler.run(null, null, null, sourceFile.getPath()); 65 | 66 | URLClassLoader urlClassLoader = null; 67 | try { 68 | urlClassLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); 69 | } catch (MalformedURLException e1) { 70 | e1.printStackTrace(); 71 | } 72 | try { 73 | return Class.forName(fileName, true, urlClassLoader); 74 | } catch (ClassNotFoundException e) { 75 | e.printStackTrace(); 76 | } 77 | return null; 78 | } 79 | 80 | private static boolean isWindows() { 81 | return System.getProperty("os.name").toLowerCase().contains("win"); 82 | } 83 | 84 | public static class Code { 85 | private String wrappedCode; 86 | 87 | public Code(String code){ 88 | this.wrappedCode = "public class Eval { static { " + code + " } } "; 89 | } 90 | 91 | @Override 92 | public String toString() { 93 | return wrappedCode + super.toString(); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /14-Networking2/problems.md: -------------------------------------------------------------------------------- 1 | ### Download a file with java 2 | Using only URL and the stream classes, download this photo: http://d3dsacqprgcsqh.cloudfront.net/photo/aozrdx0_700b.jpg to a location of your choosing 3 | 4 | ##### Now accept files from the command line and label your program the 'java wget'. Woohoo! 5 | 6 | ### Make a simple website crawler (Pair Programming) 7 | Have you grown tiiiiiiired of looking for stuff on websites that simply seems is not in the navigation menu at all? 8 | You grow tired of that... and suddenly, baaaam! Someone skypes you the link. It was there, how could I have not seen it. 9 | 10 | 11 | Today, we will put an end to that. 12 | 13 | Write a simple web crawler, that is receiving a URL as a command line parameter and a "needle" to search for. 14 | Needle is text, usually a sentence. 15 | 16 | What your crawler should do is simple 17 | - GET the contents of the URL received 18 | - Check if the contents contain "needle" 19 | - If they do, output the URL and exit 20 | - If they don't, **get all the links** from the URL given and repeat for every link. 21 | 22 | Hints/tips: 23 | - **Don't go out of the website's scope** - if a link in `abv.bg` points to google, well, don't follow google, please... 24 | - **Don't visit the same URL twice** 25 | - **Use regular expressions** for getting links. If you are unfamiliar with them, use the following method: 26 | ```java 27 | private static List getAllLinks(String content) { 28 | ArrayList resultList = new ArrayList<>(); 29 | String regex = ""; 30 | Pattern pattern = Pattern.compile(regex); 31 | Matcher matcher = pattern.matcher(content); 32 | while (matcher.find()) { 33 | resultList.add(matcher.group(1)); 34 | } 35 | return resultList; 36 | } 37 | ``` 38 | - **If you are not comfortable with even using something as ugly as regular expressions, you can do it with regular string matching. It will be harder though :(** 39 | - Use small websites for testing. For example, http://ebusiness.free.bg is one site you can use. It has very, very few links. (Search for the word 'Револвираща'.) 40 | 41 | ### Get/print all the people that have signed for more than 1 course at Hack Bulgaria. 42 | Some people have signed for Core Java. 43 | Some people have signed for Front-end Javascript. 44 | Some people have signed for Angular-JS. 45 | 46 | They are people that have signed for more than one course. 47 | Using the https://hackbulgaria.com/api/students/ API, the [Jettison library](http://jettison.codehaus.org/) and [Apache HttpClient](http://hc.apache.org/httpclient-3.x/tutorial.html), consume the REST service given and print out all the people, who have signed for more that 1 course. 48 | 49 | 50 | ##### Addendum: Print out the people with the most visits. 51 | See, whenever you visit HackBulgaria and use our WiFi, your MAC addresses get logged. If you have 'filled the forms' when registering at the HackBulgaria website, you can now see who has been coming and who hasn't been coming to the lectures. 52 | 53 | ``` 54 | {"date": "2014-06-05", "student_id": 35, "student_courses": [{"group": 1, "name": "Frontend JavaScript"}], "student_name": "Светимир Игнатов"} 55 | ``` 56 | 57 | Using https://hackbulgaria.com/api/checkins/, the [Jettison library](http://jettison.codehaus.org/) and [Apache HttpClient](http://hc.apache.org/httpclient-3.x/tutorial.html), consume the REST service given and print out pairs of String-Integer, where the key (String) is the name of a Person, and the value (Integer) is the number of times he was at HackBulgaria. Sort the pairs when printing - people with more checkins should come before people with less checkins. 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /08-WorkingWithLibraries/problems.md: -------------------------------------------------------------------------------- 1 | ### Send an email about the 'Suarez' accident 2 | 3 | Have you seen the Suarez-Chiellini biting accident from the World Cup in Brazil? It was both hilarious and weird-ish at the same time. 4 | In the dawn of the internet, when skype, snapchat and stuff like that did not exist, people were sending a lot of emails to each other with funny stuff. 5 | 6 | Send an email to someone about the suarez biting accident. Attach a gif of the biting accident, available [here](http://d3dsacqprgcsqh.cloudfront.net/photo/azbW3zq_460sa_v1.gif) 7 | 8 | Integrate and use the apache commons-email library from http://commons.apache.org/proper/commons-email/userguide.html 9 | 10 | Note: The commons-email library depends on the javax.mail library, which you should download from somewhere. 11 | 12 | ### JToaster 13 | 14 | Ivan stays a lot on his computer. His mother is afraid he will spoils his vision. 15 | As you know very well, you should take a break of at least 5 minutes (actually, it should be 15, but this *might* be outdated). 16 | 17 | Help Ivan maintain his eagle-like vision. Write a program that waits 45 minutes, and the shows a notification saying 'Get a little rest, will you?' (or a message of your choosing :D) 18 | 19 | Use the incredibly-complex JToaster library. Download it from http://jtoaster.sourceforge.net/ 20 | Use the methods `showToaster`, `setToasterWidth`, `setToasterHeight`, `setToasterIcon`, `setToasterColor`, `setBackgroundImage`, `setStep`, etc. to customize and make the coolest toaster you can imagine. Also, set a nice background, something like 21 | 22 | ![This dog] (http://www.mnn.com/sites/default/files/editorial/Corgeek.jpg) 23 | 24 | 25 | Also, check out the `Thread.sleep` method. 26 | 27 | 28 | ### Make a QuickCodeInspector desktop application 29 | 30 | Ever needed to really, really quickly inpsect some code? 31 | Here is a one cool syntax highlighter for java https://code.google.com/p/java-syntax-highlighter/ 32 | 33 | 1) Create a program, that receives a file path as a command-line argument (args[0] in `main(String[] args)`) 34 | 2) For the File given, launch a syntax highlighter windows as the example in the link above. 35 | 36 | Come back when you are done with 1) and 2). 37 | 38 | Does it work so far? Marvelous. 39 | 3) *Not mandatory*. Now, for the fun, export your program as a *runnable* jar. (See Eclipse->Export). Register your program as one that can handle .java files in your OS (the way to do this will vary among OS and distributions) 40 | For ubuntu see http://askubuntu.com/questions/289337/how-can-i-change-file-association-globally. 41 | 42 | For windows, create a **.bat** file, containing somthing like: 43 | ``` 44 | "C:\Program Files\Java\jre7\bin\javaw.exe" -jar "C:\Users\Adriana\Desktop\QuickCodeInspector.jar" %1 % 45 | ``` 46 | 1) C:\Program Files... -> Is the path to your javaw.exe location 47 | 2)-jar C:\Users..... -> is the path to your QuickCodeInspector.jar 48 | 3) Just append %1 % at the end of the .bat script. 49 | After that, try opening .java files with your application, by using **open with** and pointing to your .bat file. 50 | 51 | Go and check your cool java program that opens .java files for you. (Remove the entry later!). 52 | 53 | 4) Set a title on the window that matches the name of the file being viewed! 54 | 5) How cool would it be if we could navigate through all the files of the current directory with the arrows of the keyboard? 55 | In order to do that, make the jframe **focusable**, add a **KeyEventListener**, and when the user presses the arrow-next on the keyboard (see [key-code table](http://www.foreui.com/articles/Key_Code_Table.htm)), `dispose()` the frame and create a new one with a syntax highlighter configured for the next file. 56 | 6) Make this work recursively for all the files in the folder. 57 | 58 | -------------------------------------------------------------------------------- /06-Exam1/tasks.md: -------------------------------------------------------------------------------- 1 | Both tasks should go into a project named Exam1. 2 | Later on you will be asked to give a link to your solution (to the Exam1 project). All tasks but the last one should have good test cases with them. 3 | 4 | ### Make a method 'sort', which sorts a copy of a List 5 | `Collections.sort` is really cool, but it sorts collections in place. 6 | Write a **utility** method `sort`, that sorts a **copy of the given** `List`, and returns it. Use `Integer` as type for your `List`. 7 | 8 | ### Make a method 'reverse', which reverses a copy of a List. 9 | Write a **utility** method `reverse`, that takes a `List`, **reverses** a copy of it and returns the reversed copy. Use `Integer` as type for your `List` argument. 10 | 11 | ### Check if the given List is monotonous 12 | Make a **utility** method, that returns **boolean** whenever the `List` given is monotonic. 13 | ```java 14 | YourClass.yourMethod(Arrays.asList(1,2,3,4,5,6)); //true 15 | YourClass.yourMethod(Arrays.asList(6,5,4,3,2,1,1,1); //true 16 | YourClass.yourMethod(Arrays.asList(1,2,1,4,5,4)); //false 17 | ``` 18 | **Bonus** Maximum 1 line of code allowed. :) 19 | 20 | ### Make a logger class 21 | 22 | Disclaimer: To **log** somethings means simply to write it to the console. 23 | 24 | A *logger* class is a class that people use when they want something written on the console. Of course, one can always use `System.out.println()`, but it is a churn, and logger classes tend to offer good methods for writing a little more complicated stuff to the console (see examples below). 25 | 26 | A logger class also has something called `LEVEL`, which is usually an integer. 27 | `LEVEL` represents the **importance** of the message logged. For instance, `logger.log(3, "something)` means that the priority for message **"something"** is **3**. 28 | 29 | And when a `LEVEL` is **set to the logger**, the logger **ignores logging calls for higher levels**. 30 | For instance: 31 | ```java 32 | Logger logger = new Logger(3); //set LEVEL to 3 33 | //I can also call 'new Logger()', in which case use a default LEVEL of 3 34 | 35 | logger.log(2, "Somewhat important message"); //gets logged as "2 => Somewhat important message" 36 | logger.log(3, "Less important message"); // also gets logged! 37 | logger.log(5, "Not important"); //this is less important than LEVEL, so it will **not be logged**. 38 | logger.log("Meh"); //overload without a LEVEL parameter, use 3 as default. 39 | 40 | .... 41 | looger.setLevel(2); 42 | logger.log("My message"); //does not get printed! 43 | ``` 44 | 45 | `LEVEL` is always expected to be > 0. Your class should not encourage/tolerate behavior like: 46 | `logger.log(INTEGER.MIN_VALUE, "THIS is most important message in the world!!!")`. This is not a correct call and calling your method like this is a programmer mistake. **Make sure you do not accept such usage.** 47 | 48 | 49 | **It is important to note that LEVEL must be settable at runtime, after the logger object has been created.** 50 | 51 | 52 | 53 | Also, it is quite important on how the log message look like. In order for your log messages to be more informative, include the *current date and time* of the logging. 54 | Make a class `DateLogger`, which logs messages, but prepends 55 | Example 56 | 57 | ```java 58 | Logger logger = new DateLogger(); //I am not obliged to set a log level, by default your class should print everything in this case 59 | logger.log("My message"); //this is an overload without a LEVEL parameter. In this situation, assume the LEVEL given to you is 3. 60 | //|22:14:01 14.06.2014| 3 => My message 61 | ``` 62 | 63 | To summarize: 64 | - Create a `Logger` class. Make a constructor accepting log `LEVEL`. Make a default constructor with a default log level of 3. 65 | - Implement a `log(int level, String message)` and `log(String message)` 66 | - Do not log messages if the level given is higher than the currently set in the logger. 67 | - Protect users of this class from invalid usage 68 | - Create a sublcass `DateLogger`. Override it's methods so that date and time is added to every logged message (see examples above). 69 | - It's okay (just for now, and just for this task!), not to use TDD. This is because I have not shown you mocking, and we have not talked about PrintStreams, PrintWriters, etc. in Java. 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /16-Generics2/problems.md: -------------------------------------------------------------------------------- 1 | ### Declare an annotation type 'ClassInfo' 2 | It should contain information about: 3 | - author of the class 4 | - revision of the class (by default it should be 1) 5 | - should the class be 'checked' (by default it should be) //this 'checked' thing is a bogus one, I just made it up so you can use a boolean default 6 | - an array of 'related' classes (Class[]) 7 | 8 | - Annotatate a class with this annotation. Fill in the 'required' information 9 | - In a main method, instantiate the annotated class. Using the `getClass().getAnnotations()`, print out all the annotations declared for your annotated class. 10 | - Now fetch your own annotation using `yourInstance.getClass().getAnnotation(YourAnnotationName.class);` 11 | - Print out all the filled information 12 | 13 | 14 | ###1. Create a Box class 15 | 16 | A Box class can hold an instance. 17 | 18 | ```java 19 | Box box = new Box<>(); 20 | box.set(3); 21 | System.out.println(box.get()); //=>3 22 | 23 | 24 | Box box = new Box<>("this example belongs to Oracle"); 25 | System.out.println(box.get()) //"this example belongs to Oracle" 26 | ``` 27 | 28 | Demonstrate the usage of the class you wrote in a main method, setting an `Integer`, a `String`, and a `List` list to the box. 29 | 30 | ###2. Create a Pair class 31 | **F** stands for first, **S** stands for second. 32 | 33 | ```java 34 | Pair pair = new Pair<>(); 35 | pair.setFirst(3); 36 | pair.setSecond("string"); 37 | 38 | System.out.println(pair.toString()); //=> <3, "string"> (Implement the to string method as well) 39 | System.out.println(pair.first()); //=> 3 (first() here returns an *Integer*, not an *Object*!) 40 | System.out.println(pair.second()); //=> "string" 41 | 42 | Pair pair = new Pair<>(3, "string"); 43 | System.out.println(pair.toString()); //=> <3, "string"> 44 | ``` 45 | 46 | Demonstrate the usage of your Pair class in a similiar manner. 47 | 48 | ###3. Write a static newInstance method 49 | Declare a method that receives a Class clazz, and returns a new instance of T. See http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#newInstance-- 50 | 51 | 52 | ###4. Write a 'Favourites' class 53 | Write a class `Favourites`, with which I can do the following: 54 | ```java 55 | Favourites favourites = new Favourites(); 56 | favourites.add(String.class, "myString"); 57 | favourites.add(Integer.class, 3); 58 | 59 | System.out.println(favourites.get(Integer.class)) => //3 60 | ``` 61 | No compile time warnings : ) 62 | Hints: See `cast` method on `Class` class. There is more than 1 solution to this task. 63 | 64 | 65 | Demonstrate the usage of your class. 66 | 67 | Can you make the `Favourites` class iterable? No casts/ compiler warnings allowed : ) 68 | 69 | ###5. Write an 'Arrays.asList' - like method. 70 | ```java 71 | List ints = asList(1,2,3,4,5); 72 | List strings = asList("1","2","3","4","5"); 73 | 74 | //also, give an explanation to what is happening in the lines below :) 75 | List whatIsThis = asList(null,null,null); 76 | List hahaaah = asList(null,null,null); 77 | List didNotExpectThisWTF = asList(null,null,null); 78 | List nowWhat = YourClass. asList(null,null,null); 79 | ``` 80 | 81 | 82 | ###6. Write a class NaturalNumber that works with Integer, Short or Long 83 | ```java 84 | NaturalNumber n1 = new NaturalNumber<>(12341541L); 85 | NaturalNumber n2 = new NaturalNumber<>(123); 86 | NaturalNumber n3 = new NaturalNumber<>((short) 122); 87 | 88 | System.out.println(n1.isEven()); //false; 89 | System.out.println(n2.isEven()); //false; 90 | System.out.println(n3.isEven()); //true; 91 | 92 | NaturalNumber n4 = new NaturalNumber<>("1231516"); //compile-time error! 93 | ``` 94 | Use a combination of wildcards(?), and the `Number` class to make the above functionality work. Check out `Number`'s methods : ) 95 | 96 | ###7. Implement a `greaterThan` method that returns all the items in a collection 'arg1', that are greater than 'arg2'. 97 | Your method should receive two parameters - a Collection of some type. 98 | Hint: Your type parameter should extend Comparable 99 | 100 | ```java 101 | Collection all = Arrays.asList(1,2,3,4,5,6,7); 102 | Collection filtered = yourMethod(fitered, 5); //6, 7 103 | ``` 104 | Demonstrate the usage of your program. 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /12-SmallProject/ref/ConsoleTicTacToe/src/com/hackbulgaria/corejava/tictactoe/GameBoard.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tictactoe; 2 | 3 | 4 | public final class GameBoard { 5 | public static final int BOARD_LENGTH = 3; 6 | 7 | private static final int PLAYER_1 = 1; 8 | private static final int PLAYER_2 = 0; 9 | 10 | private static final int UNSET = -1; 11 | 12 | private int currentPlayer = PLAYER_1; 13 | 14 | private final int[][] board; 15 | 16 | public GameBoard() { 17 | this.board = (new int[BOARD_LENGTH][BOARD_LENGTH]); 18 | for (int y = 0; y < BOARD_LENGTH; y++) { 19 | for (int x = 0; x < BOARD_LENGTH; x++) { 20 | getBoard()[y][x] = UNSET; 21 | } 22 | } 23 | } 24 | 25 | public GameState play(UserInput input) { 26 | switch (input.getType()) { 27 | case NORMAL: 28 | return doPlay(input); 29 | case UNDO: 30 | return undo(input); 31 | case REDO: 32 | return redo(input); 33 | default: 34 | return GameState.PLAYING; 35 | } 36 | } 37 | 38 | private GameState redo(UserInput input) { 39 | // nooope, you' ll write this one yourself 40 | return GameState.PLAYING; 41 | } 42 | 43 | private GameState undo(UserInput input) { 44 | // nooope, you' ll write this one yourself 45 | return GameState.PLAYING; 46 | } 47 | 48 | private GameState doPlay(UserInput input) { 49 | if (canPlace(input.getPoint().y, input.getPoint().x)) { 50 | 51 | getBoard()[input.getPoint().y][input.getPoint().x] = currentPlayer; 52 | 53 | GameState gameState = fetchGameState(); 54 | if (gameState == GameState.PLAYING) { 55 | switchPlayers(); 56 | } 57 | return gameState; 58 | } 59 | return GameState.PLAYING; 60 | } 61 | 62 | private GameState fetchGameState() { 63 | // check rows 64 | for (int y = 0; y < BOARD_LENGTH; y++) { 65 | int first = getBoard()[y][0]; 66 | boolean allInRowAreSame = true; 67 | for (int x = 1; x < BOARD_LENGTH; x++) { 68 | allInRowAreSame &= (getBoard()[y][x] != UNSET && getBoard()[y][x] == first); 69 | } 70 | if (allInRowAreSame) { 71 | return chooseWinner(first); 72 | } 73 | } 74 | 75 | // check cols 76 | for (int x = 0; x < BOARD_LENGTH; x++) { 77 | int first = getBoard()[0][x]; 78 | boolean allInColAreSame = true; 79 | for (int y = 1; y < BOARD_LENGTH; y++) { 80 | allInColAreSame &= (getBoard()[y][x] != UNSET && getBoard()[y][x] == first); 81 | } 82 | if (allInColAreSame) { 83 | return chooseWinner(first); 84 | } 85 | } 86 | 87 | // check diagonals 88 | int firstOnD1 = getBoard()[0][0]; 89 | int firstOnD2 = getBoard()[0][BOARD_LENGTH - 1]; 90 | boolean d1AreAllTheSame = true; 91 | boolean d2AreAllTheSame = true; 92 | for (int d = 0; d < BOARD_LENGTH; d++) { 93 | d1AreAllTheSame &= (getBoard()[d][d] != UNSET && getBoard()[d][d] == firstOnD1); 94 | d2AreAllTheSame &= (getBoard()[d][BOARD_LENGTH - 1 - d] != UNSET && getBoard()[d][BOARD_LENGTH - 1 - d] == firstOnD2); 95 | } 96 | if (d1AreAllTheSame) { 97 | return chooseWinner(firstOnD1); 98 | } 99 | if (d2AreAllTheSame) { 100 | return chooseWinner(firstOnD2); 101 | } 102 | 103 | return canPlaceAnywhere() ? GameState.PLAYING : GameState.DRAW; 104 | } 105 | 106 | public boolean canPlaceAnywhere() { 107 | // check still playable 108 | for (int y = 0; y < BOARD_LENGTH; y++) { 109 | for (int x = 0; x < BOARD_LENGTH; x++) { 110 | if (canPlace(y, x)) { 111 | return true; 112 | } 113 | } 114 | } 115 | return false; 116 | 117 | } 118 | 119 | private GameState chooseWinner(int boardValue) { 120 | return boardValue == PLAYER_1 ? GameState.PLAYER_1_WON : GameState.PLAYER_2_WON; 121 | } 122 | 123 | private void switchPlayers() { 124 | currentPlayer++; 125 | currentPlayer %= 2; 126 | } 127 | 128 | private boolean canPlace(int y, int x) { 129 | return inBounds(y, x) && !isOwnedByP1(y, x) && !isOwnedByP2(y, x); 130 | } 131 | 132 | private boolean inBounds(int y, int x) { 133 | return x >= 0 && y >= 0 && x < BOARD_LENGTH && y < BOARD_LENGTH; 134 | } 135 | 136 | public boolean isOwnedByP1(int y, int x) { 137 | return getBoard()[y][x] == PLAYER_1; 138 | } 139 | 140 | public boolean isOwnedByP2(int y, int x) { 141 | return getBoard()[y][x] == PLAYER_2; 142 | } 143 | 144 | public boolean isEmpty(int y, int x) { 145 | return getBoard()[y][x] == UNSET; 146 | } 147 | 148 | public int[][] getBoard() { 149 | return board; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/src/com/hackbulgaria/corejava/Problems2Impl.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava; 2 | 3 | public class Problems2Impl implements Problems2 { 4 | 5 | @Override 6 | public boolean isOdd(int number) { 7 | return false; 8 | } 9 | 10 | @Override 11 | public boolean isPrime(int number) { 12 | // TODO Auto-generated method stub 13 | return false; 14 | } 15 | 16 | @Override 17 | public int min(int... array) { 18 | // TODO Auto-generated method stub 19 | return 0; 20 | } 21 | 22 | @Override 23 | public int kthMin(int k, int[] array) { 24 | // TODO Auto-generated method stub 25 | return 0; 26 | } 27 | 28 | @Override 29 | public float getAverage(int[] array) { 30 | // TODO Auto-generated method stub 31 | return 0; 32 | } 33 | 34 | @Override 35 | public long getSmallestMultiple(int upperBound) { 36 | // TODO Auto-generated method stub 37 | return 0; 38 | } 39 | 40 | @Override 41 | public long getLargestPalindrome(long N) { 42 | // TODO Auto-generated method stub 43 | return 0; 44 | } 45 | 46 | @Override 47 | public int[] histogram(short[][] image) { 48 | // TODO Auto-generated method stub 49 | return null; 50 | } 51 | 52 | @Override 53 | public long doubleFac(int n) { 54 | // TODO Auto-generated method stub 55 | return 0; 56 | } 57 | 58 | @Override 59 | public long kthFac(int k, int n) { 60 | // TODO Auto-generated method stub 61 | return 0; 62 | } 63 | 64 | @Override 65 | public int getOddOccurrence(int[] array) { 66 | // TODO Auto-generated method stub 67 | return 0; 68 | } 69 | 70 | @Override 71 | public long pow(int a, int b) { 72 | // TODO Auto-generated method stub 73 | return 0; 74 | } 75 | 76 | @Override 77 | public long maximalScalarSum(int[] a, int[] b) { 78 | // TODO Auto-generated method stub 79 | return 0; 80 | } 81 | 82 | @Override 83 | public int maxSpan(int[] array) { 84 | // TODO Auto-generated method stub 85 | return 0; 86 | } 87 | 88 | @Override 89 | public boolean canBalance(int[] array) { 90 | // TODO Auto-generated method stub 91 | return false; 92 | } 93 | 94 | @Override 95 | public int[][] rescale(int[][] original, int newWidth, int newHeight) { 96 | // TODO Auto-generated method stub 97 | return null; 98 | } 99 | 100 | @Override 101 | public String reverseMe(String argument) { 102 | // TODO Auto-generated method stub 103 | return null; 104 | } 105 | 106 | @Override 107 | public String copyEveryChar(String input, int k) { 108 | // TODO Auto-generated method stub 109 | return null; 110 | } 111 | 112 | @Override 113 | public String reverseEveryWord(String arg) { 114 | // TODO Auto-generated method stub 115 | return null; 116 | } 117 | 118 | @Override 119 | public boolean isPalindrome(String argument) { 120 | // TODO Auto-generated method stub 121 | return false; 122 | } 123 | 124 | @Override 125 | public boolean isPalindrome(int number) { 126 | // TODO Auto-generated method stub 127 | return false; 128 | } 129 | 130 | @Override 131 | public int getPalindromeLength(String input) { 132 | // TODO Auto-generated method stub 133 | return 0; 134 | } 135 | 136 | @Override 137 | public int countOcurrences(String needle, String haystack) { 138 | // TODO Auto-generated method stub 139 | return 0; 140 | } 141 | 142 | @Override 143 | public String decodeURL(String input) { 144 | // TODO Auto-generated method stub 145 | return null; 146 | } 147 | 148 | @Override 149 | public int sumOfNumbers(String input) { 150 | // TODO Auto-generated method stub 151 | return 0; 152 | } 153 | 154 | @Override 155 | public boolean areAnagrams(String A, String B) { 156 | // TODO Auto-generated method stub 157 | return false; 158 | } 159 | 160 | @Override 161 | public boolean hasAnagramOf(String string, String string2) { 162 | // TODO Auto-generated method stub 163 | return false; 164 | } 165 | 166 | } 167 | -------------------------------------------------------------------------------- /10-StructuredData/problems.md: -------------------------------------------------------------------------------- 1 | #### First, download all the files in testData/links.md 2 | 3 | #### Parse this XML 4 | Now, as you have the latest-stub-articles xml from Wikipedia, it's time to test the two XML parsers in java to see which is faster, and why. 5 | 6 | ###### Parse it with the DomParser. 7 | Use the [DOMParser](http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/) to parse the xml file and get a `Document` instance. 8 | Do not go through all the nodelists and nodes, just obtain the `Document` instance from the `parse` method. 9 | Notice the ammount of time needed for the `DocumentBuilder` to parse your file. 10 | 11 | 12 | ###### Parse it with the SAXPasrer 13 | Use the [SAXParser](http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/) to parse the xml file. Extend `DefaultHandler`, and see the time needed. 14 | 15 | 16 | ###### Hints: 17 | In order to **measure** the time needed for an operation to complete in java, check out the `System.currentTimeMillis()` : ) 18 | 19 | 20 | 21 | ###### Count the number of different 22 | As the file format above is something like: 23 | ``` 24 | 25 | Translations:Wikimedia Foundation elections/FDC Ombudsperson elections/2013/13/en 26 | 1198 27 | 2239772 28 | 29 | 5552639 30 | 5394284 31 | 2013-06-09T12:36:44Z 32 | 33 | FuzzyBot 34 | 1058846 35 | 36 | Importing a new version from external source 37 | 38 | lwdr5q15u1n9bsxgipym50earq8tpd8 39 | wikitext 40 | text/x-wiki 41 | 42 | 43 | ``` 44 | 45 | I'd like you to print the username of the **wikipedia contributor, that has contributed the most!** 46 | Choose between the two major parsers and use one of them. Use and combine the `startElement`, `endElement`, and `characters` methods in your extension of `DefaultHandler` (if you are using `SAXParser`, or use XPath or XQuery + `Document` if you prefer and like the DOMParser more (for some reason). 47 | 48 | Friendly advice: **If you haven't use the DOM Parser in Java, don't use it here. You won't like it. It is slow, as it builds up the whole tree. You don't need that. Also, XPath and XQuery are not as easy as they seem.** 49 | 50 | 51 | 52 | #### Serializing, deserializing and Bindings with JAXB/Jettison 53 | Create a class `CoreJavaCourse` with fields 54 | ``` 55 | List enrolledStudents 56 | int courseId 57 | String courseName 58 | ``` 59 | A `Student` class has the following: 60 | ``` 61 | int studentId 62 | String name 63 | ``` 64 | 65 | 66 | Now: 67 | 0) in a main method: Create an instance of the `CoreJavaCourse` class. 68 | 1) Create a JAXBContext of this class and the class Student. 69 | 2) Obtain a Marshaller from the `JAXBContext` instance. 70 | 3) Marshal the `CoreJavaCourse` instance. 71 | 4) Verify that you have correct xml output to the console. 72 | 73 | 4.5) Create an Unmarshaller from the `JAXBContext` instance. 74 | 5) Unmarshal the file to an instance. 75 | 6) Override the `toString()` method and print it to the console, verifying that you have unmarshalled the xml file properly. 76 | 77 | 7) Now, let's switch the whole procedure to JSON! We will reuse are @XML bindings, but we will just produce JSON 78 | 8) First, download and link the [jettison library](http://repo1.maven.org/maven2/org/codehaus/jettison/jettison/1.3.3/jettison-1.3.3.jar) 79 | 9) Create a `MappedNamespaceConvention` instance. 80 | 10) Create an instance of `MappedXMLStreamWriter` instance using the `MappedNamespaceConvention` instance you just created. 81 | 11) On your `Marshaller` instance, call the `marshal` method, but giving it the `MappedXMLStreamWriter` instance you just created. This instance will apply the conversion from XML to JSON, so be sure you pass your `MappedXMLStreamWriter` argument! 82 | 12) Now, you can go and check the file you've just marshalled to (or the console, if you've marshalled to the console). You see the output is JSON. 83 | 13) Repeat the procedure, but for unmarshalling, this time using a `MappedXMLStreamReader` instance. See if you can work your way **without** looking at the resources. 84 | 85 | If somewhere along the process you get lost, check out the `materials.md` file provided. Be wary - the contents there are basically everything you need and you will **learn nothing if you just head there and copy-paste some code. Don't do that. Try to understand the whole process, what is happening and why.** 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /20-Exam2/problems.md: -------------------------------------------------------------------------------- 1 | ### Part1 - Java theoretical(knowledge-based) test 2 | 3 | ###### 1. What are the differences between a 'wrapper class' and a 'primitive type' in Java? What is autoboxing and autounboxing? 4 | 5 | ###### 2. How many types of Exceptions do you know? When do we use them? 6 | 7 | ###### 3. What is the relation between Throwable, Exception, and Error? 8 | 9 | ###### 4. Explain the semantics of try-catch-finally. 10 | 11 | ###### 5. Explain the difference between a LinkedList and ArrayList in java. 12 | 13 | ###### 6. What is the difference between an interface and an abstract class (Java 7)? 14 | 15 | ###### 7. What is the difference between JDK and JRE? 16 | 17 | ###### 8. Explain how arguments are 'passed' to methods in java. What happens if the argument is a primitive type? What happens if it is an instance type? Write an example 18 | 19 | ###### 9. Explain the contract between hashCode() and equals() 20 | 21 | ###### 10. Explain the access modifiers public, protected, /*default*/, private 22 | 23 | ###### 11. What does a 'final' class mean? What happens when I declare a variable 'final'? When I declare a field 'final'? 24 | 25 | ###### 12. Explain the difference between Thread.start() and Thread.run() 26 | 27 | ###### 13. Tell me what you know about InterruptedException. 28 | 29 | ###### 14. How do I stop a thread in java? 30 | 31 | ###### 15. Why can I not make 'new T()' in java? (where T is a generic type here) 32 | 33 | ###### 16. Explain the wait-notify mechanism in Java - preferably with an example. 34 | 35 | ###### 17. When should we use an Enum? 36 | 37 | ###### 18. Explain what happens when you instantiate a type, e.g. 'new A()'. Explain the process as thoroughly as you can. 38 | 39 | ###### 19. Where can I use a 'for-each' loop in java? 40 | 41 | ###### 20. Write-out some of the methods defined in Object 42 | 43 | ###### 21. Draw a picture of the 'Collections' hierarchy -as much as you can remember. 44 | 45 | ### Part2 - Interesting language-agnostic questions 46 | 47 | ###### 1. Explain what happens when you enter a URL in the address bar of your browser and press 'Enter'. Explain as thoroughly as you can. 48 | 49 | ###### 2. Give an example of a deadlock using only 'synchronized' statements (or semaphor/mutexes, if you prefer). For just 2 threads. 50 | 51 | ###### 3. Explain the Iterator pattern. What does it help us achieve? Why is it used? Give as much (relevant) information as you can. (C#/Java/C++ details don't matter). 52 | 53 | ###### 4. You have a website, but sometimes the server crashes. You want to know the moment it does, and ensure it restarts. What would you do? 54 | 55 | ###### 5. Explain what a garbage collector system does. Explain the difference between finalizers(Java) and destructors. 56 | 57 | ######* Give an example where Java/C# code would be faster than code in C++. 58 | 59 | ######* Give an example where Java/C# code would be particulary painstakingly slower than C/C++ 60 | 61 | ### Part3 - Coding problems - use Java or close-to-Java pseudocode 62 | 63 | ###### 1. Reverse every word in a sentence. "This is a string" => "sihT si a gnirts" 64 | 65 | ###### 2. You are given a list of numbers - {1,2,3,4,5,7,19,23,3,2}. 66 | - 1) Retain only the unique items from the list. 67 | - 2) Get only the duplicating numbers. 68 | - 3) Get only the first non-duplicating element 69 | 70 | ###### 3. You are given a sorted, but rotated array. For instance, A = {3,4,5,6,7,1,2,3} 71 | Find all the indices of a given number, for instance `yourFunction(3, A) => {0,7} . 72 | 73 | ###### 4. You are given two (singly) linked lists -A and B. Can you check whether A merges in B? (Whether A and B have a common element). Give the fastest algorithm you can come up with. 74 | 75 | ### Part 4 - Practical OOP 76 | You have several fields in a web registration form. 77 | Let's say name, email, secondary email, personalHosting, phone, etc. (Secondary email = email that should be used in case you don't answer your first email.) 78 | You need to validate user input from them. 79 | 80 | Validation rules: 81 | - For `personalHosting` - it should just have a valid hostname and a TLD(that's a .bg, .com, etc). For instance `abv.bg` is a valid field entry. Notice http:// or https:// is not mandatory. 82 | - For `name` - it should not contain numbers 83 | - For `phone` - it should contain numbers only. 84 | - For `secondary_email` - it should just *be a valid email => it should have some letters/digits, a `@` sign, and a hostname and a TLD. 85 | - For `email` - it should both *be a valid email* and *it should not be already taken* (imagine you can do a `boolean isAlreadyTaken(String email)` written for you. 86 | 87 | Your code is activated like this: 88 | ```java 89 | boolean validate(FieldType field) 90 | //FieldType is an enum containing PERSONAL_HOSTING, NAME, PHONE, SECONDARY_EMAIL, EMAIL 91 | 92 | ``` 93 | Give a good OOP solution for the cases described, aiming to avoid code/logic duplication. It should scale well when a new 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/src/com/hackbulgaria/corejava/game2048/GameBoard.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.game2048; 2 | 3 | import java.awt.Point; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import com.hackbulgaria.corejava.game2048.GameBoard.MoveDirection; 8 | 9 | public class GameBoard { 10 | public static final int BOARD_SIZE = 4; 11 | private static final int GAME_WIN_NUMBER = 2048; 12 | private final int[][] board; 13 | 14 | public enum MoveDirection { 15 | MOVE_UP(0, -1), MOVE_DOWN(0, 1), MOVE_LEFT(-1, 0), MOVE_RIGHT(1, 0); 16 | private MoveDirection(int xAdd, int yAdd) { 17 | this.xAddition = xAdd; 18 | this.yAddition = yAdd; 19 | } 20 | 21 | private final int xAddition; 22 | private final int yAddition; 23 | } 24 | 25 | public enum GameResult { 26 | WIN, LOSE, UNDETERMINED 27 | } 28 | 29 | public GameBoard() { 30 | board = new int[BOARD_SIZE][BOARD_SIZE]; 31 | initOneSquare(); 32 | initOneSquare(); 33 | } 34 | 35 | private void initOneSquare() { 36 | int x = random(); 37 | int y = random(); 38 | 39 | // loop until we get a free square 40 | while (!isEmpty(y, x)) { 41 | x = random(); 42 | y = random(); 43 | } 44 | 45 | board[y][x] = twoOrFour(); 46 | } 47 | 48 | private boolean isEmpty(int y, int x) { 49 | return board[y][x] == 0; 50 | } 51 | 52 | private static int random() { 53 | return random(BOARD_SIZE); 54 | } 55 | 56 | private static int random(int n) { 57 | return GlobalRandom.INSTANCE.nextInt(n); 58 | } 59 | 60 | private static Iterable pointIterator(MoveDirection direction) { 61 | List points = new ArrayList<>(); 62 | switch (direction) { 63 | case MOVE_RIGHT: 64 | for (int y = 0; y < BOARD_SIZE; y++) { 65 | for (int x = BOARD_SIZE - 1; x >= 0; x--) { 66 | points.add(new Point(x, y)); 67 | } 68 | } 69 | break; 70 | case MOVE_LEFT: 71 | for (int y = 0; y < BOARD_SIZE; y++) { 72 | for (int x = 0; x < BOARD_SIZE; x++) { 73 | points.add(new Point(x, y)); 74 | } 75 | } 76 | break; 77 | case MOVE_UP: 78 | for (int x = 0; x < BOARD_SIZE; x++) { 79 | for (int y = 0; y < BOARD_SIZE; y++) { 80 | points.add(new Point(x, y)); 81 | } 82 | } 83 | break; 84 | case MOVE_DOWN: 85 | for (int x = 0; x < BOARD_SIZE; x++) { 86 | for (int y = BOARD_SIZE - 1; y >= 0; y--) { 87 | points.add(new Point(x, y)); 88 | } 89 | } 90 | break; 91 | } 92 | 93 | return points; 94 | } 95 | 96 | public GameResult move(MoveDirection direction) { 97 | int xAddition = direction.xAddition; 98 | int yAddition = direction.yAddition; 99 | for (Point p : pointIterator(direction)) { 100 | if (isEmpty(p.y, p.x)) { 101 | continue; // skip empty points 102 | } 103 | int cx = p.x; 104 | int cy = p.y; 105 | do { 106 | cx += xAddition; 107 | cy += yAddition; 108 | } while (isInBounds(cy, cx) && isEmpty(cy, cx)); 109 | 110 | // we've gotten out of bounds 111 | if (!isInBounds(cx, cy)) { 112 | board[cy - yAddition][cx - xAddition] = board[p.y][p.x]; 113 | if (p.x != cx - xAddition || p.y != cy - yAddition) { 114 | board[p.y][p.x] = 0; 115 | } 116 | continue; 117 | } 118 | 119 | // we've reached another square 120 | else if (!isEmpty(cy, cx)) { 121 | if (board[cy][cx] == board[p.y][p.x]) { 122 | board[cy][cx] *= 2; 123 | board[p.y][p.x] = 0; 124 | } else { 125 | board[cy - yAddition][cx - xAddition] = board[p.y][p.x]; 126 | if (p.x != cx - xAddition || p.y != cy - yAddition) { 127 | board[p.y][p.x] = 0; 128 | } 129 | } 130 | } 131 | } 132 | 133 | GameResult result = checkBoardState(); 134 | if (result == GameResult.UNDETERMINED) { 135 | initOneSquare(); 136 | } 137 | 138 | return result; 139 | } 140 | 141 | private GameResult checkBoardState() { 142 | boolean hasEmpty = false; 143 | for (int y = 0; y < BOARD_SIZE; y++) { 144 | for (int x = 0; x < BOARD_SIZE; x++) { 145 | if (board[y][x] == GAME_WIN_NUMBER) { 146 | return GameResult.WIN; 147 | } 148 | if (isEmpty(y, x)) { 149 | hasEmpty = true; 150 | } 151 | } 152 | } 153 | return hasEmpty ? GameResult.UNDETERMINED : GameResult.LOSE; 154 | } 155 | 156 | private boolean isInBounds(int cy, int cx) { 157 | return cx >= 0 && cy >= 0 && cx < BOARD_SIZE && cy < BOARD_SIZE; 158 | } 159 | 160 | // 90% chance to initialize with 2, 10% with 4 161 | private int twoOrFour() { 162 | return random(10) == 9 ? 4 : 2; 163 | } 164 | 165 | public int getValue(int y, int x) { 166 | return board[y][x]; 167 | } 168 | 169 | public boolean canMove(MoveDirection direction) { 170 | Iterable iterable = pointIterator(direction); 171 | for (Point candidate : iterable) { 172 | boolean isRealPoint = !isEmpty(candidate.y, candidate.x); 173 | if (!isRealPoint) { 174 | continue;// discard 0's 175 | } 176 | 177 | int destY = candidate.y + direction.yAddition; 178 | int destX = candidate.x + direction.xAddition; 179 | boolean isDestInBounds = isInBounds(destY, destX); 180 | boolean isDestEmpty = isDestInBounds && isEmpty(destY, destX); 181 | boolean canUpScore = isDestInBounds && board[destY][destX] == board[candidate.y][candidate.x]; 182 | 183 | if (isDestInBounds && (isDestEmpty || canUpScore)) { 184 | return true; 185 | } 186 | } 187 | return false; 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /13-Networking1/problems.md: -------------------------------------------------------------------------------- 1 | ### Print your own IP address! 2 | 3 | Print your own IP address in HackBulgaria's wireless network, using the classes `NetworkInterface`, and `InetAddress`. 4 | See http://docs.oracle.com/javase/tutorial/networking/nifs/listing.html for help. 5 | 6 | Your netowоrk interface is the one that **is up** and **is not a loopback interface** and **is not a virtual interface**. 7 | If you have more than 1 network interface with those criteria, use the one your internet connection comes from. For example, if you have `wlan0` and `eth0` both connected, but the HackBulgaria network is set at the `wlan0`, pick the `wlan0` device using `getName()` method 8 | 9 | ### Find all available hosts in your network 10 | Using the `InetAddress#isReachable()` method find the IP's of every reachable host in your network. 11 | 12 | 13 | 14 | ### Create/Implement a simple socket-based RBI backdoor-protocol. (Team work) 15 | `RBI` stands for Remote Bash Invocation - the ability to invoke bash commands from a client to a server. (something like ssh, but simplified) Don't look for RBI on google, I just made it up. 16 | 17 | Craete an **RBI-Protocol**, **RBI-Server** and **RBI-Client** applications. 18 | 19 | An **RBI-Server** does the following: 20 | - Accepts an incoming socket connection 21 | - Retrieves a **command** string from the incoming connections socket's input stream. 22 | - Executes the command using `Runtime.getRuntime().exec` methods 23 | - Logs to the command line the command being executed and the start time of execution. 24 | - Retrieves the output of the command executed. 25 | - Logs to the command line that the command executed has finished and logs the time of execution. 26 | - Writes it back to the incoming connection socket's output stream. 27 | - The server **supports only one client at a time** 28 | - The server **does not break when the user gets an invalid command**. 29 | 30 | An **RBI-Client** does the following: 31 | - Receive a 'server' IP as a command line parameter from `args[0]`; 32 | - Connect to the server ip given. 33 | - Echo a 'Connection successfull' message to the user. 34 | - Accept a user command **from the command line**. 35 | - Let's say the user enters 'ls /tmp'. 36 | - You need to write the user command to the output stream of your connected socket. 37 | 38 | The **RBI-Protocol** project **holds** the following: 39 | - A class for all constants related to the protocol. For example, the port the server starts in. 40 | - The 'EOM' (End-of-message) String - you can use something like `<[?!EOM!?]>` 41 | - Holds the logic for **reading an RBI message from a socket** - has a utility method that **receives** a connected socket and returns 1 message from it. If there is no message, return null or block (choice is yours). 42 | - Holds the logic for **writing an RBI message to a socket** - has a utility **void** method that **receives** a connected socket and a message => and writes the message to the socket's output stream. 43 | 44 | Hints and tips: 45 | - Both **RBI-Server** and **RBI-Client** projects should **depend on** the **RBI-Protocol** class in their build path (e.g. so they can see the protocol-related constants) 46 | - After every message writing, **append your 'EOM' string**. (Preferably as a new line) 47 | - When you read a message from a socket, **read until you see an 'EOM' line** 48 | - Use `PrintWriter` for writing and be very careful to **flush** all your messages. 49 | - Watch out for blocks: You should know that `read` operations from socket's input stream will **block** if there is nothing in the stream. But if you implement the 'EOM' concept properly, you should have no problem at all. 50 | - Watch out for firewall-related problems. Temporarily disable your: 51 | - - Windows firewall, if you have one. 52 | - - MAC OS X firewall, if you have one. 53 | - - `sudo iptables -F` if you are on Linux. (Don't worry, they will be restored on next boot!) 54 | 55 | 56 | ##### You are done? Excellent 57 | Can you make the client-server application you've just build in order to **stream the ascii ART representation** of a picture located on your partner's laptop? Use the ASCII art jar you built in the previous sessions. 58 | 59 | What happens when you try to do the same, but with a .gif file instead? 60 | 61 | ##### Send and receive files 62 | Just adding to our fantasy protocol: 63 | - In **RBI-Client** if the user writes **rbi-send ** the client writes: `<[?!FILENAME?!]>name-of-the-file\n`, gets the file and writes it to the outputstream, after that adding a **newline**. After that, the client adds `<[!?EOM?!]>` on a newline. 64 | - In **RBI-Server** if the server sees a `<[?!FILENAME?!]>` command, it parses it until it sees **end-of-line** symbol, gets all the bytes until it sees a newline. Saves it to a file in `/home//.RBI/files/file-name` 65 | 66 | 67 | ##### Implement a simple 'login' procedure as a part of the RBI protocol 68 | Just adding this to our fantasy protocol: 69 | - Every connection starts with the client writing the following: 70 | ``` 71 | username:MyUserName\n 72 | hash:MyHash 73 | ``` 74 | - The server parses both the username and the password and decides whether or not to allow the connection: 75 | - For instance, you can check whether the username and hash are contained in a file called `/home//.RBI/.allowedUsers`. It can be xml, json, .properties, or just plain text. I recommend .properties format + usage of [Apache Commons Configuration](http://commons.apache.org/proper/commons-configuration/userguide/howto_filebased.html#File-based_Configurations), but you can use plain text and parsings if you want to. 76 | - If the server decides **not to** accept the connection, the server writes **Unathorized.\n401** and **closes** the socket. 77 | - If the server decides to accept the connection, the server writes **OK.\n200**. 78 | 79 | -------------------------------------------------------------------------------- /17-JavaTooling/problems.md: -------------------------------------------------------------------------------- 1 | ### Assure you have Maven properly installed 2 | ``` 3 | mvn -v 4 | Apache Maven 3.0.4 5 | Maven home: /usr/share/maven 6 | Java version: 1.7.0_55, vendor: Oracle Corporation 7 | Java home: /usr/lib/jvm/java-7-openjdk-i386/jre 8 | Default locale: en_US, platform encoding: UTF-8 9 | OS name: "linux", version: "3.5.0-37-generic", arch: "i386", family: "unix" 10 | 11 | ``` 12 | Any OS will do, and any Maven >= 3.0.0 will do. 13 | 14 | ### Maven in 5 minutes tutorial 15 | Execute maven in 5 minutes from here: 16 | http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html 17 | 18 | 19 | ### Stop the Tomcat instance launched from Eclipse 20 | Shutdown Eclipse's use of tomcat. We will not let Eclipse manage tomcat for us this time. 21 | Forget Run as -> Server. We won't be using that again. 22 | 23 | If you do not have running Tomcat instance from Eclipse, you don't have to do anything. 24 | Else, just click on the red button in the'Servers' view. 25 | 26 | (If you've just launched Eclipse, you don't have to do anything) 27 | 28 | ### Check out tomcat's installation directory 29 | -Go to your tomcat installation directory. For me, it was `/home/georgi/Dev/tomcat/` 30 | -Do an `ls` and notify me when you get there. 31 | 32 | - `tomcat/bin` => All the binaries for tomcat. If you need to start or stop tomcat, there are the binaries you need. 33 | - `tomcat/conf` => All the configuration files for tomcat. tomcat-user.xml and others 34 | - `tomcat/webapps` => The most important folder of all. You must delpoy your web applications here. 'Deploying' means copying one .war file to your webapps dir. 35 | 36 | One web application = one .war file. It's like a .jar file, but it means 'webarchive' (.war). 37 | 38 | -Start your tomcat using `startup.sh` or `startup.bat` in the `/bin/` folder. 39 | 40 | -Go to http://localhost:8080 . Do you see the cat? You need to see the cat. 41 | -Now take a look at http://localhost:8080/examples/ 42 | 43 | -Take a note - if you let eclipse manage your tomcat, you won't see neither a cat nor examples. 44 | 45 | -Edit the tomcat-users.xml file in `your-tomcat-dir/conf`. See the commented lines and add *2 roles* one with a `rolеname="manager"` and the other with a `rolеname="manager-gui"`. 46 | -Create a user with username "a" and password "a" with the role of "manager-gui" 47 | -Create a user with username "test" and password "test" with the role of "manager" 48 | -Save tomcat-users.xml 49 | 50 | -Open http://localhost:8080/manager . Authenticate with "a"/"a". 51 | -What you are seeing now is something called the "Tomcat Manager". Here you can see what applications do you have deployed, which of them are running, etc. If you have any problems with web applications, that's the place to check first: 52 | -1) Your web application should be DEPLOYED 53 | -2) Your web application should be RUNNING 54 | 55 | ### In Eclipse 56 | - Create your Dynamic Web project. Name your project 'AsciiService'. 57 | - Create a servlet echoing "Hello World!" to the writer in the `doGet` method 58 | - Convert it to a Maven project. (Right click on project -> Configure -> Convert to Maven). Leave the groupId and artifactId intact, but delete the "-SNAPSHOT" part from the versioning string. 59 | Enter name and description of your project. 60 | - Notice the immediate creation of a pom.xml file 61 | - Go to pom.xml and click the "pom.xml" tab (it's below the editor window) 62 | - If you ever need to change anything on the namings, it's there. 63 | - Using the UI, (Right click on your project -> Maven -> Add dependency), try and add a dependency. Let's say, add apache's commons-io library. Latest version. 64 | - You may need to enable global repository indexing in order for your dependency search to work. See http://stackoverflow.com/questions/18523044/how-to-force-maven-repository-indexing-in-eclipse. 65 | - See the changes in your pom.xml file (You now have a 'dependencies' tag and subtags...) Next time, just manually copy-paste the 'dependacy' tag from the library vendor in your pom.xml (at the appropriate tag-location, of course) 66 | - Update your project (right click on project -> Maven -> Update project) 67 | - Try using apache-commons-io (for instance, invoke a static method on `IOUtils` class). If your code compiles, than you have sucessfully added a dependency. 68 | 69 | ### Show time 70 | Now, it's time to delve deep. I want you to bridge maven with your eclipse project. 71 | Your goal here: every time you make a change on your project, executing `mvn install` should *upload your project to the webapps folder* in `\webapps`. 72 | - 1) You can use the tomcat7 plugin for maven. See http://stackoverflow.com/questions/15824096/how-to-deploy-war-with-maven-to-tomcat (test results with `mvn clean tomcat7:deploy`) 73 | - 2) You can use a simple maven-anttask-plugin. See http://www.itcuties.com/tools/maven-3-deploy-war-package/ (test results with `mvn install`) 74 | - 3) 1) is the harder route, but it's the better route. You'll learn more by doing 1). If it's half an hour until the end of the session, better choose 2) 75 | 76 | 11) If you've done 1), there is one more step. You can see your war being deployed by doing `mvn clean tomcat:deploy`. But we want this to happen only on `mvn install`. 77 | Follow http://www.avajava.com/tutorials/lessons/how-do-i-attach-a-plugin-goal-to-a-particular-phase-of-a-maven-lifecycle.html to **invoke a goal on a phase**. 78 | 79 | ### Extra 80 | If you are ready, just implement the rest of the 'AsciiService' project. You need to receive a file (via POST, like a file-upload), process it and return the ascii representation of the file. Implement it with pictures only. Use [Apache FileUpload] http://commons.apache.org/proper/commons-fileupload/ at the server side and [Apache HTTP Client] http://hc.apache.org/httpclient-3.x/ at the client side 81 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/problems1.md: -------------------------------------------------------------------------------- 1 | ###1. Is it an odd number?### 2 | ```boolean isOdd(int n)``` 3 | Return whether n is an odd number 4 | 5 | ###2. Is N prime?### 6 | ```boolean isPrime(int N)``` 7 | 8 | ###3. Find the minimum element of an array### 9 | ```int min(int... array)``` 10 | 11 | ###4. Find the kth minimal element of an array### 12 | ```int kthMin(int k, int[] array)``` 13 | *There will be no duplicates in the array. If they are duplicates in the test, ignore them (my bad).* 14 | 15 | ###5. Find the average(средно аритметично) of the elements of an array### 16 | ```int getAverage(int[] array);``` 17 | 18 | ###6. Double factorial### 19 | ```long doubleFac(int n);``` 20 | return 21 | E.g. if n=3, => (3!)! = 6! = 720 22 | 23 | ###7. Kth factorial### 24 | ```long kthFac(int k, int n);``` 25 | Get the kthFactorial of n. k is guaranteed to be positive. 26 | *Bonus* no "helper" methods, no recursion :) 27 | 28 | ###8. Smallest multiple### 29 | ```long getSmallestMultiple(int upperBound);``` 30 | 31 | Find the smallest (positive) number, that can be divided by each of the numbers from 1 to *upperBound*. 32 | 33 | ###9. Find the largest integer palindrome number up to N### 34 | ```long getLargestPalindrome(long N);``` 35 | 36 | 1234321 is a palindrome. You are given a number => *N*. 37 | Find the largest number < N, that is a palindrome. 38 | 39 | *Bonus* do this without using Collections.sort 40 | 41 | ###10. Grayscale image histogram### 42 | ```int[] histogram(short[][] image)``` 43 | 44 | A histogram is a representation of distribution of some data. 45 | 46 | Here you receive a grayscale image matrix (*image*). Each of the matrix's values will be between 0 and 255. 47 | Return an array *result*, which is a histogram of *image* => the value of *result[i]* should be the ammount of times *i* is in the matrix *image*. 48 | 49 | ###11. Raise an integer to a power of another### 50 | ```long pow(int a, int b)``` 51 | 52 | Write a O(log(b)) solution. 53 | 54 | ###12. Find the only number, that occurs odd times in an array### 55 | ```int getOddOccurrence(int... array)``` 56 | 57 | Every element in array will occur an even ammount of times. There will be exactly one element 58 | Example: {1,2,2,1,3,4,3,4,4,6,5,6,5} => 4 occurs only an odd number of times. 59 | 60 | ###13. Maximal scalar product### 61 | ```long maximalScalarSum(int[] a, int[] b)``` 62 | You are given two vectors, *a* and *b*. Let a be ```{a1,a2,a3}``` and b be ```{b1,b2,b3}```. The scalar product of vectors *a* and *b* is the number ```a1*b1 + a2*b2 + a3*b3``` 63 | 64 | Find a permutation of a, and a permutation of b, for which their scalar product is the largest possible. 65 | 66 | ###14. Max span### 67 | ```int maxSpan(int[] numbers)``` 68 | Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found in the given array. 69 | 70 | maxSpan({1, 2, 1, 1, 3}) → 4 71 | maxSpan({1, 4, 2, 1, 4, 1, 4}) → 6 72 | maxSpan({1, 4, 2, 1, 4, 4, 4}) → 6 73 | 74 | ###15. Can balance?### 75 | ```boolean canBalance(int[] numbers)``` 76 | 77 | canBalance({1, 1, 1, 2, 1}) → true 78 | canBalance({2, 1, 1, 2, 1}) → false 79 | canBalance({10, 10}) → true 80 | 81 | Return true if there is an element in the array, where you can split the array in half and the sum of left side would be equal to the sum of the right part. 82 | 83 | ###16. Rescale an image using nearest neighbour interpolation### 84 | ```int[][] rescale(int[][] original, int newWidth, int newHeight)``` 85 | 86 | You are given an image *original*. Rescale it to newWidth, newHeight, using nearest neighbour interpolation. (See http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation) 87 | 88 | 89 | ###17. Reverse a String### 90 | `String reverseMe(String argument)` 91 | 92 | ###18. Reverse each word in a String### 93 | `String reverseEveryChar(String arg)` 94 | 95 | `reverseEveryChar("What is this") => tahW si siht` 96 | 97 | ###18. Is this string a palindrome### 98 | `boolean isPalindrome(String argument)` 99 | 100 | ###19. Is this number a palindrome### 101 | `boolean isPalindrome(int argument)` 102 | 103 | 104 | ###18. Copy every character K times ### 105 | `String copyEveryChar(String input, int k)` 106 | 107 | `copyEveryChar("tldr", 3) => "tttllldddrrr"` 108 | Important Note: There is an error in the unit test. 109 | If you are failing on this line: 110 | `assertEquals("ttt www rrr", problems2.copyEveryChar("t w r", 2));` 111 | It is because is shoud be "3" instead of "2" as an argument at the end. 112 | (My bad). 113 | 114 | 115 | 116 | ###19. Check for palindrome length around '*' ### 117 | `int getPalindromeLength(String input)` 118 | 119 | `getPalindromeLength("taz*zad") => 2` 120 | 121 | ###20. Count number of (non-overlapping) occurences ### 122 | `int countOcurrences(String needle, String haystack)` 123 | `countOcurrences("da", "daaadaadada") => 4` 124 | 125 | *Bonus* Only 1 line of code allowed. No loops :) 126 | 127 | ###21. Decode an URL ### 128 | Input 'kitten%20pic.jpg' 129 | Output 'kitten pic.jpg' 130 | %20=>' ' 131 | %3A=>':' 132 | %3D=>'?' 133 | %2F=>'/' 134 | `String decodeUrl(String input)` 135 | 136 | 1 line of code is allowed. 137 | 138 | ###22. Sum all the numbers in a String### 139 | `int sumOfNumbers(String input)` 140 | 141 | Sum all of the numbers in the String. Ignore the characters. 142 | `sumOfNumbers("abc123dd34") => 157` 143 | `sumOfNumbers("12 99 1) => 112` 144 | 145 | ###23. Is String A an anagram of String B?### 146 | `boolean anagram(String A, String B)` 147 | See http://en.wikipedia.org/wiki/Anagram 148 | 149 | No HashMaps, hashSets, or such stuff allowed : ) 150 | Note: The last unit test is a *faulty* one. Delete it. (My bad). 151 | ###24. Is an anagram of String A a susbstring in B?### 152 | `boolean hasAnagramOf(A,B)` 153 | Return whether an anagram of String A can be found in String B. 154 | -------------------------------------------------------------------------------- /05-Exceptions/problems5.md: -------------------------------------------------------------------------------- 1 | All tasks should go into 'Exceptions1' project in your workspace. 2 | 3 | ### Unchecked (runtime) exception example usage 4 | Design an unchecked Exception class "DatabaseCorruptedException", which is to be thrown whenever a corrupted database object is detected (e.g. "" for username in table `Users`). 5 | Use good and concise exception message, explaining what is wrong with the object `User` object - for this excercise you can assume that the `username` field is "". 6 | 7 | *Database Corruption is not expected to happen. People should not need to 'catch' an eventual database corruption on every interaction/transaction with a database, because this is not an expected situation and it is not OK to be fault-tolerant on such scenarios* 8 | 9 | Make a method that throws this exception. Use it and see your message in the stack trace. 10 | 11 | ### Checked exception example usage 12 | Imagine you are designing an API for using services. 13 | 14 | *In the real world, services break all the time. Network connections go down, firewalls go crazy, routers get re(s)tarted, etc. It is more or less expected of you to be network fault-tolerant, as networks are not perfect and they just can't be.* 15 | 16 | For this task, you need to **first create an Exception class, a checked one (`extends Exception`), give it a good long-ish name, like `ServiceNotAvailableAtTheMoment`, and encapsulate some information about the situation in the exception.** For example, it would be cool if in the exception message you write possible reasons for the service breakdown, what could have gotten wrong, etc. 17 | 18 | *Exceptions messages and traces are watched by **developer**. It is a sign of courtesy and respectfullness to write good, descriptive and concise exception messages to help people that investigate when things go wrong.* 19 | 20 | After you are done designing your good looking Exception class, you should declare your a method (e.g. `useService`) that is **declared to throw your exception**. 21 | After you are done with that, try and use your method. 22 | Observe how every time you use it, you are forced to think *what will happen if this service fails?*. 23 | 24 | 25 | ### Make the 'Time' class fool-proof 26 | Remember you wrote a `Time` class, some weeks ago? Go back, copy your class into your project and **make it fool-proof**. Protect the poor public user of your class using exceptions. Think of some unpleasent (or edge-case) situations that may occur while using your class. 27 | 28 | Hint: Check http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html and 29 | http://stackoverflow.com/questions/15208544/when-should-illegalargumentexception-be-thrown 30 | 31 | ### Do not allow them to insert null as a key! 32 | You know HashMap in java. They are completely happy with (null, null) key-value pairs. 33 | Let's say we are not happy with this being the default behavior. Especially for **keys**. 34 | 35 | Extends `HashMap` and make it optional for your class to accept null **keys**, but by default, set this option to `false`. (Use a flag, make a constructor with the option.) 36 | Fix the `put`, `get` methods accordingly to allow or not allow null keys. 37 | What should you do in those methods if your object is set not to allow null keys? Throw your very own, good-named, custom-made exception with a good message, of course. 38 | 39 | ### Impement your very own immutable list 40 | Create a class 'ImmutableList', which implements List. It's okay to extend something else. 41 | Your delcaration should be like this: 42 | `public class Immutable extends ArrayList` 43 | 44 | But make your instances immutable, and throw exception when anyone tries to modify them. 45 | Of course, in order for your class to be immutable, you need good constructors. 46 | Make a constructor that accepts a `Collection collection` in which you add all the elements from `collection` to your list, and forbid anyone to modify it by throwing an exception when anyone tries to do that. 47 | 48 | Implement `Arrays.asList()` factory method functionality - declare a static method ` List asList(T... arguments)`. 49 | Use the `@SafeVarargs` annotation on top of your method declararation to tell the compiler you won't be naughty. 50 | 51 | ### Implement a XmlMarkupBuilder class ### 52 | Make an easy to use XmlMarkupBuilder class, which creates a **valid xml** 53 | 54 | We won't worry about namespaces here. By valid, I mean having the `` declaration, and having only tags, attributes, and text between a tag opening and tag closing. 55 | 56 | For instance: 57 | ``` 58 | 59 | attr 60 | 61 | 62 | 63 | 64 | Hey dude check it out 65 | why are you out of scope, man? 66 | 67 | 68 | ``` 69 | 70 | Your class should support these operations: 71 | ```java 72 | XmlMarkupBuilder openTag(String tagName); 73 | XmlMarkupBuilder addAttr(String attrName, String attrValue); // valid only when you have a tag opened! 74 | XmlMarkupBuilder addText(String text); 75 | XmlMarkupBuilder closeTag(); //close the last opened tag. 76 | XmlMarkupBuilder finish(); //close all tags and finelize your object. Any open,addAttr or other calls to your object, should throw an Exception. 77 | String getResult(); //let's stay close to http://en.wikipedia.org/wiki/Builder_pattern 78 | ``` 79 | 80 | Example usages of your `XmlMarkupBuilder` class 81 | ```java 82 | XmlMarkupBuilder markupBuilder = new XmlMarkupBuilder(); 83 | 84 | //http://en.wikipedia.org/wiki/Fluent_interface ftw 85 | String validMarkup = markupBuilder.openTag("body").addAttr("background","0xFF0000").addText("Helo HTML!").finalize().getResult(); 86 | markupBuilder.closeTag() //BOOOM! Object finalized! Exception! 87 | ............... 88 | XmlMarkupBuilder markupBuilder = new XmlMarkupBuilder(); 89 | markupBuilder.openTag("a").closeTag().openTag("a") //BOOOM! You need to have a root XML object, XML is not a list! 90 | ............... 91 | XmlMarkupBuilder markupBuilder = new XmlMarkupBuilder(); 92 | markupBuilder.openTag("a").closeTag().closeTag() //BOOOM! What the hell are we closing?! 93 | ............... 94 | XmlMarkupBuilder markupBuilder = new XmlMarkupBuilder(); 95 | markupBuilder.openTag("a").closeTag().addAttribute("href","https://www.youtube.com/watch?v=P5ft_7Bcyc4") //BOOOM! What are you adding attribute to? 96 | 97 | and so on and so on 98 | ``` 99 | -------------------------------------------------------------------------------- /12-SmallProject/problems.md: -------------------------------------------------------------------------------- 1 | ## Project 1 - Design and implement a TicTacToe game (PairProgramming/Github workflow) 2 | Design (classes and code-flow) for a TicTacToe game. Do not start implementing until you have a very clear picture. 3 | 4 | The minimal requirements: 5 | 6 | - Game is played by two people - `User1` and `User2`. They take turns - first enters `User1`, after that `User2`. 7 | - Users input the move via console like this: "0 1" // first row, second column y => 0, x = 1 8 | - When `User1` wins, a "Player 1 wins!" text should be seen on the screen. 9 | - When `User2` wins, a "Player 2 wins!" text should be seen on the screen. 10 | - If the game is a tie, "It's a draw!" text should be seen on the screen. 11 | - Otherwise, the game board should be printed before every move. 12 | - If a user inputs **q**, the game should **exit immediately**. 13 | - We are very likely to add other features to the game, and more complex user input is likely to follow. 14 | 15 | ###### Some hints and tips: 16 | 17 | - Core game logic should **not** be in the **main** method! 18 | - Distinguish game/board **visualization** from **game logic**. 19 | - User keyboard input and error handling logic **must** be separated from **game logic**. Design your game so that a Swing (window-based) visualization can be easily added later on **with as few in-class modifications as possible** 20 | - Implement the game only on the console. Use 'X' for player 1, and 'O' for player 2. (Or use swing for GUI, if you feel up to it). 21 | - Use good naming conventions, make your code presentable. 22 | - Matrices are usually easier to visualize by both developer and users when using an y-first approach. 23 | ``` 24 | 1 2 3 25 | 4 5 6 26 | 27 | input: 1 2 //row 1, col 2 => 6 28 | ``` 29 | 30 | 31 | ###### Additional: Implement a simple undo-redo. 32 | Now imagine User1 has made a bad choice. He now wants to undo his choice and User2 is OK with that. 33 | If a user enters **u**, it means **undo** - the game must revert its previous state - the board just as it was before player 1 has made his bad choice. 34 | Also, it is his turn again : ) 35 | If a user enters "r", it means 'redo' - the user now wants to undo his undo - resulting in a 'redo' operation - again, change of turns is happening. 36 | If a user makes an **undo operation**, and does a new move, the **redo** operations become unavailable. 37 | Design an 'Undo-Redo' solution. You may or may not use the classical [Memento](http://en.wikipedia.org/wiki/Memento_pattern) solution to this problem. 38 | If you are into it, you can use the [Command pattern](http://gamedevelopment.tutsplus.com/tutorials/let-your-players-undo-their-in-game-mistakes-with-the-command-pattern--gamedev-1391) for this undo redo, but I personally don't recommend this approach for this task. 39 | 40 | 41 | ###### Additional: User inputs 42 | If a user presses **n**, the board is cleared and the game starts all over. **Starting a new game can be undone.** 43 | If a user presses **s**, his game gets saved (see below). 44 | If a user presses **l**, his game gets loaded (see below). **Loading can be undone** 45 | 46 | 47 | ###### Additional: Implement a simple save-load mechanism 48 | When the user decides he wants to quit, don't lose his game forever. Save it to a location with a format of your choosing. You can use binary format + [serialization](http://www.tutorialspoint.com/java/java_serialization.htm). It is up to you. 49 | When launching the game, if **the user has a save, restore it**. 50 | 51 | ###### Additional: The most simple AI in the world 52 | Now, it's all cool playing with two players. How about playing against the CPU? 53 | Read a command-line argument `multiplay`. By default `multiplay` should be false. 54 | Example: 55 | ``` 56 | java -jar yourJar.jar //launches your game with you playing against the CPU. 57 | java -jar yourJar.jar multiplay //launches your game with 2 players 58 | ``` 59 | 60 | The 'AI' here is just as complex and smart as Brazil's gameplan against Germany. 61 | However, make sure your 'AI' approach is extensible - meaning that you could very very easy replace the AI if you wanted. Don't hardcode anything. See [Strategy pattern](http://java.dzone.com/articles/design-patterns-strategy) 62 | ###### AI round one: Random moves 63 | Make the stupidest AI on the planet earth. Force your bot to choose a random location. Be wary when choosing locations, you should only use free positions. 64 | 65 | ###### AI round two: Random moves + finishing strategy. 66 | Your AI should check if there is a move that he can make that will make him an instant winner. If not, move at random. 67 | 68 | 69 | ## Project 2 - a 2048 implementation (PairProgramming/GithubWorkflow) 70 | Have you played 2048? The tradition is simple: nobody explains you the rules, you figure them out yourself. See http://gabrielecirulli.github.io/2048/ 71 | Design (classes and code flow) for a 2048 game. Don't start implementing until you have a very clear picture of the classes you are going to use. 72 | 73 | Minimal requirements: 74 | - Game is played by one player. 75 | - He/she/it inputs its move via the **console**. 76 | - When the player wins, a "You've won!" message gets displayed. 77 | - When the player loses, a "You've lost :(" message gets displayed. 78 | - The game board gets printed before every move. 79 | - A chance of a random '4' spawning instead of a '2' is 10%. 80 | - If a user enters **q**, the game must **exit imediately** 81 | - Design your game in a way that GUI visualization can be easily added later. 82 | 83 | 84 | ###### Hints/tips: 85 | - Core game logic must not be in your **main** class/method! 86 | - User input getting must be **decoupled** from core game logic! 87 | - Game **visualization** should be **decoupled** from core game logic. 88 | - Use good naming conventions, make your code presentable. 89 | - Matrices are usually easier to visualize by both developer and users when using an y-first approach. 90 | ``` 91 | 1 2 3 92 | 4 5 6 93 | 94 | input: 1 2 //row 1, col 2 => 6 95 | ``` 96 | - Core game logic here might be a bit more difficult, but we have only 1 player. 97 | 98 | 99 | ###### Additional: Undo-Redo 100 | You've made a wrong choice in 2048 and you want to rip all of your hair. Don't! There is a simple solution - just press **u**, and the game will undo! If you want to repeat your move, press **r** - your undone move will be redone. 101 | However, if you **undo** a move and then make a new move, there is no **redo** for you. (What happens when you go gone back in the past and kill your grandfather?) 102 | 103 | ###### Additional: User inputs 104 | If a user presses **n**, the board is cleared and the game starts all over. **Starting a new game can be undone.** 105 | If a user presses **s**, his game gets saved (see below). 106 | If a user presses **l**, his game gets loaded (see below). **Loading can be undone** 107 | 108 | ###### Additional: Do not require 'enter' for taking input. 109 | Did you know you could read the console without having to wait for a 'return'(Enter)? You could use `Jline` to do that. See [Terminal](http://jline.sourceforge.net/apidocs/jline/Terminal.html), and most notably the `setupTerminal` and `read` methods. 110 | 111 | ###### Additional: Implement a simple save-load mechanism 112 | When the user decides he wants to quit, don't lose his game forever. Save it to a location with a format of your choosing. You can use binary format + [serialization](http://www.tutorialspoint.com/java/java_serialization.htm). It is up to you. 113 | When launching the game, if **the user has a save, restore it**. 114 | 115 | 116 | -------------------------------------------------------------------------------- /03-OOP1/problems3.md: -------------------------------------------------------------------------------- 1 | ###OOP fun!### 2 | 3 | ###1### 4 | Make a class Car. 5 | Make several(at least 4) subtypes of Car, representing the different brands of cars - Audi, BMW, Wolkswagen (of course!), etc. 6 | 7 | Implement the toString method, to match the type of the class. For example, an object of type Audi should return "Audi@1f52ac3"; 8 | 9 | ###2### 10 | 11 | Make a class `Time` to hold information about the current time and *the current date* . 12 | 13 | Make an *easy-to-use* constructor (from client perspective), that would represent the time and date the client wants to hold in your class. 14 | 15 | Implement the toString() method, returning the time and date in format : "hh:mm:ss dd.MM.YY". 16 | 17 | Check out String.format method 18 | 19 | *Bonus* 20 | Make a factory method `now()` for your class, returning the Time at the present moment :) 21 | 22 | See http://en.wikipedia.org/wiki/Factory_method_pattern 23 | 24 | ###3### 25 | 26 | Make a class `Pair`, representing a pair of *Objects* (later we will revisit this with Generics) 27 | 28 | Create getter methods for the first and second member of the pair. 29 | http://stackoverflow.com/questions/2036970/how-do-getters-and-setters-work 30 | 31 | Implement the toString method, giving a meaningful representation of the class. 32 | Override the equals method from Object => two pairs are equal if both their members are equal. 33 | 34 | Make the class *immutable*. 35 | ###4### 36 | 37 | Create and implement a class `StackImpl`, representing a... well, stack. 38 | 39 | Think about all the required (public) operations needed, so that one can use a stack class. You know, stuff like actually pushing an element, popping an element, length, clear, isEmpty, stuff like that. Think about the return types of those operations (see task 5, you may get a hint about one). *Extract them all to an interface `Stack`, which your class should implement*. 40 | 41 | ###5### 42 | 43 | Create an implementation of your `Stack` interface, which has the added invariant: 44 | -It does not allow an element to be duplicated. If there is an element 'a' in the stack, and some smart guy pushes 'a' again, his operation should fail, and the smart guy should have a way to know this. 45 | 46 | 47 | ###6### 48 | 49 | Implement a (doubly-linked) list (using ints only). Just as before, extract all of its required public operations in an interface. Some of those operations are add, *remove*, size, get(int elementIndex), getHead (getFirst), getTail(getLast), etc. 50 | Think good and hard about your implementation, and whether you will need another class for a List Node. 51 | 52 | ###7### 53 | Implement your own `Stack` with your own (doubly) `LinkedList` class : ) 54 | 55 | *Bonus* implement a unique stack just as before, but using your `LinkedList` and an *anonymous implementation*, combined with a factory method. 56 | See http://www.programmerinterview.com/index.php/java-questions/java-anonymous-class-example/ 57 | 58 | Return your anonymous implementation from a factory method! 59 | 60 | ###8### 61 | Make a mutable class 'Matrix' represeting a NxM (int[][]) matrix. Think good about your constructors, your data. Your goal is to make this class as convenient as possible for the person using it. 62 | 63 | Your class `Matrix` should have another cool thing about it => it would allow operations with every pixel. 64 | In order for this to work, your class should declare a public method `operate(MatrixOperation op)` 65 | 66 | Where `MatrixOperation` is an interface, containing a method 'int withPixel(int x, int y, int[][] matrix)'. 67 | *Think - why are we getting x, y, and the matrix instead of just passing the pixel value?* 68 | 69 | Implement the toString(), converting the whole matrix into a String in a way that it would be visible on the console. 70 | 71 | The method should `operate(MatrixOperation op)` should call the `withPixel` method for every x and y in the matrix and assign the result of `withPixel` to the matrix. 72 | 73 | Now that you have this, implement: 74 | -a naive binarization filter, using a simple threshold, for instance 127. 75 | -a naive gaussian blur filter, which just averages the color of this pixel by using the colors of its neighbour pixels! 76 | 77 | *Bonuses* - Use a *local class* to fetch information about the matrix using the MatrixOperation interface. 78 | 79 | Make an implementation of MatrixOperation, that you can use to: 80 | - get average of pixels 81 | - get most used color in the matrix 82 | - get an image histogram of the matrix 83 | 84 | See http://docstore.mik.ua/orelly/java-ent/jnut/ch03_11.htm 85 | 86 | ###9### 87 | Create a friendly interactive calculator in java 88 | Bundle, execute and test your program as a jar file. 89 | 90 | Example usage of your program: 91 | ``` 92 | java -jar yourJar.jar 93 | Hello! 94 | 95 | Enter expression:> 5 96 | Output:> 5.0 97 | Enter expression:> 3 + (5 + 9*7 + 9) 98 | Output:> 78 99 | Enter expression:> 4*(4 + 5) 100 | Output:> 36 101 | Enter expression:> exit 102 | 103 | Bye! 104 | ``` 105 | 106 | 107 | Supported operations: 108 | - addition 109 | - multiplication 110 | - division (this is not integer division! 2/3 = 0.666666667, not 0!) 111 | - brackets 112 | - Negative numbers. 113 | 114 | Multiplication and addition take precedence and have higher priority than addition. 115 | Priority list: () before * before / before + before - 116 | 117 | Your program should support a *variable* ammount of spaces in the expression, as shown in the output below. 118 | 119 | *Hints* 120 | - Use this class if you have trouble reading from system.in: https://gist.github.com/GeorgiPachov/bcc51f1fc3b3a1de1bce 121 | - Write this program in a TDD way, but *iteratively*. Start from the easiest 'features', add tests for them,and build up on them after you are sure they are rock-solid. 122 | - Do not worry about invalid input: 123 | `123/213/123/1/2/23/3 //order of divisions is undefined here, do what is easier for you.` 124 | `(12 + 5) + 65) //brackets mashup => this is invalid input` 125 | `(12++-*3) //operators mashup => this is invalid input` 126 | - There is no need to use any collections here. 127 | - There is no need to use any generics here. 128 | - There is no need to use any regular expressions here. You will probably just need to escape some stuff when calling `String.replace`, e.g. to replace a '+', you will need to call `someString.replace("\\+","my replaced output)` (because + is from regex syntax. And because `replace` accepts a regex input as a String, not as a Pattern, which is actually not the smartest decision in the world). 129 | 130 | But if you think regexes will help you here and will make your life easier, you are free to use them. 131 | Use http://docs.oracle.com/javase/tutorial/essential/regex/ for reference 132 | and http://www.tutorialspoint.com/java/java_regular_expressions.htm for example usage. 133 | 134 | 135 | *Bonus challenge objectives* 136 | - Use less than 120 lines of code in total for all classes. (not counting bonuses implementations and unit tests, you can test as much as you like there!) 137 | - Add factorial operation support. It should precede multiplication and division, but bracket rules should apply. 138 | Examples: 139 | ``` 140 | java -jar your Jar.jar: 141 | Hello! 142 | 143 | Output:> 5.0 144 | Enter expression:> (5+3)! 145 | Output:> 40320.0 146 | Enter expression:> (2*3 + 1*3)! 147 | Output:> 362880.0 148 | Enter expression:> 9! 149 | ``` 150 | - Add 'power' support: 2^3 = 8, 3^2 = 9, etc. It has the same priority as multiplication! 151 | Examples: 152 | ``` 153 | java -jar your Jar.jar: 154 | Hello! 155 | 156 | Enter expression:> 3^2 + 2^3 157 | Output:> 17.0 158 | Enter expression:> 2^3 + (5+3)^2 159 | Output:> 72.0 160 | Enter expression:> 2^3! + 5*((3+2!)^2) 161 | Output:> 189.0 162 | ``` 163 | -Add support for mashed up user input: E.g. 2+3\ should be parsed as 2+3. Discourage any symbols different from the ones you are interested in. //regexes will probably help you here, although the difference with/without is ~2 lines of code. 164 | -------------------------------------------------------------------------------- /11-OOP2/problems.md: -------------------------------------------------------------------------------- 1 | You will work in teams - minimum of 2 people per team. 2 | Here we will be focusing on architecture rather than implementation. 3 | Do not use TDD unless specified in the task. 4 | 5 | ##### Warm-up 6 | Mary has a furniture business. She has a website, which sells furniture. 7 | Mary only sells a handful of furniture - chairs and tables using only two materials - iron and wood. 8 | 9 | Unfortunately, Mary is not very good at OOP programming. 10 | Each furniture has a `getDescription()` method - the description of the furniture (for her website!) 11 | The base `Furniture` class looks like this 12 | ```java 13 | public abstract class Furniture{ 14 | protected int price; 15 | public Furniture(int price){ 16 | this.price = price; 17 | } 18 | 19 | public abstract String getDescription(); 20 | ... 21 | } 22 | ``` 23 | 24 | And now the derived classes look like this 25 | ```java 26 | public class IronChair extends Furniture{ 27 | //constructor, calling super, nothing fancy here 28 | ... 29 | @Override 30 | public String getDescription(){ 31 | return "A chair made of iron"; 32 | } 33 | } 34 | ``` 35 | 36 | ```java 37 | public class WoodenTable extends Furniture { 38 | //constructor, nothing fancy here 39 | 40 | @Override 41 | public String getDescirption(){ 42 | return "A table made of wood"; 43 | } 44 | } 45 | ``` 46 | There are 2 more similiar classes - WoodenChair and IronTable. 47 | 48 | Now, Mary is proud that her business is expanding. She will be selling sofas! Also, she has made a contract with another supplier, so now she can sell sofas, tables and chairs, made of concrete. 49 | 50 | How many new classes must Marry create? If by the next week she signs a deal with a supplier getting her furniture made of ice, and she starts selling beds, how many classes will she have to create? Make a big O estimation of the (un)scalability of Mary's furniture hierarchy. 51 | 52 | Refactor Mary's hierarchy, avoiding the forseen explosion of `Furniture` subclasses. Pseudo-code is enough. 53 | 54 | 55 | ##### Warm-up 2 - Design and implement a time tracker class (Pair Programming) 56 | A 'TimeTracker' is a class that tracks the time needed for an operation. 57 | Design a class supporting time tracking for several operations. See example usage below: 58 | 59 | Example usage 1: 60 | ```java 61 | TimeTracker timeTracker = new TimeTracker(); 62 | timeTracker.start("fileCopyOperation"); 63 | FileUtils.copy(path1, path2); 64 | timeTracker.finish("fileCopyOperation"); 65 | 66 | System.out.println(timeTracker.getReport("fileCopyOperation")); 67 | // => "Operation fileCopyOperation took 314 ms. 68 | // "11:05 08-07-2014 started" 69 | // "11:06 08-07-2014 finished" 70 | 71 | ``` 72 | 73 | 74 | Example usage 2: 75 | ```java 76 | final TimeTracker timeTracker = new TimeTracker(); 77 | timeTracker.start("asyncFileCopy"); 78 | FileUtils.copyAsync(directory1, directory2, new CopyCallback(){ //copying ALL the files in directory1 to directory2 79 | 80 | public void onFileCopied(File whichFile){ //called when one file is copied! 81 | timeTracker.update("asyncFileCopy"); 82 | 83 | } 84 | 85 | public void onAllFilesCopied(){ 86 | timeTracker.finish("asyncFileCopy"); 87 | System.out.println(timeTracker.getReport("asyncFileCopy")); 88 | } 89 | } 90 | ); //copying multiple files here! 91 | 92 | timeTracker.start("moveOpearion"); 93 | FileUitls.mv(path1,path2); 94 | timeTracker.finish("moveOperation"); 95 | System.out.println(timeTracker.getReport("moveOperation")); 96 | // "Operation moveOperation took 112 ms" 97 | "11:07 08-07-2014" - started 98 | "11:07 08-07-2014" - updated 99 | "11:08 08-07-2014" - updated 100 | "11:08 08-07-2014" - updated 101 | "11:09 08-07-2014" - finished 102 | ``` 103 | 104 | **Note: calling getReport(String) if operation has not finished is a VALID operation** 105 | 106 | 107 | #### Design and implement a 'search' method, giving the user some settings (Pair Programming) 108 | 109 | Design and implement a class (or a utility method) to carry out a prioritized search. Your method will be searching for a `String` in a `List`. Lets call them `needle` and `haystack`. 110 | It should return a `List` - the matches, in prioritiezed order. 111 | 112 | Your method should support something called **prioritized search**. 113 | Here are some predefined prioritization criteria you will need to implement and make availabe to your class's clients: 114 | 115 | - If a line in `haystack` is an exact match with needle, this is the top result. 116 | - If a line in `haystack` **begins** with `needle`, it is a second-top match. 117 | - If a line in `haystack` **contains** a `needle` **as a word**, and not a word **infix**, it is a third-rated match. 118 | - - For example, if a line in `haystack` = "Baba Pena mrazi Sergei Stanishev" && `needle` = "mrazi" => third-rated match. 119 | - - if `needle` = "mraz" => not a third-rated match. 120 | - If a line in `haystyack` **contains** needle, it is the last-based match. 121 | 122 | The **priorities** given above are just for the example. The user of your class should be able to use any your predefined criteria, as well as **his own criteria**, and **define the priorities himself**. 123 | 124 | 125 | #### Design and implement a TicTacToe game (Pair Programming) 126 | Design (classes and code-flow) for a TicTacToe game. Do not start implementing until you have a very clear picture. 127 | 128 | Read the requirements below: 129 | 130 | - Game is played by two people - User1 and User2. They take turns - first enters user A, after that - user B. 131 | - Users input its move via console like this: "0 1" // first row, second column 132 | - If a user enters "q", the game should exit immediately. 133 | - We are very likely to add other features to the game, and more complex user input is likely to follow. 134 | Some hints and tips: 135 | - Core game logic should **not** be in the **main** method! 136 | - Distinguish game/board **visualization** from **game logic**. 137 | - User keyboard input and error handling logic **must** be separated from **game logic**. Design your game so that a Swing (window-based) visualization can be easily added later on **with as few in-class modifications as possible** 138 | - Design the game in order to support **different visualizations**. Imagine we would like to add a GUI visualization later. 139 | - Implement the game only on the console. Use 'X' for player 1, and 'O' for player 2. (Or use swing for GUI, if you feel up to it). 140 | - Use good naming conventions, make your code presentable. 141 | - Matrices are usually easier to visualize by both developer and users when using an y-first approach. 142 | ``` 143 | 1 2 3 144 | 4 5 6 145 | 146 | input: 1 2 //row 1, col 2 => 6 147 | ``` 148 | 149 | 150 | ###### Additional: Implement a simple undo-redo. 151 | Now imagine User1 has made a bad choice. He now wants to undo his choice and User2 is OK with that. 152 | If a user enters "u", it means 'undo' - the game must revert its previous state - the board just as it was before player 1 has made his bad choice. 153 | Also, it is also his turn again : ) 154 | If a user enters "r", it means 'redo' - the user now wants to undo his undo - resulting in a 'redo' operation. 155 | Design an 'Undo-Redo' solution. You may or may not use the classical [Memento](http://en.wikipedia.org/wiki/Memento_pattern) solution to this problem. 156 | If you are into it, you can use the [Command pattern](http://gamedevelopment.tutsplus.com/tutorials/let-your-players-undo-their-in-game-mistakes-with-the-command-pattern--gamedev-1391) for this undo redo, but I personally don't recommend that for this task. 157 | 158 | 159 | ##### Additional: A new game 160 | If a user presses 'n', a new game instance is launched. 161 | 162 | 163 | ##### Additional: Implement a simple save-load mechanism 164 | When the user decides he wants to quit, don't lose his game forever. Save it to a location with a format of your choosing. You can use binary format + [serialization](http://www.tutorialspoint.com/java/java_serialization.htm) 165 | When launching the game, if the user has a save, restore it. 166 | 167 | 168 | 169 | -------------------------------------------------------------------------------- /07-Files1/problems.md: -------------------------------------------------------------------------------- 1 | ### Prepare utility methods for reading and writing to files 2 | 3 | Create a class `FileUtils`. Forbid it's instantiating (make the default constructor private). 4 | Create and implement a **utility** method `String readFrom(File file)`. 5 | `readFrom` should read **all the contents** from the file to a String, using the default (OS-default) charset. Do not worry about performance. 6 | 7 | As this method is an **API**, you should NOT catch the exceptions in the method's body, remember? 8 | 9 | - Add an overload `String readFrom(Path path)`. Make sure one of them calls the other, **do not let code duplication in those methods**. 10 | 11 | For this task, do not worry about performance or different encoding. 12 | 13 | 14 | Do the same for a 'write' method. 15 | Make sure you have utility methods that read from and write to files, and people can use them in 1-liners. 16 | 17 | ### Implement a 'Properties' file parser. 18 | 19 | [.properties files](http://en.wikipedia.org/wiki/.properties) are commonly used in java as a resources and configuration. They just represent a key=value pairs, where each pair is a new line. The `#` sign denotes a comment. 20 | 21 | Make a **utility** method `Map parseProperties` that reads a .properties file and returns its content as a Map. 22 | 23 | The `#`-sign, when seen as a **first character in a line**, denotes that **the line is a comment and should not be parsed**. 24 | 25 | ``` 26 | # this=comment 27 | a1=b1 28 | a2 =b2 29 | a3 = b3 30 | a4 = b4 31 | a5=b6=b7=b8 32 | a6=b9 #comment 33 | a7==b10 34 | ``` 35 | All of the above entries (`a1` to `a7`) are valid key-value pairs. 36 | The value for `a5` is `b6=b7=b8` 37 | The value for `a6` is `b9 #comment` 38 | The value for `a7` is `=b10` 39 | 40 | Hints and suggestions: 41 | - Make a helper method, that does all the parsing logic (generates the Map from List). 42 | - Do **not** split the lines on your own like `fileContents.split("\n")`. This is not a cross-platform solution. 43 | - First test your helper method, which creates the Map from a given List. 44 | - After assuring yourself your helper method works great, test the `parseProperties` method. 45 | - Create (write) your .properties file (for testing) programmatically, in `setUp`. Do not depend on external resources for testing if you can avoid it! 46 | - Do not polute the filesystem because you are writing tests. Clean up (delete the file in `tearDown`) after your each test run. Your file is relevant ONLY for the tests, and it should not outlive them. 47 | 48 | 49 | ### Implement the wc command 50 | 51 | Create a **utility** method `WordCountResult wordCount(Path path)` with an overload `WordCountResult wordCount(File file)`. 52 | As you've probably guessed, the `WordCountResult` is a custom class, having these methods 53 | ``` 54 | int getLineCount(); //returns number of lines 55 | int getWordCount(); //returns number Of words in File 56 | int getCharacterCount(); //returns number of characters in the file. 57 | ``` 58 | 59 | Follow the testing approach described in the previous task. 60 | 61 | 62 | 63 | ### Fix these subtitles 64 | Have you ever wanted to watch a movie, and all the cyrillic characters be like ������? 65 | 66 | Have you ever received emails like "Greetings, dear �������"? 67 | 68 | These things happen because of different encoding and decoding schemes used. 69 | 70 | As we all know, even text files and strings are retained as binary in memory. 71 | So if we have the string 'Dumbledore', we need to store an array of bytes to represent it. 72 | 73 | The way we choose what bytes represent 'Dumbledore' in memory is called an **encoding scheme**. (a.k.a. encoding) 74 | "windows-1251" is a type of encoding scheme. 75 | "ISO-8859-1" is another type of encoding scheme. 76 | 77 | The way we choose to convert it from a byte array to a char array is called a **decoding scheme**. 78 | 79 | **Unicode** is an industry standard of encodings. There is no good reason against an Unicode encoding scheme. 80 | UTF-8 is a good encoding scheme from the Unicode standard. (There are others, which differ slightly.) 81 | 82 | So, here you are given a text file with a Windows-1251 encoding. Your task is to convert it to UTF-8. You can test this in your browser, just open the text file and choose to view it with UTF-8 encoding. (You might have to rename it to .html though) 83 | 84 | The subtitle you need to fix are here: http://subsunacs.net/get.php?id=41854 85 | It is okay not to use TDD for this one. 86 | 87 | In summary: 88 | - Create a utility method `fixEncoding(Path path)` 89 | - Backup the subtitles file so you don't have to download it again if you fail to write it. 90 | - The text in the file given is encoded using a **windows-1251** scheme. 91 | - Conver it to UTF-8. 92 | 93 | 94 | ### Enums quick write-up 95 | Design an Enum name 'Day', containing the days => MONDAY, TUESDAY... SUNDAY 96 | 97 | Design a method greetMe(Day day), which returns a (String) different greeting per day. 98 | 99 | Example 100 | greetMe(Day.Monday) => "Holla!"; 101 | greetMe(Day.Tuesday) => "Aloha!"; 102 | 103 | ### Reduce-file-path in 1 line 104 | *This is a really quick one.* 105 | Solve the [reduce-file-path problem (number 27)] (https://github.com/HackBulgaria/Programming101/blob/master/week0/simple_problems2.md) with no more than 1 line of Java code. 106 | Check out [the normalize method] (http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#normalize%28%29) 107 | 108 | 109 | ### Find all broken links in a given folder 110 | A broken link is a link that points to something that is simply not there. 111 | Make a **utility** method that is given a folder (as a Path), and searches recursively for bad links. 112 | If it finds a bad link, it should simply print it out. 113 | 114 | How to detect a bad link? Use `Files.isSymbolicLink(path)` in order to check if a file is a link, and `Files.readSymbolicLink(path)` in order to follow it and receive its target's path. 115 | 116 | 117 | ### Implement a simple text file compression 118 | (*Optional*) 119 | 120 | Create a **utility** method `compress(Path filePath)` 121 | that reads the text from `filePath` and writes it back in a compressed way, adding the `.compr` extension (or one of your choosing). 122 | 123 | Let's have the file 124 | `Buffalo buffalo buffalo rides a buffalo buffalo buffalo.` 125 | There are a lot of repeating words here (duuh). 126 | 127 | Parse all the words from a file, add them to an index, and assign them numbers. 128 | Replace all the words in the file with their respective indices, prepending them with '~' or another letter of your choosing. 129 | E.g. our sentence becomes 130 | 131 | ~0 ~0 ~0 ~1 ~2 ~0 ~0 ~0. 132 | 133 | Implement a decompressing scheme (another **utility** method) 134 | 135 | Check out the file compression you've just made : ) 136 | 137 | 138 | ### Find all duplicated files! 139 | 140 | ##### Summary: 141 | Two files are **duplicates** if all the **bytes** from file1 are the same as the **bytes** from file2. 142 | Find and print out all touples of duplicate files. 143 | 144 | ##### Detailed 145 | 146 | We are going to make a command line java tool, that receives a folder location and finds and prints outs all groups of duplicating files, ancestors of the given folder. 147 | It is called like this: 148 | ```java 149 | java -jar duplicates-finder.jar /home/georgi/Dev 150 | 151 | //Ouput below: 152 | //Group A 153 | /home/georgi/Dev/eclipse/settings.xml 154 | /home/georgi/Dev/ADT/settings.xml //duplicate 155 | /home/georgi/Dev/eclipse/plugins/default/settings.xml //duplicate 156 | 157 | //Group B 158 | /home/georgi/Dev/eclipse/update-site.xml 159 | /home/georgi/Dev/ADT/update-site.xml //duplicate 160 | /home/georgi/Dev/tmp/copies/site_backup.xml //duplicate 161 | 162 | //Group C 163 | /home/georgi/Dev/eclipse/readme.txt 164 | /home/georgi/Dev/workspace/Project1/data/readme.txt //duplicate 165 | 166 | 3 groups of duplications found. 167 | A total of 5 duplicate files can be deleted, freeing up /*the sum of the lengths of those 5 files*/ disk space 168 | ... 169 | ``` 170 | 171 | All the files from Group A are equivalent (every file from Group A has the same contents). 172 | Same for group B and group C. As you can see, the **name** of the file does not matter. 173 | File A can be a duplicate of file B regardless of them having different names. 174 | 175 | 176 | Hints: 177 | - When visiting files, be careful with links. You should check if the file currently being visited is a link by using `Files.isSymbolicLink(Path)`. If the file happens to be a symbolic link, find and use **it's target**, by using `Files.readSymbolicLink(pathOfSymbolicLink);`. 178 | - When following symbolic links in the way described above, be careful, because symbolic links may lead to files that **do not exist** (broken links). Your program should not stop working merely because it saw a broken link! 179 | - Ignore files with size over 512KB. If we want our tool to work for large files, the task get's a little bit more interesting and non-trivial :) 180 | - Be very careful when dealing with **OS-Special files (devices files)**. You should ignore them, as the OS call might block/hang when you try to read or write into of them. Use `Files.isRegular(path)` to check whether a file is a normal file, or it's a special file and we should probably not play with it. 181 | - Create a folder `testData` in your project. Create several folders and files with which you can test your problem. If you are too lazy for that, just download and unzip [this test data] (https://github.com/HackBulgaria/Core-Java-1/blob/master/7-Files1/testData.zip) in your project. 182 | [More spoilers and possible approaches] (https://gist.github.com/GeorgiPachov/039d2c339358dbfcc650) 183 | 184 | 185 | 186 | 187 | -------------------------------------------------------------------------------- /01-TypesArraysStrings/Project1/test/com/hackbulgaria/corejava/tests/Problems2Tests.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava.tests; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertFalse; 5 | import static org.junit.Assert.assertTrue; 6 | import static org.junit.Assert.fail; 7 | 8 | import java.util.Arrays; 9 | 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | import com.hackbulgaria.corejava.Problems2; 14 | import com.hackbulgaria.corejava.Problems2Factory; 15 | 16 | public class Problems2Tests { 17 | 18 | private static final String NOT_IMPLEMENTED = "NOT IMPLEMENTED"; 19 | private final Problems2 problems2 = Problems2Factory.createProblems2Instance(); 20 | 21 | private void notImplemented() { 22 | fail(NOT_IMPLEMENTED); 23 | } 24 | 25 | @Test 26 | public void testIsPrime() { 27 | assertTrue(problems2.isPrime(5)); 28 | assertTrue(problems2.isPrime(7)); 29 | assertTrue(problems2.isPrime(41)); 30 | assertTrue(problems2.isPrime(3)); 31 | assertTrue(!problems2.isPrime(39)); 32 | } 33 | 34 | @Test 35 | public void testIsOdd() { 36 | assertTrue(problems2.isOdd(3)); 37 | assertTrue(problems2.isOdd(5)); 38 | assertTrue(problems2.isOdd(7)); 39 | assertTrue(problems2.isOdd(-1)); 40 | assertTrue(problems2.isOdd(-3)); 41 | assertTrue(!problems2.isOdd(0)); 42 | } 43 | 44 | @Test 45 | public void testMin() { 46 | int min = problems2.min(1, 3, 4, 5, 6, -1, 23, -125, 125125, -63262, 2151, -1212); 47 | assertTrue(min == -63262); 48 | 49 | min = problems2.min(-1, 0, 1, 1, -1, -9, 0, 5); 50 | assertTrue(min == -9); 51 | } 52 | 53 | @Test 54 | public void testKthMin() { 55 | int testArr[] = new int[] { 1, 2151, 125, 125, 1125, 16, 754, 132, 613, -51521, 51251, 675, 125366 }; 56 | Arrays.sort(testArr); 57 | 58 | assertTrue(testArr[0] == problems2.kthMin(1, testArr)); 59 | assertTrue(testArr[1] == problems2.kthMin(2, testArr)); 60 | assertTrue(testArr[2] == problems2.kthMin(3, testArr)); 61 | } 62 | 63 | @Test 64 | public void testGetAverage() { 65 | int testArr[] = new int[] { 1, 2151, 125, 125, 1125, 16, 754, 132, 613, -51521, 51251, 675, 125366 }; 66 | 67 | float avg = 0; 68 | for (int i = 0; i < testArr.length; i++) { 69 | avg += testArr[i]; 70 | } 71 | avg /= testArr.length; 72 | 73 | assertEquals(avg, problems2.getAverage(testArr), 0.01f); 74 | } 75 | 76 | @Test 77 | public void testGetSmallestMultiple() { 78 | assertEquals(2520, problems2.getSmallestMultiple(10)); 79 | assertEquals(232792560, problems2.getSmallestMultiple(20)); 80 | 81 | } 82 | 83 | @Test 84 | public void testGetLargestPalindrome() { 85 | assertEquals(99, problems2.getLargestPalindrome(100)); 86 | assertEquals(99_999, problems2.getLargestPalindrome(10_0000)); 87 | assertEquals(123_321, problems2.getLargestPalindrome(123_456)); 88 | } 89 | 90 | @Test 91 | public void testHistorgram() { 92 | final short[][] image = new short[10][10]; 93 | assertEquals(100, problems2.histogram(image)[0]); 94 | 95 | for (short i = 0; i < image.length; i++) { 96 | for (short j = 0; j < image[0].length; j++) { 97 | image[i][j] = (short) (i * image[0].length + j); 98 | } 99 | } 100 | 101 | assertEquals(1, problems2.histogram(image)[13]); 102 | 103 | for (short i = 0; i < image.length; i++) { 104 | for (short j = 0; j < image[0].length; j++) { 105 | image[i][j] = (short) (i * j + j); 106 | } 107 | } 108 | } 109 | 110 | @Test 111 | public void testDoubleFac() { 112 | assertEquals(720, problems2.doubleFac(3)); 113 | assertEquals(2, problems2.doubleFac(2)); 114 | } 115 | 116 | @Test 117 | public void testKthFac() { 118 | assertEquals(3628800, problems2.kthFac(1, 10)); 119 | assertEquals(3628800 / 10, problems2.kthFac(1, 9)); 120 | testDoubleFac(); 121 | } 122 | 123 | @Test 124 | public void testGetOddOccurrence() { 125 | int[] numbers = new int[] { 1, 1, 3, 3, 6, 5, 4, 6, 5, 9, 1, 1, 3, 15, 4, 5, 9, 3, 15 }; 126 | assertEquals(5, problems2.getOddOccurrence(numbers)); 127 | } 128 | 129 | @Test 130 | public void testPow() { 131 | assertEquals(8, problems2.pow(2, 3)); 132 | assertEquals(-1, problems2.pow(-1, 9)); 133 | assertEquals(1, problems2.pow(99, 0)); 134 | 135 | assertEquals(-32, problems2.pow(-2, 5)); 136 | assertEquals(729, problems2.pow(3, 6)); 137 | } 138 | 139 | @Test 140 | public void testMaximalScalarSum() { 141 | int[] a = new int[] { 1, 2, 3, 4, 5, 6 }; 142 | int[] b = new int[] { 0, 0, 0, 0, 0, 0 }; 143 | 144 | assertEquals(0, problems2.maximalScalarSum(a, b)); 145 | b = new int[] { 1, 1, 1, 1, 1, 1 }; 146 | 147 | assertEquals(21, problems2.maximalScalarSum(a, b)); 148 | 149 | b = new int[] { 5, 4, 8, 9, -1, 2 }; 150 | assertEquals(129, problems2.maximalScalarSum(a, b)); 151 | 152 | } 153 | 154 | @Test 155 | public void testMaxSpan() { 156 | assertEquals(4, problems2.maxSpan(new int[] { 1, 2, 1, 1, 3 })); 157 | assertEquals(6, problems2.maxSpan(new int[] { 1, 4, 2, 1, 4, 1, 4 })); 158 | assertEquals(6, problems2.maxSpan(new int[] { 1, 4, 2, 1, 4, 4, 4 })); 159 | } 160 | 161 | @Test 162 | public void testCanBalance() { 163 | assertTrue(problems2.canBalance(new int[] { 1, 1, 1, 2, 1 })); 164 | assertFalse(problems2.canBalance(new int[] { 2, 1, 1, 2, 1 })); 165 | assertTrue(problems2.canBalance(new int[] { 10, 10 })); 166 | } 167 | 168 | @Test 169 | public void testRescale() { 170 | final int[][] original = new int[100][100]; 171 | int counter = 0; 172 | for (int y = 0; y < original.length; y++) { 173 | for (int x = 0; x < original[0].length; x++) { 174 | original[y][x] = counter++; 175 | } 176 | } 177 | 178 | final int newWidth = 10; 179 | final int newHeight = 10; 180 | 181 | final int[][] newImage = problems2.rescale(original, newWidth, newHeight); 182 | assertEquals(newImage[0][0], original[0][0]); 183 | assertEquals(newImage[9][9], original[90][90]); 184 | assertEquals(newImage[0][9], original[0][90]); 185 | assertEquals(newImage[9][0], original[90][0]); 186 | } 187 | 188 | @Test 189 | public void testStringReverse(){ 190 | assertEquals("ytrewq", problems2.reverseMe("qwerty")); 191 | assertEquals("How about", problems2.reverseMe("tuoba woH")); 192 | assertEquals(" ", " "); 193 | assertEquals("This is bad", problems2.reverseMe(problems2.reverseMe("This is bad"))); 194 | } 195 | 196 | @Test 197 | public void testReverseWords(){ 198 | assertEquals("tahW si siht", problems2.reverseEveryWord("What is this")); 199 | assertEquals("yrevE drow si desrever", problems2.reverseEveryWord("Every word is reversed")); 200 | } 201 | 202 | @Test 203 | public void testIsPalindrome(){ 204 | assertEquals(true, problems2.isPalindrome("radar")); 205 | assertEquals(false, problems2.isPalindrome("Nixin")); 206 | assertEquals(false, problems2.isPalindrome("Nikon")); 207 | assertEquals(true, problems2.isPalindrome("Nobody ydoboN")); 208 | assertEquals(false, problems2.isPalindrome("Nobody ydobom")); 209 | } 210 | 211 | @Test 212 | public void testIsPalindromeNumber(){ 213 | assertEquals(true, problems2.isPalindrome(191)); 214 | assertEquals(false, problems2.isPalindrome(1992)); 215 | assertEquals(true, problems2.isPalindrome(0x00)); 216 | } 217 | 218 | @Test 219 | public void testCopyCharacter(){ 220 | assertEquals("aaa", problems2.copyEveryChar("a", 3)); 221 | assertEquals("aabbaadd", problems2.copyEveryChar("abad", 2)); 222 | assertEquals("Wwhhaatt tthhee hheellll", problems2.copyEveryChar("What the hell", 2)); 223 | } 224 | 225 | @Test 226 | public void testPalindromStarLength(){ 227 | assertEquals(2, problems2.getPalindromeLength("taz*zad")); 228 | assertEquals(0, problems2.getPalindromeLength("tad*zad")); 229 | assertEquals(3, problems2.getPalindromeLength("tad*dat")); 230 | } 231 | 232 | @Test 233 | public void testNonOverlappingOccurrences(){ 234 | assertEquals(0, problems2.countOcurrences("demetrius", "")); 235 | assertEquals(2, problems2.countOcurrences("ab", "abandon all hope, abandon this place!")); 236 | assertEquals(2, problems2.countOcurrences("de", "deutschland uber alles, detonate all the allez")); 237 | } 238 | 239 | @Test 240 | public void testCopyEveryCharacter(){ 241 | assertEquals("ttwwrr", problems2.copyEveryChar("twr", 2)); 242 | assertEquals("ttt www rrr", problems2.copyEveryChar("t w r", 3)); 243 | } 244 | 245 | @Test 246 | public void testDecodeUrl(){ 247 | assertEquals("http://meyerweb.com/eric/tools/dencoder/", problems2.decodeURL("http%3A%2F%2Fmeyerweb.com%2Feric%2Ftools%2Fdencoder%2F")); 248 | assertEquals("http://javarevisited.blogspot.com/2012/10/10-java-string-interview-question-answers-top.html", problems2.decodeURL("http%3A%2F%2Fjavarevisited.blogspot.com%2F2012%2F10%2F10-java-string-interview-question-answers-top.html")); 249 | } 250 | 251 | 252 | @Test 253 | public void testSumOfIntegers(){ 254 | assertEquals(999, problems2.sumOfNumbers("999problemsButJavaAint0")); 255 | assertEquals(0, problems2.sumOfNumbers("000 three five -1 1")); 256 | assertEquals(2, problems2.sumOfNumbers("samir1WhatAreYou2Doing3You-4")); 257 | } 258 | 259 | @Test 260 | public void testAnagrams(){ 261 | assertEquals(true, problems2.areAnagrams("A", "A")); 262 | assertEquals(true, problems2.areAnagrams("BRADE", "BEARD")); 263 | assertEquals(true, problems2.areAnagrams("TOP CODER", "COTE PROD")); 264 | assertEquals(false, problems2.areAnagrams("TOP CODER", "COTO PRODE")); 265 | 266 | // Грешен Unit test! 267 | // assertEquals(true, problems2.areAnagrams("том месвролуко риддъл", "тук съм и лорд волдеморт")); 268 | } 269 | 270 | @Test 271 | public void testHasAnagramOf(){ 272 | assertEquals(true, problems2.hasAnagramOf("abc", "cbadfghhijh")); 273 | assertEquals(true, problems2.hasAnagramOf("abcdef", "fedbcadh")); 274 | assertEquals(true, problems2.hasAnagramOf("dirac", "libcarid")); 275 | assertEquals(false, problems2.hasAnagramOf("abc", "cbda")); 276 | } 277 | } -------------------------------------------------------------------------------- /04-CollectionsAndGenerics1/problems4.md: -------------------------------------------------------------------------------- 1 | All of these should go in a project named 'Collections1' 2 | ###0.Check if an expression of brackets is correct### 3 | Such expression is a string like `"()()())))((())("` - it has multiple brackets, your job is to check whether the expression is correct. 4 | Such expression is correct if: 5 | - it starts with a `'('` 6 | - it ends with a `')'` 7 | - the number of opening brackets equals exactly the number of closing brackets 8 | - at no point in the string the number of closing brackets is higher than the number of opening brackets. E.g. `())(()` is not a valid one, because at index 2 there is a second closing bracket with only one opening bracket. 9 | 10 | TDD, of course. 11 | 12 | *Hint (and also spoiler)* 13 | Is there a way you can use a *stack* in here? 14 | 15 | ###1.Reverse a generic collection### 16 | Declare a method, expecting a Collection and reverse it in your method. Return the same collection given, do not return a new collection!. 17 | Either use: 18 | `static void reverse (Collection collection)` 19 | or make it a concrete type: 20 | `static void reverse(Collection collection)` 21 | 22 | *Do not try to use* Collections.reverse. It works only for a List, and not for collections : ) 23 | 24 | 25 | ###2.Implement an on/off collection### 26 | Implement a Collection, in which, if you add an element twice, the element gets removed from your collection. 27 | 28 | *Hint and edge case spoiler:* How would you handle null objects? :) 29 | *Fun fact:*: As logical idea behind a collection is an abstraction of a... well, bunch of elements, allowing null actually makes no sense. 30 | Note that the java implementations are broken on several places, allowing nulls to creep into the collections, making all kinds of havoc later on. Don't blindly follow the java implementations, do better. 31 | 32 | 33 | ###3.Make a bounded queue### 34 | A bounded queue is queue with a 'limit' of maximum elements. 35 | Your `BoundedQueue` class of course should implement the `Queue` interface. 36 | Example usage of your `BoundedQueue` class: 37 | ``` 38 | BoundedQueue boundedQueue = new BoundedQueue<>(3); 39 | boundedQueue.offer(1); 40 | boundedQueue.offer(2); 41 | boundedQueue.offer(3); 42 | boundedQueue.offer(4); 43 | boundedQueue.offer(5); 44 | System.out.println(boundedQueue.toString()); //3,4,5 45 | ``` 46 | 47 | ###4.Rotate the elements of a collection### 48 | Make a void *utility* method that rotates the contents of a collection. 49 | 50 | You are given a collection containing `[one, two, three, four, five, six, seven]` 51 | "Rotating" it once means the collection becoming `[seven, one, two, three, four, five, six]` 52 | 53 | ```java 54 | void rotate(Collection collection, int rotateStep ) 55 | ``` 56 | 57 | `rotateStep` can be negative - meaning you are rotating to the left, and not to the right. 58 | 59 | 60 | ###5.Given a list contaning some duplicate values, find the first unique element### 61 | Make a *utility* method, which returns the first unique element in a given argument of type `Collection`. 62 | Example: 63 | 64 | ```java 65 | Collection ints = Arrays.asList(1,2,3,4,5,5,4,3,1); 66 | System.out.println(yourMethod(ints)) //2; 67 | ``` 68 | 69 | 70 | ###6.Given several sets, find the duplicating elements### 71 | Write a *utility* method, that takes several sets, and returns a set that contains the duplicating elements of all the other sets. 72 | 73 | ``` 74 | A = {1,2,3,4,5} 75 | B = {4,5,6} 76 | C = {5,6,7,8} 77 | ``` 78 | 79 | `yourMethd(A,B,C) => D{5}` 80 | 81 | ###7.Given a list of Students, sort them by grade### 82 | Lets say you have a `List`, where a Student is a class, containing two fields: `name` and `grade`. 83 | 84 | Sort them by their grades first. Their grades actually are integers => 2,3,4,5,6. If two students happen to have the same grades, sort those two by their names. 85 | 86 | ###8.Give me the median, quick!### 87 | Make an interface `Statistics`, which has these operations: 88 | 89 | ``` 90 | -getMean(); 91 | -getMedian(); 92 | -getMode(); 93 | -getRange(); 94 | ``` 95 | 96 | If you don't know what Mean,Median, Mode and Range are, see http://www.purplemath.com/modules/meanmode.htm 97 | 98 | Make an implementation of this interface, with an additional operation `add(int number)` (Work with integers only). 99 | I would also like to able to look through all the integers I've given you, with a `for(Integer i : isntanceOfYourClass) {... }`. 100 | 101 | So, as a client of your code, I will be adding some integers(just like in a list), and would want you to give me the mean, median, mode and range. 102 | 103 | *Bonus/Challenge* 104 | Every method from `Statistics` interface should complete in O(1) time. 105 | This is a little bit on the algorithm side, and you might need some interesting data structures : ) 106 | Come back to this when you are done with all the tasks. 107 | 108 | 109 | *Hints* 110 | Solve this one *iteratively* with TDD. 111 | 112 | 113 | ###9.Implement a class ToDoList### 114 | Imagine you have a world of stuff to do. 115 | Homeworks, courseworks, exams, even preparing for HackBulgaria! 116 | Unfortunately you do not have much time - you need to eat, you need to sleep, you need to have a good time. 117 | 118 | Now, you need to sort your priorities right! Make a class `ToDoList`, which supports the following operations: 119 | `void add(Task t)` 120 | `void markFinished(Task t)` 121 | `void markCancelled(Task t)` 122 | `Task getTop()` 123 | `boolean canFinish()` 124 | `int getRemainigTime()` //calculates the time remaining after you've done all of your tasks. 125 | 126 | ... where `Task` is a class which represents something you have to do. What data/methods should it have? What is common for all the tasks you need to get done? 127 | A `Task` should at the very least have a priority and a time required in order to finish. 128 | You should take an integer in your constructor - the ammount of hours available for each task. 129 | 130 | Example usage of your class: 131 | 132 | ```java 133 | ToDoList todo = new ToDoList(11); //11 hours remaining! 134 | todo.addTask(new StudyForAlgebraTask(10)); //maximum priority! 135 | todo.addTask(new LearnGeometryTask()); //default priority, smaller than 10 136 | todo.addTask(new GoOutTask(1.5f)); //default priority, smaller than 10 137 | todo.addTask(new SleepTask()); //straight 8 hours, of course! 138 | 139 | if (todo.canFinish()){ 140 | System.out.println("Woohoo!"); 141 | } else { 142 | System.out.println("I am ...screwed :("); 143 | } 144 | 145 | System.out.println(todo.top()) //StudyForAlgebraTask 146 | System.out.println(todo.getTimeNeeded()) //sum of the time needed for every task added in todo list 147 | ``` 148 | 149 | *Hints* 150 | See Comparable and Comparator classes in Java. Check out the PriorityQueue class. 151 | http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html 152 | 153 | ###10.Make a utility method that converts a hashMap into a very human-readable string### 154 | Make a *utility* method that takes a `HashMap` 155 | and *returns a String*, representing the HashMap. 156 | 157 | I want you to make a utility method that does this, *do not* override `toString()` in hashMap. 158 | 159 | Example: 160 | 161 | ```java 162 | String result = YourUtilsClass.yourFirstUtilMethod(map); 163 | System.out.println(result) // { key1:value1, key2:value2, key3:value3 } 164 | ``` 165 | 166 | ###11.Count occurences of words in text### 167 | Make a *utility* method that takes a `String text` and returns a map, which on every word in `text` maps the number of times this word has been used. 168 | 169 | See Example: 170 | 171 | ```java 172 | Map result = YourUtilsClass.yourSecondUtilMethod("Ninjas are all over the place! We are all going to die!"); 173 | System.out.println(YourUtilsClass.yourFirstUtilMethod(result)); 174 | ``` 175 | 176 | Outputs: 177 | 178 | ``` 179 | // { Ninjas:1, are:2, all:2, over:1, the:1, place!:1, We:1, going:1, to:1, die!:1 } 180 | ``` 181 | 182 | Retain the ordering of the elements! 183 | 184 | ###12.Cryptoanalysis fun### 185 | There is an old technique for encrypting messages - shuffling the letters. For instance, if we take the string `Godzilla`, one crypted version of it 186 | is `Mrezotti`. 187 | The cipher here is 188 | ``` 189 | G=m 190 | o=r 191 | d=e 192 | i=o 193 | l=t 194 | z=z 195 | ``` 196 | 197 | Your task here is to decrypth the following text: 198 | ``` 199 | Ajb vnf guj luqv akjvojufq . Sk qkkj egvfs Rkhfwu Lumemu'q akhhfjvq kj vnf ohifjbojc essoxew kg Dofck Ckqve , nfsf'q Ffsjejbk Tkssfq vk qnkr vnf ohifvukuq zkujc dkz nkr ov'q bkjf Iv'q vnf qehf fxfsz quhhfs . Nk-kjf neq fxfs coxfj hf ejzvnojc kj e iwevf . Tnfz hebf hf akhifvf gks hz iweaf vnf xfsz hkhfjv I ckv ojvk vnf gosqv vfeh; vnev'q rnev vnfz veucnv hf ejb ov'ww df vnev rez ujvow I wfexf . Tnf nocnfs puewovz iwezfsq vnev akhf - ejb Dofck Ckqve oq puewovz - vnf csfevfs vnf akhifvovokj roww df ejb vnf dfvvfs ov'ww df gks vnf vfeh .Ajb gfes jkv ( ks , ewvfsjevoxfwz , bkj'v cfv vkk ftaovfb) , Tkssfq neq jk iwejq vk vuam veow ejb suj ejb wfexf noq iezanfamq dfnojb . I bkj'v nexf ejz iwejq vk hkxf erez socnv jkr . Ig rf woqvfjfb vk eww vnf suhkusq rf'b nexf 50 iwezfsq . Nkr'q jkv vnf socnv vohf vk df vnojmojc edkuv Cnfwqfe . I'h qusf vnf awud oq rksmojc vk ohiskxf vnf vfeh , duv eww vnev hevvfsq socnv jkr oq vnf Wkswb Cui .Om , vnev dov edkuv vnf 50 iwezfsq hebf hf anuamwf . Noaf kjf , Ffsjejbk .Nkr , oj ej obfew rkswb , rf rkuwb ifsneiq cfv vnfqf rksbq gskh Lumemu , rnkh rf'b womf vk dfakhf wfcfjbesz ev Cnfwqfe . Buv rf bkj'v woxf oj ej obfew rkswb , ejb ojqvfeb rf cfv vnfqf rksbq gskh Tkssfq , rnkh rf'b womf vk dfakhf e wkjc-gksckvvfj hfhksz ev Cnfwqfe . Aweq .Tnev dfojc qeob , qojaf ov'q deqoaewwz ej ohikqqodwf vk veqm vk sob kusqfwxfq kg vnf £100h gwki , ev wfeqv nf'q ckv vnf socnv evvovubf . Hussez? 200 | ``` 201 | 202 | Once more, your task is not to make a program that *deciphers every possible text on the planet*, you just have to decipher *this text*. And by decipher, I mean extract the meaning of it - let's not care about missed dots, commas, word casing and such stuff. 203 | 204 | ####Instructions and hints#### 205 | 206 | A usually good counter-attacking technique is to simply make a histogram of the usage of letters in the *given* text and comapre it to the histogram of letters *in the language*. 207 | For example, in the english language, the letter 'e' is the most frequently used, in a total of 13% of all letters. So there is a good chance the most commonly used letter in the given text is 'e'. 208 | 209 | You can see some frequencies and letter distribution facts here: 210 | http://en.wikipedia.org/wiki/Letter_frequency 211 | http://www.cryptograms.org/letter-frequencies.php 212 | 213 | 214 | Some hints: 215 | - Ignore one-letter words. They are likely dots or hyphens or commas, you will add them later. 216 | - Trim spaces on words after you parse them. Make sure you are not analysing empty spaces. 217 | - Watch out for letter casing! Make sure you analyze uppercase 'T' the same as downcase 't'. 218 | - Make a method `String applyCipher(Map cipher)`. You will likely find a good use for it. Of course, it is not mandatory. 219 | - As this problem requires some visual examination, do *not try* to solve in TDD at first. In fact, in general, apply *TDD* only when you have something to test for. 220 | - If frequency attack turns out to be not good enough, check [the list of 5000 most used words in English](https://docs.google.com/spreadsheets/d/1LuHWIlshSqwfr3AKwvqIoXAGZrNmsPUopwfhc3DhtS4/edit#gid=0). There is a good chance some of those will be from the first words you unveil! 221 | 222 | 223 | -------------------------------------------------------------------------------- /12-SmallProject/ref/2048/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------