├── .gitignore ├── .idea ├── .gitignore ├── vcs.xml ├── compiler.xml ├── misc.xml ├── modules.xml ├── $PRODUCT_WORKSPACE_FILE$ └── uiDesigner.xml ├── src ├── sell_statistics │ ├── StatisticEnum.java │ ├── SellStatisticInput.java │ └── SellStatistics.java ├── Codility │ ├── Distinct.java │ ├── PermCheck.java │ ├── PassingCars.java │ ├── TieRope.java │ ├── CountWordsInParagraph.java │ ├── OddOccurrencesInArray.java │ ├── PalidromeString.java │ ├── events.sql │ ├── UnsortedArrayCleanUp.java │ ├── ShuffleInt.java │ ├── PermMissingElements.java │ ├── ArrayOrderByRemovingElements.java │ ├── SumOfOdds.java │ ├── MissingInteger.java │ ├── LightBulbs.java │ ├── StringReversing.java │ ├── MaxProductOfThree.java │ ├── FrogJump.java │ ├── TapeEquilibrium.java │ ├── AbsDistinct.java │ ├── READMEUpdate.java │ ├── PairsEqualToProduct.java │ ├── PairsEqualToSum.java │ ├── CountNonDivisible.java │ ├── FrogRiverOne.java │ ├── CountSemiprimes.java │ └── PhoneBill.java ├── amazon │ └── rss │ │ └── parser │ │ ├── RssMain.java │ │ ├── FeedMessage.java │ │ ├── Feed.java │ │ └── RSSFeedParser.java └── PhoneNumberConversion.java ├── data2.txt ├── data.txt ├── .classpath ├── .project ├── Java-Snippets.iml ├── Codility Problems.iml ├── .settings └── org.eclipse.jdt.core.prefs ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | out/ 3 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /src/sell_statistics/StatisticEnum.java: -------------------------------------------------------------------------------- 1 | package sell_statistics; 2 | 3 | public enum StatisticEnum { 4 | S, Q 5 | } 6 | -------------------------------------------------------------------------------- /data2.txt: -------------------------------------------------------------------------------- 1 | 11 2 | S 1 1 2 3 | S 2 1.1 2 4 | S 2 2.3 1 5 | S 1 2.2 1 6 | Q 1 1 2 7 | Q 1 2 1 8 | Q 2 1 2 9 | Q 2 2 1 10 | Q 1.2 1 -1 11 | Q 1.2 -1 2 12 | Q 1.2 -1 -1 -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /data.txt: -------------------------------------------------------------------------------- 1 | 15 2 | Q 1 1.2 2.5 3 | S 1 1.3 2.5 4 | S 1 1.2 2.6 5 | Q 1 1.2 2.6 6 | Q 1 1.2 2 7 | S 2 2 3.5 8 | Q 2 2.3 3.5 9 | S 1 1.2 3.4 10 | Q 1 1 -1 11 | S 3 2.3 6.7 12 | S 3 2.4 6.8 13 | S 2 2 7.8 14 | Q 3 2 6.7 15 | Q 3 2 6 16 | Q 1.3 2 -1 -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/Codility/Distinct.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Distinct { 6 | public static void main(String[] args) { 7 | int[] A = new int[] { 2, 1, 1, 2, 3, 1 ,4,4,7}; 8 | System.out.println(solution(A)); 9 | } 10 | 11 | public static int solution(int[] A) { 12 | return (int) Arrays.stream(A).distinct().count(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Java-Snippets 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 | -------------------------------------------------------------------------------- /Java-Snippets.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/Codility/PermCheck.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.Arrays; 4 | 5 | public class PermCheck { 6 | public static void main(String[] args) { 7 | int[] A = new int[] { 4, 1, 3 }; 8 | System.out.println(solution(A)); 9 | } 10 | 11 | public static int solution(int[] A) { 12 | Arrays.sort(A); 13 | 14 | for (int i = 0; i < A.length; i++) { 15 | if (i > 0 && !(A[i] == A[i - 1] + 1)) { 16 | return 0; 17 | } 18 | } 19 | 20 | return 1; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Codility Problems.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/amazon/rss/parser/RssMain.java: -------------------------------------------------------------------------------- 1 | package amazon.rss.parser; 2 | 3 | public class RssMain { 4 | 5 | public static void main(String[] args) throws Exception { 6 | // Ex:https://www.amazon.in/gp/rss/bestsellers/grocery/4860245031/ref=zg_bs_4860245031_rsslink 7 | RSSFeedParser parser = new RSSFeedParser("Enter amazon URL here"); 8 | Feed feed = parser.readFeed(); 9 | for (FeedMessage message : feed.getMessages()) { 10 | 11 | System.out.println(message); 12 | } 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/Codility/PassingCars.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | public class PassingCars { 4 | public static void main(String[] args) { 5 | int[] A = new int[] { 0, 1, 0, 1, 1 }; 6 | System.out.println(solution(A)); 7 | } 8 | 9 | public static int solution(int[] A) { 10 | int res = 0; 11 | int ones = 0; 12 | 13 | for (int i = A.length - 1; i >= 0; i--) { 14 | 15 | if (A[i] == 1) 16 | ones++; 17 | else { 18 | res += ones; 19 | } 20 | 21 | if (res > 1000000000) 22 | return -1; 23 | } 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.idea/$PRODUCT_WORKSPACE_FILE$: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 8 | 9 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/Codility/TieRope.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | public class TieRope { 4 | public static void main(String[] args) { 5 | int[] A = new int[] { 1, 2, 3, 4, 1, 1, 3 }; 6 | int K = 4; 7 | 8 | System.out.println(solution(A, K)); 9 | } 10 | 11 | public static int solution(int[] A, int K) { 12 | int numOfRopes = 0; 13 | int ropeLengthCounter = 0; 14 | for (Integer a : A) { 15 | ropeLengthCounter += a; 16 | if (ropeLengthCounter >= K) { 17 | numOfRopes++; 18 | ropeLengthCounter = 0; 19 | } 20 | } 21 | System.out.println(); 22 | return numOfRopes; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Codility/CountWordsInParagraph.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class CountWordsInParagraph { 6 | 7 | public static void main(String[] args) { 8 | String s = "Hello People," + 9 | " i'm just counting." + 10 | " Do you want to \" join"; 11 | System.out.println(countWords(s)); 12 | } 13 | 14 | private static long countWords(String paragraph) { 15 | paragraph = paragraph.replaceAll("[^0-9a-zA-Z' ]+", ""); 16 | return Stream.of(paragraph.split(" ")).filter( world -> world.length()>0).count(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.8 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.8 12 | -------------------------------------------------------------------------------- /src/Codility/OddOccurrencesInArray.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.HashSet; 4 | 5 | public class OddOccurrencesInArray { 6 | public static void main(String[] args) { 7 | System.out.println(solution(new int[] { 9, 3, 9, 3, 9, 7, 9, 7, 7, 1, 1, 4 })); 8 | 9 | } 10 | 11 | public static int solution(int[] A) { 12 | 13 | HashSet set = new HashSet(A.length / 2); 14 | 15 | for (int i = 0; i < A.length; i++) { 16 | if (set.contains(A[i])) { 17 | set.remove(A[i]); 18 | } else { 19 | set.add(A[i]); 20 | } 21 | } 22 | 23 | return (int) set.toArray()[0]; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/Codility/PalidromeString.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.stream.Collectors; 4 | import java.util.stream.IntStream; 5 | 6 | public class PalidromeString { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(isPalidrome("abccba")); 10 | System.out.println(isPalidrome("ME")); 11 | } 12 | 13 | private static boolean isPalidrome(String word) { 14 | 15 | var wordChar = word.toCharArray(); 16 | var result = IntStream.range(0, wordChar.length) 17 | .mapToObj(i -> wordChar[wordChar.length - i - 1]) 18 | .map(Object::toString) 19 | .collect(Collectors.joining("")); 20 | return result.equals(word); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Codility/events.sql: -------------------------------------------------------------------------------- 1 | /** 2 | * Let's say we have a table Events with 3 | * (sensor_id:integer, event_type:integer, value:integer and time:timestamp). 4 | * I want an SQL for each sensor and event type return the most sum of events
5 | * . The table should be sorted by sensor_id (asc). 6 | * 7 | * result should be : 8 | * 9 | * sensor_id | event_type 10 | * -----------+------------ 11 | * 2 | 3 12 | * 3 | 1 13 | */ 14 | 15 | SELECT distinct sensor_id ,count( event_type) 16 | FROM ( 17 | select sensor_id, event_type, 18 | row_number() over (partition by sensor_id, event_type) as rn 19 | from events 20 | ) t 21 | where rn = 1 22 | GROUP BY sensor_id 23 | ORDER BY sensor_id ASC -------------------------------------------------------------------------------- /src/PhoneNumberConversion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * for Arabic coders, this code snippet convert Arabic written digits to English 3 | * written it will convert digits only , characters and symbols will be ignored 4 | * 5 | * @author Maha M. Hamza 6 | * 7 | */ 8 | public class PhoneNumberConversion { 9 | 10 | public String convert(String num) { 11 | StringBuilder number = new StringBuilder(); 12 | 13 | num.chars().mapToObj(x -> (char) x).forEach(e -> { 14 | char c = comparingCharacter(e); 15 | number.append(c); 16 | }); 17 | 18 | return number.toString(); 19 | } 20 | 21 | private char comparingCharacter(Character e) { 22 | char c = e.charValue(); 23 | if (c >= 0x0660 && c <= 0x0669) 24 | c -= 0x0660 - '0'; 25 | else if (c >= 0x06f0 && c <= 0x06F9) 26 | c -= 0x06f0 - '0'; 27 | return c; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/Codility/UnsortedArrayCleanUp.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.IntStream; 8 | 9 | /** 10 | * Remove duplicates from unsorted array 11 | */ 12 | public class UnsortedArrayCleanUp { 13 | 14 | private static void cleanArray(List listOfSum) { 15 | 16 | listOfSum.stream().distinct().forEach(e-> System.out.format("%d ",e)); 17 | } 18 | 19 | private static void cleanArray2(List listOfSum) { 20 | new HashSet<>(listOfSum) 21 | .forEach(e-> System.out.format("%d ",e)); 22 | } 23 | 24 | public static void main(String[] args) { 25 | cleanArray(List.of(1, 2, 5, 1, 7, 2, 4, 2)); 26 | System.out.println(); 27 | cleanArray2(List.of(1, 2, 5, 1, 7, 2, 4, 2)); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/Codility/ShuffleInt.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.Random; 4 | 5 | public class ShuffleInt { 6 | 7 | public static void main(String[] args) { 8 | System.out.println(shuffleInt(8745)); 9 | } 10 | 11 | private static int shuffleInt(int number) { 12 | char[] stringVersion = String.valueOf(number).toCharArray(); 13 | int length = stringVersion.length; 14 | String result = ""; 15 | do { 16 | int randomNumberWithinRange = (int) (Math.random() * (length)); 17 | if (!result.contains("" + stringVersion[randomNumberWithinRange])) { 18 | result = result.concat("" + stringVersion[randomNumberWithinRange]); 19 | if (result.length() == length) 20 | length = -1; 21 | } 22 | } while (length != -1); 23 | 24 | 25 | return Integer.parseInt(result); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Codility/PermMissingElements.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.IntStream; 5 | 6 | public class PermMissingElements { 7 | public static void main(String[] args) { 8 | int[] A = new int[] { 1, 2, 0, 4, 5 }; 9 | System.out.println(solution(A)); 10 | System.out.println(solution2(A)); 11 | } 12 | 13 | public static int solution(int[] A) { 14 | int res = 0; 15 | for (int i = 0; i < A.length; i++) { 16 | if (i > 0 && !(A[i] == A[i - 1] + 1)) { 17 | res = A[i - 1] + 1; 18 | break; 19 | } 20 | } 21 | return res; 22 | } 23 | 24 | public static int solution2(int[] A) { 25 | 26 | int min = Arrays.stream(A).min().getAsInt(); 27 | int max = Arrays.stream(A).max().getAsInt(); 28 | 29 | int expectedSum = IntStream.range(min, max).sum() + min + max; 30 | int currentSum = Arrays.stream(A).sum(); 31 | 32 | return Math.abs(expectedSum - currentSum); 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/Codility/ArrayOrderByRemovingElements.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | public class ArrayOrderByRemovingElements { 9 | 10 | public static void main(String[] args) { 11 | int[] array = {1, 2, 5, 4, 6, 7, 9, 8}; // 1 2 5 6 7 8 remove 4 9 12 | System.out.println(returnValidSortedArray(array)); 13 | int[] array2 = {1, 2, 4, 3, 5, 7, 8, 6, 9, 10}; 14 | System.out.println(returnValidSortedArray(array2)); 15 | 16 | } 17 | 18 | private static List returnValidSortedArray(int[] array) { 19 | List result = new ArrayList<>(); 20 | result.add(array[0]); 21 | 22 | Arrays.stream(array).forEach(number -> { 23 | if (!result.contains(number) && result.get(result.size() - 1) < number) { 24 | result.add(number); 25 | } 26 | }); 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Codility/SumOfOdds.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.stream.Collector; 8 | import java.util.stream.Collectors; 9 | import java.util.stream.IntStream; 10 | 11 | /** 12 | * Find all pairs in an array of integers that sum up to a given number 13 | */ 14 | public class SumOfOdds { 15 | 16 | private static void sumOfOdd(List listOfSum) { 17 | 18 | var sum = listOfSum.stream() 19 | .filter(i -> Collections.frequency(listOfSum, i) % 2 != 0) 20 | .reduce(0, (a, b) -> a + b); 21 | 22 | System.out.println(sum); 23 | 24 | 25 | } 26 | 27 | public static void main(String[] args) { 28 | sumOfOdd(List.of(1, 1, 2, 2, 3, 3, 3)); 29 | System.out.println("------------------"); 30 | sumOfOdd(List.of(10, 20, 30, 40, 40)); 31 | System.out.println("------------------"); 32 | 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/Codility/MissingInteger.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MissingInteger { 6 | 7 | public static void main(String[] args) { 8 | int[] A = new int[] { 1,1,4,2,3,5,9 }; 9 | int[] B = new int[] { 1,2,3 }; 10 | int[] C = new int[] { -1,-3 }; 11 | int[] D = new int[] { 10021,58541,99999 }; 12 | System.out.println(solution(A)); // expected 6 13 | System.out.println(solution(B)); // expected 4 14 | System.out.println(solution(C)); // expected 1 15 | System.out.println(solution(D)); // expected 1 16 | } 17 | 18 | public static int solution(int[] A) { 19 | // sort and remove duplication 20 | int[] AN = Arrays.stream(A).filter(n -> n > 0).distinct().sorted().toArray(); 21 | int N = AN.length; 22 | int MIN = 1; 23 | 24 | for (int i = 0; i < N; i++) { 25 | MIN = i+1; 26 | if (AN[i] != MIN) { 27 | return MIN; 28 | } 29 | else if (MIN == N) { 30 | return ++MIN; 31 | } 32 | } 33 | return MIN; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Codility/LightBulbs.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | /** 3 | N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of current bulb. Given an initial state of all bulbs, find the minimum number of switches you have to press to turn on all the bulbs. You can press the same switch multiple times. 4 | 5 | Note : 0 represents the bulb is off and 1 represents the bulb is on. 6 | 7 | Example: 8 | 9 | Input : [0 1 0 1] 10 | Return : 4 11 | 12 | Explanation : 13 | 14 | press switch 0 : [1 0 1 0] 15 | press switch 1 : [1 1 0 1] 16 | press switch 2 : [1 1 1 0] 17 | press switch 3 : [1 1 1 1] 18 | */ 19 | //light bulb 20 | public class LightBulbs { 21 | public static void main(String[] args) { 22 | int[] A = {2, 1, 3, 5, 4}; 23 | int count = 0; 24 | int numComparison = 0; 25 | for (int i = 0; i < A.length; i++) { 26 | numComparison = Math.max(numComparison, A[i]); 27 | if (numComparison == i + 1) { 28 | count++; 29 | } 30 | } 31 | System.out.println(count); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Find below solution for the following : 3 |
    4 |
  • SumOfOdds.java
  • 5 |
  • UnsortedArrayCleanUp.java
  • 6 |
  • ArrayOrderByRemovingElements.java
  • 7 |
  • PermCheck.java
  • 8 |
  • CountSemiprimes.java
  • 9 |
  • MaxProductOfThree.java
  • 10 |
  • TieRope.java
  • 11 |
  • MissingInteger.java
  • 12 |
  • AbsDistinct.java
  • 13 |
  • CountNonDivisible.java
  • 14 |
  • FrogJump.java
  • 15 |
  • PhoneBill.java
  • 16 |
  • LightBulbs.java
  • 17 |
  • ShuffleInt.java
  • 18 |
  • CountWordsInParagraph.java
  • 19 |
  • StringReversing.java
  • 20 |
  • FrogRiverOne.java
  • 21 |
  • TapeEquilibrium.java
  • 22 |
  • READMEUpdate.java
  • 23 |
  • PassingCars.java
  • 24 |
  • PalidromeString.java
  • 25 |
  • OddOccurrencesInArray.java
  • 26 |
  • PairsEqualToSum.java
  • 27 |
  • events.sql
  • 28 |
  • Distinct.java
  • 29 |
  • PermMissingElements.java
  • 30 |
  • PairsEqualToProduct.java
  • 31 |
  • SellSttistics.java
  • 32 |
33 | Please Feel Free To Contact me in case of Edits and suggestions. 34 | Thanks To Blogs' owners Who Gave me the initial Steps to break the ice with codility. 35 | please feel free to contact me via mail : sci.maha@gmail.com or skype : maha.hamza.profit 36 | -------------------------------------------------------------------------------- /src/Codility/StringReversing.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | public class StringReversing { 4 | 5 | public static void main(String[] args) { 6 | char[] stringToReverse = {' ',' ',' ','h','i',' ','y','o','u',' ',' ',' ','H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', ' ', 'I', 'T', 'S', ' ', 'M', 'A', 'H', 'A',' ',' ',' ',' '}; 7 | System.out.println(reverseStringPhrase(stringToReverse)); 8 | 9 | } 10 | 11 | private static char[] reverseStringPhrase(char[] stringToReverse){ 12 | String reversed=""; 13 | String s = ""; 14 | for (int i = stringToReverse.length-1; i >= 0; i--) { 15 | if (stringToReverse[i] != ' ' ) { 16 | s += stringToReverse[i]+""; 17 | } 18 | if(stringToReverse[i] == ' '|| i==0) { 19 | reversed += reverseString(s); 20 | } 21 | if(stringToReverse[i] == ' ') { 22 | reversed += " "; 23 | s=""; 24 | } 25 | 26 | } 27 | return reversed.toCharArray(); 28 | } 29 | 30 | private static String reverseString(String s) { 31 | String toRev = ""; 32 | for (int i = s.length() - 1; i >= 0; i--) 33 | toRev += s.charAt(i); 34 | return toRev; 35 | } 36 | 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/amazon/rss/parser/FeedMessage.java: -------------------------------------------------------------------------------- 1 | package amazon.rss.parser; 2 | 3 | public class FeedMessage { 4 | String title; 5 | String description; 6 | String link; 7 | String author; 8 | String guid; 9 | String imageURL; 10 | 11 | public String getTitle() { 12 | return title; 13 | } 14 | 15 | public void setTitle(String title) { 16 | this.title = title; 17 | } 18 | 19 | public String getDescription() { 20 | return description; 21 | } 22 | 23 | public void setDescription(String description) { 24 | this.description = description; 25 | } 26 | 27 | public String getLink() { 28 | return link; 29 | } 30 | 31 | public void setLink(String link) { 32 | this.link = link; 33 | } 34 | 35 | public String getAuthor() { 36 | return author; 37 | } 38 | 39 | public void setAuthor(String author) { 40 | this.author = author; 41 | } 42 | 43 | public String getGuid() { 44 | return guid; 45 | } 46 | 47 | public void setGuid(String guid) { 48 | this.guid = guid; 49 | } 50 | 51 | public void setImageURL(String imageURL) { 52 | this.imageURL = imageURL; 53 | } 54 | 55 | public String getImageURL() { 56 | return imageURL; 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return "FeedMessage [title=" + title + ", description=" + description + ", link=" + link + ", author=" + author 62 | + ", guid=" + guid + ", imageURL=" + imageURL + "]"; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/Codility/MaxProductOfThree.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | A non-empty zero-indexed array A consisting of N integers is given. 7 | 8 | The problem is to find the maximum product of 3 elements from given array. 9 | 10 | The length of the array is between 3 and 100,000 11 | 12 | each element of array A is an integer within the range [−1,000..1,000] 13 | 14 | expected worst-case time complexity is O(N*log(N)); 15 | 16 | expected worst-case space complexity is O(1), 17 | beyond input storage (not counting the storage required for input arguments). Example: 18 | 19 | a[0] = -3; 20 | a[1] = 7; 21 | a[2] = 2; 22 | a[3] = 1; 23 | a[4] = 5; 24 | a[5] = 7; 25 | the max product is a[1]*a[4]*a[5] = 245 26 | */ 27 | public class MaxProductOfThree { 28 | public static void main(String[] args) { 29 | int[] A = new int[] { -9, -6, 3, 2, 5, 7 }; 30 | System.out.println(solution(A)); 31 | } 32 | 33 | public static int solution(int[] A) { 34 | int[] array = Arrays.stream(A).distinct().sorted().toArray(); 35 | int sum1 = 1; 36 | int sum2 = 1; 37 | 38 | for (int i = array.length - 3; i < array.length; i++) { 39 | sum1 = Math.multiplyExact(sum1, array[i]); 40 | } 41 | 42 | for (int i = 0; i < 2; i++) { 43 | sum2 = Math.multiplyExact(sum2, array[i]); 44 | } 45 | sum2 = Math.multiplyExact(sum2, array[array.length - 1]); 46 | 47 | return Math.max(sum1, sum2); 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Codility/FrogJump.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | /** 3 | A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D. Count the minimal number of jumps that the small frog must perform to reach its target. 4 | 5 | Write a function: 6 | 7 | class Solution { public int solution(int X, int Y, int D); } 8 | that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y. 9 | 10 | For example, given: 11 | 12 | X = 10 Y = 85 D = 30 13 | 14 | the function should return 3, because the frog will be positioned as follows: after the first jump, at position 10 + 30 = 40 after the second jump, at position 10 + 30 + 30 = 70 after the third jump, at position 10 + 30 + 30 + 30 = 100 15 | 16 | Assume that: 17 | X, Y and D are integers within the range [1..1,000,000,000]; 18 | X ≤ Y. 19 | Complexity: 20 | expected worst-case time complexity is O(1); 21 | expected worst-case space complexity is O(1) 22 | */ 23 | public class FrogJump { 24 | 25 | public static void main(String[] args) throws Exception { 26 | int A = 10; 27 | int B = 85; 28 | int D = 30; 29 | System.out.println(solution(A, B, D)); 30 | } 31 | 32 | private static int solution(int a, int b, int d) throws Exception { 33 | if (b < a) { 34 | throw new Exception("b can't be less than a"); 35 | } 36 | 37 | return (int) Math.ceil(((double) b - a) / d); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Codility/TapeEquilibrium.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.List; 7 | import java.util.stream.Collectors; 8 | 9 | public class TapeEquilibrium { 10 | 11 | public static int solution(int[] array) { 12 | List list = Arrays.stream(array).boxed().collect(Collectors.toList()); 13 | int leftSum = 0; 14 | int rightSum = 0; 15 | List ints = new ArrayList<>(); 16 | 17 | for (int i = 0; i < list.size(); i++) { 18 | if (i == 0) { 19 | leftSum = list.get(0); 20 | rightSum = Arrays.stream(Arrays.copyOfRange(array, 1, list.size())).sum(); 21 | } else if (i != array.length - 1) { 22 | leftSum = Arrays.stream(Arrays.copyOfRange(array, 0, i + 1)).sum(); 23 | rightSum = Arrays.stream(Arrays.copyOfRange(array, i + 1, list.size())).sum(); 24 | } 25 | if (i != array.length - 1 || i == 0) 26 | ints.add(Math.abs(leftSum - rightSum)); 27 | 28 | } 29 | 30 | Collections.sort(ints); 31 | return ints.get(0); 32 | } 33 | 34 | public static int solution2(int[] A) { 35 | int expectedMinimum = Integer.MAX_VALUE; 36 | int tmp = 0; 37 | int sum = 0; 38 | 39 | sum = Arrays.stream(A, 0, A.length).sum(); 40 | 41 | for (int i = 0; i < A.length - 1; i++) { 42 | tmp += A[i]; 43 | expectedMinimum = Math.min(expectedMinimum, Math.abs(tmp - (sum - tmp))); 44 | } 45 | return expectedMinimum; 46 | } 47 | 48 | public static void main(String[] args) { 49 | int[] array = { 3, 1, 2, 4, 3 }; 50 | System.out.println(solution(array)); 51 | System.out.println(solution2(array)); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Codility/AbsDistinct.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | /** 6 | A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array. 7 | 8 | For example, consider array A such that: 9 | 10 | A[0] = -5 11 | A[1] = -3 12 | A[2] = -1 13 | A[3] = 0 14 | A[4] = 3 15 | A[5] = 6 16 | The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6. 17 | 18 | Write a function: 19 | 20 | class Solution { public int solution(int[] A); } 21 | 22 | that, given a non-empty array A consisting of N numbers, returns absolute distinct count of array A. 23 | 24 | For example, given array A such that: 25 | 26 | A[0] = -5 27 | A[1] = -3 28 | A[2] = -1 29 | A[3] = 0 30 | A[4] = 3 31 | A[5] = 6 32 | the function should return 5, as explained above. 33 | 34 | Write an efficient algorithm for the following assumptions: 35 | 36 | N is an integer within the range [1..100,000]; 37 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]; 38 | array A is sorted in non-decreasing order. 39 | */ 40 | public class AbsDistinct { 41 | 42 | public static void main(String[] args) { 43 | int[] A = { -5, -3, -1, 0, 3, 6 }; 44 | System.out.println(solution(A)); 45 | } 46 | 47 | public static int solution(int[] A) { 48 | 49 | return (int) IntStream.of(A).map(Math::abs).distinct().count(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/amazon/rss/parser/Feed.java: -------------------------------------------------------------------------------- 1 | package amazon.rss.parser; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Feed { 7 | 8 | final String title; 9 | final String link; 10 | final String description; 11 | final String language; 12 | final String copyright; 13 | final String pubDate; 14 | 15 | final List entries = new ArrayList(); 16 | 17 | public Feed(String title, String link, String description, String language, 18 | String copyright, String pubDate) { 19 | this.title = title; 20 | this.link = link; 21 | this.description = description; 22 | this.language = language; 23 | this.copyright = copyright; 24 | this.pubDate = pubDate; 25 | } 26 | 27 | public List getMessages() { 28 | return entries; 29 | } 30 | 31 | public String getTitle() { 32 | return title; 33 | } 34 | 35 | public String getLink() { 36 | return link; 37 | } 38 | 39 | public String getDescription() { 40 | return description; 41 | } 42 | 43 | public String getLanguage() { 44 | return language; 45 | } 46 | 47 | public String getCopyright() { 48 | return copyright; 49 | } 50 | 51 | public String getPubDate() { 52 | return pubDate; 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | return "Feed [copyright=" + copyright + ", description=" + description 58 | + ", language=" + language + ", link=" + link + ", pubDate=" 59 | + pubDate + ", title=" + title + "]"; 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /src/Codility/READMEUpdate.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | import java.util.stream.Collectors; 9 | 10 | public class READMEUpdate { 11 | public static void main(String[] args) throws IOException { 12 | 13 | var titles = parseFile("./src/Codility"); 14 | updateReadMe("./README.md", titles); 15 | 16 | } 17 | 18 | private static List parseFile(String path) throws IOException { 19 | return Files.list(Paths.get(path)) 20 | .map(Path::getFileName) 21 | .map(Path::toString) 22 | .collect(Collectors.toList()); 23 | } 24 | 25 | private static void updateReadMe(String path, List titles) throws IOException { 26 | 27 | var formattedTitles = titles.stream() 28 | .map(title -> String.format("
  • %s
  • ", title)) 29 | .collect(Collectors.joining("\n")); 30 | 31 | var lines = Files.readAllLines(Paths.get(path)); 32 | StringBuilder newContent = new StringBuilder(); 33 | lines.forEach(line -> { 34 | if (!line.trim().startsWith("
  • ")) { 35 | newContent.append(String.format("%s\n", line)); 36 | } else { 37 | newContent.append("_"); 38 | } 39 | }); 40 | newContent.replace( 41 | newContent.indexOf("_"), 42 | newContent.lastIndexOf("_") + 1, 43 | String.format("%s\n", formattedTitles) 44 | ); 45 | 46 | Files.write(Paths.get(path), newContent.toString().getBytes()); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/sell_statistics/SellStatisticInput.java: -------------------------------------------------------------------------------- 1 | package sell_statistics; 2 | 3 | public class SellStatisticInput { 4 | private StatisticEnum type; 5 | private int startDay; 6 | private int endDay; 7 | private int productId; 8 | private int categoryId; 9 | private int stateId; 10 | private int regionId; 11 | 12 | public SellStatisticInput(StatisticEnum type, int startDay, int endDay, int productId, int categoryId, int stateId, int regionId) { 13 | this.type = type; 14 | this.startDay = startDay; 15 | this.endDay = endDay; 16 | this.productId = productId; 17 | this.categoryId = categoryId; 18 | this.stateId = stateId; 19 | this.regionId = regionId; 20 | } 21 | 22 | public StatisticEnum getType() { 23 | return type; 24 | } 25 | 26 | public int getStartDay() { 27 | return startDay; 28 | } 29 | 30 | public int getEndDay() { 31 | return endDay; 32 | } 33 | 34 | public int getProductId() { 35 | return productId; 36 | } 37 | 38 | public int getCategoryId() { 39 | return categoryId; 40 | } 41 | 42 | public int getStateId() { 43 | return stateId; 44 | } 45 | 46 | public int getRegionId() { 47 | return regionId; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return "SellStatisticInput{" + 53 | "type=" + type + 54 | ", startDay=" + startDay + 55 | ", endDay=" + endDay + 56 | ", productId=" + productId + 57 | ", categoryId=" + categoryId + 58 | ", stateId=" + stateId + 59 | ", regionId=" + regionId + 60 | '}'; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/Codility/PairsEqualToProduct.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.IntStream; 6 | 7 | /** 8 | * Find all pairs in an array of integers that product of a given number 9 | */ 10 | public class PairsEqualToProduct { 11 | 12 | static class Pairs { 13 | private int x; 14 | private int y; 15 | 16 | public Pairs(int x, int y) { 17 | this.x = x; 18 | this.y = y; 19 | } 20 | 21 | @Override 22 | public String toString() { 23 | return "{" + x + "," + y + "}"; 24 | } 25 | } 26 | 27 | private static List findPairs(int sum, List listOfSum) { 28 | List pairs = new ArrayList<>(); 29 | 30 | IntStream.range(0, listOfSum.size()) 31 | .forEach(i -> IntStream.range(i, listOfSum.size()) 32 | .filter(j -> i != j && listOfSum.get(i) * listOfSum.get(j) == sum) 33 | .forEach(j -> pairs.add(new Pairs(listOfSum.get(i), listOfSum.get(j)))) 34 | ); 35 | 36 | return pairs; 37 | } 38 | 39 | private static void print(List pairs) { 40 | pairs.forEach(System.out::println); 41 | System.out.println(" # of pairs: " + pairs.size()); 42 | } 43 | 44 | public static void main(String[] args) { 45 | print(findPairs(400, List.of(10, 20, 9, 40))); 46 | System.out.println("------------------"); 47 | 48 | print(findPairs(1906, List.of(10, 20, 9, 40))); 49 | System.out.println("------------------"); 50 | 51 | print(findPairs(400, List.of(-10, 20, 9, -40))); 52 | System.out.println("------------------"); 53 | 54 | print(findPairs(-400, List.of(-10, 20, 9, 40,-10))); 55 | System.out.println("------------------"); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/Codility/PairsEqualToSum.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.IntStream; 6 | 7 | /** 8 | * Find all pairs in an array of integers that sum up to a given number 9 | */ 10 | public class PairsEqualToSum { 11 | 12 | static class Pairs { 13 | private int x; 14 | private int y; 15 | 16 | public Pairs(int x, int y) { 17 | this.x = x; 18 | this.y = y; 19 | } 20 | 21 | @Override 22 | public String toString() { 23 | return "{" + x + "," + y + "}"; 24 | } 25 | } 26 | 27 | private static List findPairs(int sum, List listOfSum) { 28 | List pairs = new ArrayList<>(); 29 | 30 | IntStream.range(0, listOfSum.size()) 31 | .forEach(i -> IntStream.range(i, listOfSum.size()) 32 | .filter(j -> i != j && listOfSum.get(i) + listOfSum.get(j) == sum) 33 | .forEach(j -> pairs.add(new Pairs(listOfSum.get(i), listOfSum.get(j)))) 34 | ); 35 | 36 | return pairs; 37 | } 38 | 39 | private static void print(List pairs) { 40 | pairs.forEach(System.out::println); 41 | System.out.println(" # of pairs: " + pairs.size()); 42 | } 43 | 44 | public static void main(String[] args) { 45 | print(findPairs(6, List.of(1, 5, 7, -1))); 46 | System.out.println("------------------"); 47 | 48 | print(findPairs(6, List.of(1, 5, 7, -1, 5))); 49 | System.out.println("------------------"); 50 | 51 | print(findPairs(2, List.of(1, 1, 1, 1))); 52 | System.out.println("------------------"); 53 | 54 | print(findPairs(11, List.of(10, 12, 10, 15, -1, 7, 6, 55 | 5, 4, 2, 1, 1, 1))); 56 | System.out.println("------------------"); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/Codility/CountNonDivisible.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | You are given a non-empty zero-indexed array A consisting of N integers. For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors. For example, consider integer N = 5 and array A such that: 7 | 8 | A[0] = 3 9 | A[1] = 1 10 | A[2] = 2 11 | A[3] = 3 12 | A[4] = 6 13 | For the following elements: 14 | 15 | A[0] = 3, the non-divisors are: 2, 6, 16 | A[1] = 1, the non-divisors are: 3, 2, 3, 6, 17 | A[2] = 2, the non-divisors are: 3, 3, 6, 18 | A[3] = 3, the non-divisors are: 2, 6, 19 | A[6] = 6, there aren't any non-divisors. 20 | Write a function: 21 | 22 | class Solution { public int[] solution(int[] A); } 23 | that, given a non-empty zero-indexed array A consisting of N integers, returns a sequence of integers representing the numbers of non-divisors. The sequence should be returned as: 24 | 25 | a structure Results (in C), 26 | or a vector of integers (in C++), 27 | or a record Results (in Pascal), 28 | or an array of integers (in any other programming language). 29 | For example, given: 30 | 31 | A[0] = 3 32 | A[1] = 1 33 | A[2] = 2 34 | A[3] = 3 35 | A[4] = 6 36 | the function should return [2, 4, 3, 2, 0], as explained above. Assume that: 37 | 38 | N is an integer within the range [1..50,000]; 39 | each element of array A is an integer within the range [1..2 * N]. 40 | Complexity: 41 | 42 | expected worst-case time complexity is O(N*log(N)); 43 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 44 | */ 45 | public class CountNonDivisible { 46 | 47 | public static void main(String[] args) { 48 | int[] A = { 3, 1, 2, 3, 6 }; 49 | System.out.println(Arrays.toString(solution(A))); 50 | } 51 | 52 | public static int[] solution(int[] A) { 53 | int[] nonDiv = new int[A.length]; 54 | int count = 0; 55 | for (int i = 0; i < A.length; i++) { 56 | count = 0; 57 | for (int j = 0; j < A.length; j++) { 58 | if (A[i] % A[j] != 0) { 59 | count++; 60 | } 61 | } 62 | nonDiv[i] = count; 63 | } 64 | 65 | return nonDiv; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Codility/FrogRiverOne.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | /** 3 | A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river. 4 | 5 | You are given an array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds. 6 | 7 | The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river. 8 | 9 | For example, you are given integer X = 5 and array A such that: 10 | 11 | A[0] = 1 12 | A[1] = 3 13 | A[2] = 1 14 | A[3] = 4 15 | A[4] = 2 16 | A[5] = 3 17 | A[6] = 5 18 | A[7] = 4 19 | In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river. 20 | 21 | Write a function: 22 | 23 | class Solution { public int solution(int X, int[] A); } 24 | 25 | that, given a non-empty array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river. 26 | 27 | If the frog is never able to jump to the other side of the river, the function should return −1. 28 | 29 | For example, given X = 5 and array A such that: 30 | 31 | A[0] = 1 32 | A[1] = 3 33 | A[2] = 1 34 | A[3] = 4 35 | A[4] = 2 36 | A[5] = 3 37 | A[6] = 5 38 | A[7] = 4 39 | the function should return 6, as explained above. 40 | 41 | Write an efficient algorithm for the following assumptions: 42 | 43 | N and X are integers within the range [1..100,000]; 44 | each element of array A is an integer within the range [1..X]. 45 | */ 46 | public class FrogRiverOne { 47 | public static void main(String[] args) { 48 | int[] A = { 1, 3, 1, 4, 2, 3, 5, 4 }; 49 | int X = 5; 50 | System.out.println(solution(A, X)); 51 | } 52 | 53 | public static int solution(int[] A, int X) { 54 | 55 | if (X > A.length) { 56 | return -1; 57 | } 58 | 59 | int[] isFilled = new int[X]; 60 | int position = 0; 61 | for (int i = 0; i < A.length; i++) { 62 | int x = A[i]; 63 | if (x <= X) { 64 | if (isFilled[x - 1] == 0) { 65 | isFilled[x - 1] = 1; 66 | position += 1; 67 | if (position == X) { 68 | return i; 69 | } 70 | } 71 | } 72 | } 73 | 74 | return -1; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/Codility/CountSemiprimes.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.IntStream; 8 | /** 9 | /** 10 | * A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13. 11 | * A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26. 12 | * You are given two non-empty zero-indexed arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges. 13 | * Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N. 14 | * For example, consider an integer N = 26 and arrays P, Q such that: 15 | * P[0] = 1 Q[0] = 26 16 | * P[1] = 4 Q[1] = 10 17 | * P[2] = 16 Q[2] = 20 18 | * The number of semiprimes within each of these ranges is as follows: 19 | * (1, 26) is 10, 20 | * (4, 10) is 4, 21 | * (16, 20) is 0. 22 | * Write a function: 23 | * class Solution { public int[] solution(int N, int[] P, int[] Q); } 24 | * that, given an integer N and two non-empty zero-indexed arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries. 25 | * For example, given an integer N = 26 and arrays P, Q such that: 26 | * P[0] = 1 Q[0] = 26 27 | * P[1] = 4 Q[1] = 10 28 | * P[2] = 16 Q[2] = 20 29 | * the function should return the values [10, 4, 0], as explained above. 30 | * Assume that: 31 | * N is an integer within the range [1..50,000]; 32 | * M is an integer within the range [1..30,000]; 33 | * each element of arrays P, Q is an integer within the range [1..N]; 34 | * P[i] ≤ Q[i]. 35 | * Complexity: 36 | * expected worst-case time complexity is O(N*log(log(N))+M); 37 | * expected worst-case space complexity is O(N+M), beyond input storage (not counting the storage required for input arguments). 38 | * Elements of input arrays can be modified. 39 | */ 40 | */ 41 | public class CountSemiprimes { 42 | public static void main(String[] args) { 43 | int[] A = new int[] { 1, 4, 16 }; 44 | int[] B = new int[] { 26, 10, 20 }; 45 | int N = 26; 46 | System.out.println(Arrays.toString(solution(A, B, N))); 47 | 48 | } 49 | 50 | public static int[] solution(int[] A, int[] B, int N) { 51 | int[] semiPrimesCount = new int[A.length]; 52 | 53 | for (int i = 0; i < A.length; i++) { 54 | int el1 = A[i]; 55 | int el2 = B[i]; 56 | semiPrimesCount[i] = findSemiPrimInRange(el1, el2, N); 57 | } 58 | 59 | return semiPrimesCount; 60 | } 61 | 62 | public static int findSemiPrimInRange(int A, int B, int N) { 63 | 64 | int semi = 0; 65 | 66 | for (int i = A; i <= B; i++) { 67 | if (isSemiPrime(i, N)) 68 | semi++; 69 | } 70 | 71 | return semi; 72 | } 73 | 74 | public static boolean isSemiPrime(int num, int N) { 75 | 76 | List semi = getSemiPrimes(N); 77 | 78 | return semi.contains(num); 79 | } 80 | 81 | public static List getSemiPrimes(int N) { 82 | List semiPrimes = new ArrayList<>(); 83 | 84 | List primes = getPrimes(N); 85 | 86 | for (Integer integer : primes) { 87 | for (Integer integer2 : primes) { 88 | semiPrimes.add(integer2 * integer); 89 | } 90 | } 91 | 92 | return semiPrimes; 93 | } 94 | 95 | public static List getPrimes(int N) { 96 | return IntStream.rangeClosed(2, N).parallel() 97 | .map(i -> IntStream.rangeClosed(2, (int) (Math.sqrt(i))).filter(j -> i / j * j == i).map(j -> 0) 98 | .findAny().orElse(i)) 99 | .filter(i -> i != 0).mapToObj(i -> Integer.valueOf(i)).collect(Collectors.toList()); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/sell_statistics/SellStatistics.java: -------------------------------------------------------------------------------- 1 | package sell_statistics; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Paths; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.List; 9 | import java.util.concurrent.atomic.AtomicInteger; 10 | import java.util.stream.Collectors; 11 | import java.util.stream.IntStream; 12 | 13 | public class SellStatistics { 14 | 15 | public static void main(String[] args) throws IOException { 16 | var data = parseFile("./data.txt"); 17 | calculateTotalNumberOfProductSold(data).forEach(System.out::println); 18 | } 19 | 20 | private static List parseFile(String path) throws IOException { 21 | var entries = Files.readAllLines(Paths.get(path)); 22 | 23 | List input = new ArrayList<>(); 24 | entries.stream() 25 | .skip(1) 26 | .forEach(line -> { 27 | var elements = line.split(" "); 28 | var s_e_day = checkAndSplit(elements[1]); 29 | var p_c = checkAndSplit(elements[2]); 30 | var s_r = checkAndSplit(elements[3]); 31 | 32 | input.add(new SellStatisticInput( 33 | StatisticEnum.valueOf(elements[0]), 34 | s_e_day.get(0), 35 | s_e_day.get(1), 36 | p_c.get(0), 37 | p_c.get(1), 38 | s_r.get(0), 39 | s_r.get(1) 40 | )); 41 | } 42 | ); 43 | return input; 44 | } 45 | 46 | private static List checkAndSplit(String element) { 47 | var array = element.contains(".") ? element.split("\\.") : new String[]{element}; 48 | var split = Arrays 49 | .stream(array) 50 | .map(Integer::valueOf) 51 | .collect(Collectors.toList()); 52 | 53 | if (split.size() == 1) 54 | split.add(0); 55 | 56 | return split; 57 | 58 | } 59 | 60 | private static List calculateTotalNumberOfProductSold(List input) { 61 | List result = new ArrayList<>(); 62 | 63 | AtomicInteger count = new AtomicInteger(0); 64 | 65 | IntStream.range(0, input.size()).forEach(index -> { 66 | var currentItem = input.get(index); 67 | if (currentItem.getType().equals(StatisticEnum.Q)) { 68 | input.subList(0, index) 69 | .stream() 70 | .filter(before -> before.getType().equals(StatisticEnum.S)) 71 | .forEach(sell -> { 72 | if (checkSellsFactors(sell, currentItem)) { 73 | count.incrementAndGet(); 74 | } 75 | }); 76 | result.add(count.intValue()); 77 | count.set(0); 78 | } 79 | }); 80 | 81 | return result; 82 | } 83 | 84 | private static Boolean checkSellsFactors(SellStatisticInput sell, SellStatisticInput query) { 85 | 86 | return ((sell.getProductId() == query.getProductId()) || (query.getProductId() == -1)) 87 | && ((sell.getStateId() == query.getStateId()) || (query.getStateId() == -1)) 88 | && (query.getCategoryId() != 0 ? sell.getCategoryId() == query.getCategoryId() : sell.getCategoryId() >= query.getCategoryId()) 89 | && (query.getRegionId() != 0 ? sell.getRegionId() == query.getRegionId() : sell.getRegionId() >= query.getRegionId()) 90 | && (query.getEndDay() != 0 ? IntStream.rangeClosed(query.getStartDay(), query.getEndDay()).anyMatch(x -> x == sell.getStartDay()) : (sell.getStartDay() == query.getStartDay())); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/amazon/rss/parser/RSSFeedParser.java: -------------------------------------------------------------------------------- 1 | package amazon.rss.parser; 2 | 3 | import javax.xml.stream.XMLEventReader; 4 | import javax.xml.stream.XMLInputFactory; 5 | import javax.xml.stream.XMLStreamException; 6 | import javax.xml.stream.events.Characters; 7 | import javax.xml.stream.events.XMLEvent; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.net.MalformedURLException; 11 | import java.net.URL; 12 | import java.util.regex.Matcher; 13 | import java.util.regex.Pattern; 14 | 15 | public class RSSFeedParser { 16 | static final String TITLE = "title"; 17 | static final String DESCRIPTION = "description"; 18 | static final String CHANNEL = "channel"; 19 | static final String LANGUAGE = "language"; 20 | static final String COPYRIGHT = "copyright"; 21 | static final String LINK = "link"; 22 | static final String AUTHOR = "author"; 23 | static final String ITEM = "item"; 24 | static final String PUB_DATE = "pubDate"; 25 | static final String GUID = "guid"; 26 | 27 | final URL url; 28 | 29 | public RSSFeedParser(String feedUrl) { 30 | try { 31 | this.url = new URL(feedUrl); 32 | } catch (MalformedURLException e) { 33 | throw new RuntimeException(e); 34 | } 35 | } 36 | 37 | public Feed readFeed() { 38 | Feed feed = null; 39 | try { 40 | boolean isFeedHeader = true; 41 | String description = ""; 42 | String title = ""; 43 | String link = ""; 44 | String language = ""; 45 | String copyright = ""; 46 | String author = ""; 47 | String pubdate = ""; 48 | String guid = ""; 49 | String imageURL = ""; 50 | 51 | XMLInputFactory inputFactory = XMLInputFactory.newInstance(); 52 | InputStream in = read(); 53 | XMLEventReader eventReader = inputFactory.createXMLEventReader(in); 54 | while (eventReader.hasNext()) { 55 | XMLEvent event = eventReader.nextEvent(); 56 | if (event.isStartElement()) { 57 | String localPart = event.asStartElement().getName().getLocalPart(); 58 | switch (localPart) { 59 | case ITEM: 60 | if (isFeedHeader) { 61 | isFeedHeader = false; 62 | feed = new Feed(title, link, description, language, copyright, pubdate); 63 | } 64 | event = eventReader.nextEvent(); 65 | break; 66 | case TITLE: 67 | title = getCharacterData(event, eventReader); 68 | break; 69 | case DESCRIPTION: 70 | description = getCharacterData(event, eventReader); 71 | imageURL = extractImageFromString(description); 72 | break; 73 | case LINK: 74 | link = getCharacterData(event, eventReader); 75 | break; 76 | case GUID: 77 | guid = getCharacterData(event, eventReader); 78 | break; 79 | case LANGUAGE: 80 | language = getCharacterData(event, eventReader); 81 | break; 82 | case AUTHOR: 83 | author = getCharacterData(event, eventReader); 84 | break; 85 | case PUB_DATE: 86 | pubdate = getCharacterData(event, eventReader); 87 | break; 88 | case COPYRIGHT: 89 | copyright = getCharacterData(event, eventReader); 90 | break; 91 | } 92 | } else if (event.isEndElement()) { 93 | if (event.asEndElement().getName().getLocalPart() == (ITEM)) { 94 | FeedMessage message = new FeedMessage(); 95 | message.setAuthor(author); 96 | message.setDescription(description); 97 | message.setGuid(guid); 98 | message.setLink(link); 99 | message.setTitle(title); 100 | message.setImageURL(imageURL); 101 | feed.getMessages().add(message); 102 | event = eventReader.nextEvent(); 103 | continue; 104 | } 105 | } 106 | } 107 | } catch (XMLStreamException e) { 108 | throw new RuntimeException(e); 109 | } 110 | return feed; 111 | } 112 | 113 | private String getCharacterData(XMLEvent event, XMLEventReader eventReader) throws XMLStreamException { 114 | String result = ""; 115 | event = eventReader.nextEvent(); 116 | if (event instanceof Characters) { 117 | result = event.asCharacters().getData(); 118 | } 119 | return result; 120 | } 121 | 122 | private String extractImageFromString(String desc) { 123 | Pattern pattern = Pattern.compile("()"); 124 | Matcher matcher = pattern.matcher(desc); 125 | if (matcher.find()) { 126 | String img = matcher.group(1); 127 | Pattern pattern2 = Pattern.compile("src=\"(.*?)\""); 128 | Matcher matcher2 = pattern2.matcher(img); 129 | if (matcher2.find()) { 130 | return matcher2.group(1); 131 | } 132 | } 133 | return ""; 134 | } 135 | 136 | private InputStream read() { 137 | try { 138 | return url.openStream(); 139 | } catch (IOException e) { 140 | throw new RuntimeException(e); 141 | } 142 | } 143 | } -------------------------------------------------------------------------------- /src/Codility/PhoneBill.java: -------------------------------------------------------------------------------- 1 | package Codility; 2 | 3 | import java.time.LocalTime; 4 | import java.util.ArrayList; 5 | import java.util.Collections; 6 | import java.util.Comparator; 7 | import java.util.List; 8 | import java.util.regex.Pattern; 9 | import java.util.stream.Collectors; 10 | 11 | public class PhoneBill { 12 | 13 | public static void main(String[] args) { 14 | String N = "00:01:07,100-234-090 00:05:00,100-234-090 00:01:07,400-234-090 00:05:01,701-080-080 00:05:00,400-234-090"; 15 | // String N = "00:01:07,400-234-090 00:05:01,701-080-080 16 | // 00:05:00,400-234-090"; 17 | System.out.println(solution(N)); 18 | } 19 | 20 | private static List parseLog(String N) { 21 | List logH = new ArrayList<>(); 22 | String[] tokens = N.split(" "); 23 | for (int i = 0; i < tokens.length; i++) { 24 | String[] inter = tokens[i].split(","); 25 | logH.add(new LogHolder(inter[1], inter[0])); 26 | } 27 | return logH; 28 | } 29 | 30 | public static List removeFreeCall(List logs) { 31 | List logH = new ArrayList<>(); 32 | for (LogHolder log : logs) { 33 | double callDu = (LocalTime.parse(log.getCallDuration()).getHour() * 60 34 | + LocalTime.parse(log.getCallDuration()).getMinute() 35 | + (LocalTime.parse(log.getCallDuration()).getSecond() > 0 ? 1 : 0)); 36 | 37 | int existed = Collections.binarySearch(logH, new LogHolder(log.getPhone(), callDu), 38 | new Comparator() { 39 | 40 | @Override 41 | public int compare(LogHolder o1, LogHolder o2) { 42 | return o1.getPhone().compareTo(o2.getPhone()); 43 | } 44 | }); 45 | if (existed < 0) { 46 | double sum = Pattern.compile("").splitAsStream(log.getPhone().replaceAll("-", "")) 47 | .mapToInt(Integer::parseInt).sum(); 48 | logH.add(new LogHolder(log.getPhone(), callDu, sum)); 49 | } else if (existed >= 0) { 50 | logH.get(existed).setTotalDuration(logH.get(existed).getTotalDuration() + callDu); 51 | } 52 | } 53 | 54 | final Comparator comp1 = (p1, p2) -> Double.compare(p1.getTotalDuration(), p2.getTotalDuration()); 55 | double maxDuration = logH.stream().max(comp1).get().getTotalDuration(); 56 | 57 | final Comparator comp2 = (p1, p2) -> Double.compare(p1.getNumericalSum(), p2.getNumericalSum()); 58 | double minNumSum = logH.stream().min(comp2).get().getNumericalSum(); 59 | 60 | List list = logH.stream().filter(call -> call.getTotalDuration() == maxDuration) 61 | .collect(Collectors.toList()); 62 | 63 | LogHolder freeLog = null; 64 | if (list.size() > 1) { 65 | freeLog = list.stream().filter(call -> call.getNumericalSum() == minNumSum).collect(Collectors.toList()) 66 | .get(0); 67 | } else { 68 | freeLog = list.get(0); 69 | } 70 | 71 | List hand = new ArrayList<>(); 72 | for (LogHolder l : logs) { 73 | if (!l.getPhone().equals(freeLog.getPhone())) 74 | hand.add(l); 75 | } 76 | 77 | return hand; 78 | } 79 | 80 | public static double solution(String N) { 81 | double totalCost = 0.0; 82 | List logs = parseLog(N); 83 | List calls = removeFreeCall(logs); 84 | 85 | for (LogHolder logHolder : calls) { 86 | System.out.println( 87 | logHolder.getPhone() + " " + logHolder.getCallDuration()); 88 | } 89 | 90 | for (LogHolder logHolder : calls) { 91 | String duration = logHolder.getCallDuration(); 92 | if (LocalTime.parse(duration).getHour() == 0) { 93 | int minutes = LocalTime.parse(duration).getMinute(); 94 | if (minutes < 5) { 95 | totalCost += (minutes * 60 + (LocalTime.parse(duration).getSecond())) * 3; 96 | 97 | } else { 98 | totalCost += (minutes + (LocalTime.parse(duration).getSecond() > 0 ? 1 : 0)) * 150; 99 | 100 | } 101 | } else { 102 | 103 | totalCost += ((LocalTime.parse(duration).getHour() * 60) + (LocalTime.parse(duration).getMinute()) 104 | + (LocalTime.parse(duration).getSecond() > 0 ? 1 : 0)) * 150; 105 | } 106 | } 107 | 108 | return totalCost; 109 | } 110 | } 111 | 112 | class LogHolder { 113 | private String phone; 114 | private double totalDuration; 115 | private double numericalSum; 116 | private String callDuration; 117 | 118 | public LogHolder(String phone, String callDuration) { 119 | super(); 120 | this.phone = phone; 121 | this.callDuration = callDuration; 122 | } 123 | 124 | public LogHolder(String phone, double totalDuration) { 125 | super(); 126 | this.phone = phone; 127 | this.totalDuration = totalDuration; 128 | 129 | } 130 | 131 | public LogHolder(String phone, double totalDuration, double numericalSum) { 132 | super(); 133 | this.phone = phone; 134 | this.totalDuration = totalDuration; 135 | this.numericalSum = numericalSum; 136 | 137 | } 138 | 139 | public void setPhone(String phone) { 140 | this.phone = phone; 141 | } 142 | 143 | public String getPhone() { 144 | return phone; 145 | } 146 | 147 | public void setTotalDuration(double totalDuration) { 148 | this.totalDuration = totalDuration; 149 | } 150 | 151 | public double getTotalDuration() { 152 | return totalDuration; 153 | } 154 | 155 | public void setNumericalSum(double numericalSum) { 156 | this.numericalSum = numericalSum; 157 | } 158 | 159 | public double getNumericalSum() { 160 | return numericalSum; 161 | } 162 | 163 | public void setCallDuration(String callDuration) { 164 | this.callDuration = callDuration; 165 | } 166 | 167 | public String getCallDuration() { 168 | return callDuration; 169 | } 170 | 171 | } 172 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | --------------------------------------------------------------------------------