├── .gitignore ├── .travis.yml ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── com │ └── codingmaniacs │ ├── books │ └── StringChallenges.java │ ├── codility │ ├── CollectionChallenges.java │ ├── NumericChallenges.java │ └── StringChallenges.java │ ├── hackerrank │ ├── CollectionChallenges.java │ └── StringChallenges.java │ └── others │ ├── CollectionChallenges.java │ └── StringChallenges.java └── test └── java └── com └── codingmaniacs ├── books └── StringChallengesTests.java ├── codility ├── CollectionChallengesTests.java ├── NumericChallengesTests.java └── StringChallengesTests.java ├── hackerrank ├── CollectionChallengesTests.java └── StringChallengesTests.java └── others ├── CollectionChallengesTests.java └── StringChallengesTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | ### Intellij ### 2 | .idea 3 | *.iml 4 | *.ipr 5 | *.iws 6 | 7 | ### Go ### 8 | # Binaries for programs and plugins 9 | *.exe 10 | *.dll 11 | *.so 12 | *.dylib 13 | 14 | # Test binary, build with `go test -c` 15 | *.test 16 | 17 | # Output of the go coverage tool, specifically when used with LiteIDE 18 | *.out 19 | 20 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 21 | .glide/ 22 | 23 | ### Java ### 24 | # Compiled class file 25 | *.class 26 | 27 | # Log file 28 | *.log 29 | 30 | # BlueJ files 31 | *.ctxt 32 | 33 | # Mobile Tools for Java (J2ME) 34 | .mtj.tmp/ 35 | 36 | # Package Files # 37 | *.jar 38 | *.war 39 | *.ear 40 | *.zip 41 | *.tar.gz 42 | *.rar 43 | 44 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 45 | hs_err_pid* 46 | 47 | ### Maven ### 48 | target/ 49 | pom.xml.tag 50 | pom.xml.releaseBackup 51 | pom.xml.versionsBackup 52 | pom.xml.next 53 | release.properties 54 | dependency-reduced-pom.xml 55 | buildNumber.properties 56 | .mvn/timing.properties 57 | 58 | # Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) 59 | !/.mvn/wrapper/maven-wrapper.jar 60 | 61 | ### SBT ### 62 | # Simple Build Tool 63 | # http://www.scala-sbt.org/release/docs/Getting-Started/Directories.html#configuring-version-control 64 | 65 | dist/* 66 | lib_managed/ 67 | src_managed/ 68 | project/boot/ 69 | project/plugins/project/ 70 | .history 71 | .cache 72 | .lib/ 73 | 74 | ### Gradle ### 75 | .gradle 76 | build/ 77 | 78 | # Ignore Gradle GUI config 79 | gradle-app.setting 80 | 81 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 82 | !gradle-wrapper.jar 83 | 84 | # Cache of project 85 | .gradletasknamecache 86 | 87 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 88 | # gradle/wrapper/gradle-wrapper.properties 89 | 90 | ### Gradle Patch ### 91 | **/build/ 92 | 93 | ### Bloop ### 94 | .bloop/ 95 | 96 | ### Metals ### 97 | .metals/ 98 | project/metals.sbt 99 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk11 4 | 5 | branches: 6 | # safelist 7 | only: 8 | - master 9 | # blocklist 10 | except: 11 | - /^feature.*$/ 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Coding Challenges 2 | 3 | [![Build Status](https://travis-ci.org/geektimus/java-challenges.svg?branch=master)](https://travis-ci.org/geektimus/java-challenges) 4 | 5 | This repo will contain the solutions using Java 8 for challenges found on: 6 | 7 | * Books 8 | * Hacker Rank 9 | * Codility 10 | * CodeFights 11 | 12 | ## Challenges 13 | 14 | ### Codility 15 | 16 | #### Can we sort an array with a simple swap? 17 | 18 | We need to write a function that will return true if we can sort an array swapping only two elements. 19 | 20 | #### Mystery number 21 | 22 | We need to write a function to shuffle the digits on a number on a particular way. The first char with the last char, 23 | the second char with the second to last char until we use all the digits. 24 | 25 | #### Find the longest sentence. 26 | 27 | We have phrases composed by sentences and each of this sentences contain words. We need to write a function that will 28 | give us the number of words on the longest sentence. The sentences are separated by "?", "!", "." and the words simply 29 | by spaces (" "). 30 | 31 | #### Binary Gap 32 | 33 | A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. 34 | 35 | #### CyclicRotation 36 | 37 | We need to perform an array shift to the right a given number of times. 38 | 39 | #### Frog Jumps 40 | 41 | A little frog wants to cross to the other side of the river, but it can only jump to the leaves that fall on the water 42 | and only then the complete path from 0 to target has all required leaves. 43 | Given the starting position 0, and a non empty array indexed by each second and the position of the leaf. Find the earliest 44 | time when the frog can jump all the way from 0 to the target position. 45 | 46 | #### Permutation Check 47 | 48 | We need to perform a check on an array to see if it's a permutation of N elements where N original size of the array. 49 | 50 | **Note:** A permutation is a sequence containing each element from 1 to N once, and only once. 51 | 52 | #### Max Counter (Counter Operations) 53 | 54 | We need to calculate the values of counters after applying all alternating operations: increase counter by 1; set 55 | value of all counters to current maximum. 56 | 57 | #### Minimum Number of Plays on a Casino (\*) 58 | 59 | A guy walks out of a Casino with N chips. We know that he played W times an all in. 60 | We need to find the minimum number of plays he could play on the casino to earn those N chips. 61 | 62 | #### Factory of Shoes (\*) 63 | 64 | We have a line of shoes composed of Left (L) and Right (R) shoes. We want to assign a group of workers to work on the 65 | shoes, but we need to guarantee that we assign each worker a group of shoes that contains the same number of L and R shoes. 66 | 67 | ### Hacker Rank 68 | 69 | #### Odd number generator 70 | 71 | We need to write a function that return all the odd numbers on a range given the start and the end of the range as 72 | integers. This collection will include the start and end integers if they are odd numbers too 73 | 74 | ### Books 75 | 76 | #### Unique characters 77 | 78 | We need to write a function that will tell us if all the characters on a given string are unique. 79 | 80 | #### Check permutation 81 | 82 | We need to write a function that given two strings let us find if one is a permutation of the other. 83 | 84 | #### URL Friendly String 85 | 86 | Given a String and its true length, transform the string to a URL friendly string by replacing the spaces by %20 87 | 88 | **Note:** We can assume that the string contains a length that allow us to store the additional chars 89 | without having to allocate a new string. 90 | 91 | ### Others (Challenges proposed by Friends or Solved on hackatons) 92 | 93 | #### Recursively reverse a string 94 | 95 | Given a string, reverse the characters and return 96 | 97 | #### Find the first char that repeats itself on a given string 98 | 99 | Given a string, find the first chat that repeats itself. 100 | 101 | #### Sort server logs by two fields 102 | 103 | We had to sort a list of logs given the log level, or the event timestamp. -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | // Apply the java plugin to add support for Java 3 | id 'java' 4 | } 5 | 6 | repositories { 7 | // Use jcenter for resolving your dependencies. 8 | // You can declare any Maven/Ivy/file repository here. 9 | jcenter() 10 | } 11 | 12 | dependencies { 13 | testImplementation 'junit:junit:4.13.1' 14 | } 15 | 16 | group = 'com.codingmaniacs.challenges' 17 | version = '1.0-SNAPSHOT' 18 | description = 'Java 8 Challenges' 19 | sourceCompatibility = '8' 20 | 21 | tasks.withType(JavaCompile) { 22 | options.encoding = 'UTF-8' 23 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geektimus/java-challenges/03a888a609435506188a7d652ec559f0d0b9c1a7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Jun 24 16:28:06 COT 2020 2 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip 3 | distributionBase=GRADLE_USER_HOME 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | 88 | @rem Execute Gradle 89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 90 | 91 | :end 92 | @rem End local scope for the variables with windows NT shell 93 | if "%ERRORLEVEL%"=="0" goto mainEnd 94 | 95 | :fail 96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 97 | rem the _cmd.exe /c_ return code! 98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 99 | exit /b 1 100 | 101 | :mainEnd 102 | if "%OS%"=="Windows_NT" endlocal 103 | 104 | :omega 105 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | */ 4 | 5 | rootProject.name = 'challenges' 6 | -------------------------------------------------------------------------------- /src/main/java/com/codingmaniacs/books/StringChallenges.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.books; 2 | 3 | import java.util.Arrays; 4 | import java.util.Hashtable; 5 | import java.util.Map; 6 | 7 | public class StringChallenges { 8 | 9 | /** 10 | * Function that given a string determines if all letters are unique 11 | * 12 | * @param str String being analyzed. 13 | * @return true if all the chars in this string are unique, false otherwise. 14 | */ 15 | public static boolean hasUniqueChars(String str) { 16 | return str.chars().distinct().count() == str.length(); 17 | } 18 | 19 | public static boolean hasUniqueCharsHash(String str) { 20 | Hashtable chars = new Hashtable<>(str.length()); 21 | 22 | for (String c : str.split("")) { 23 | if (chars.containsKey(c)) 24 | return false; 25 | else 26 | chars.putIfAbsent(c, 1); 27 | } 28 | 29 | for (Map.Entry val : chars.entrySet()) { 30 | System.out.println(val); 31 | } 32 | return true; 33 | } 34 | 35 | /** 36 | * Finds if word1 is a permutation of word2 37 | * 38 | * @param word1 First word to test 39 | * @param word2 Second word to test 40 | * @return true if word1 is a permutation of word2, false otherwise. 41 | */ 42 | public static boolean isPermutation(String word1, String word2) { 43 | if (word1 == null || word2 == null) 44 | return false; 45 | 46 | if (word1.length() != word2.length()) 47 | return false; 48 | 49 | if (word1.equals(word2)) 50 | return true; 51 | 52 | char[] word1arr = word1.toLowerCase().toCharArray(); 53 | char[] word2arr = word2.toLowerCase().toCharArray(); 54 | Arrays.sort(word1arr); 55 | Arrays.sort(word2arr); 56 | return Arrays.equals(word1arr, word2arr); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/codingmaniacs/codility/CollectionChallenges.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.codility; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class CollectionChallenges { 8 | /** 9 | * Finds if the given array can be sorted moving only two values on a single swap 10 | * 11 | * @param data array to be checked. 12 | * @return true if the array can be sorted using one swap, false otherwise 13 | */ 14 | public static boolean isOrderedBySingleSwap(int data[]) { 15 | if (data == null || data.length == 0 || data.length == 1) 16 | return true; 17 | 18 | int first = 0, second = 0; 19 | int min = 0; 20 | boolean sorted = true; 21 | 22 | for (int i = 0; i < data.length - 1; i++) { 23 | if (data[i] > data[i + 1]) { 24 | first = i; 25 | second = first + 1; 26 | min = data[first]; 27 | sorted = false; 28 | break; 29 | } 30 | } 31 | 32 | if (sorted) { 33 | return true; 34 | } 35 | 36 | for (int i = second; i < data.length; i++) { 37 | if (min < data[i]) { 38 | second = i - 1; 39 | break; 40 | } 41 | } 42 | 43 | // Swap 44 | int temp = data[first]; 45 | data[first] = data[second]; 46 | data[second] = temp; 47 | 48 | // Last validation 49 | for (int i = 0; i < data.length - 1; i++) { 50 | if (data[i] > data[i + 1]) { 51 | return false; 52 | } 53 | } 54 | return true; 55 | 56 | } 57 | 58 | /** 59 | * Performs an element shift to the right step times. 60 | * 61 | * @param ns Number array 62 | * @param step step of the shift right 63 | * @return number array shifted to the right step times. 64 | */ 65 | public static int[] arrayShiftRight(int[] ns, int step) { 66 | int s = step; 67 | int nsLength = ns.length; 68 | if (nsLength == 0 || nsLength == 1 || s == nsLength) 69 | return ns; 70 | 71 | int[] res = new int[nsLength]; 72 | 73 | s %= nsLength; 74 | 75 | int[] l = Arrays.copyOfRange(ns, 0, nsLength - s); 76 | int[] r = Arrays.copyOfRange(ns, nsLength - s, nsLength); 77 | 78 | System.arraycopy(r, 0, res, 0, r.length); 79 | System.arraycopy(l, 0, res, r.length, l.length); 80 | 81 | return res; 82 | } 83 | 84 | /** 85 | * Finds the earliest time when the frog can jump all the way from 0 to the target position 86 | * 87 | * @param target End position / The goal position of the small frog 88 | * @param leaves Array of the positions where the leaves fall indexed by second. 89 | * @return the earliest time when the frog can reach target given the leaves array 90 | */ 91 | public static int findFrogJumpsOverLeaves(int target, int[] leaves) { 92 | Set storage = new HashSet<>(target); 93 | int index = -1; 94 | for (int i = 0; i < leaves.length; i++) { 95 | if (leaves[i] <= target) { 96 | storage.add(leaves[i]); 97 | if (storage.size() == target) { 98 | index = i; 99 | break; 100 | } 101 | } 102 | } 103 | return index; 104 | } 105 | 106 | /** 107 | * Find if an array is a permutation of n elements 108 | * 109 | * @param arr Array of numbers 110 | * @return True if arr is a permutation of n elements, False otherwise 111 | * @apiNote A permutation is a sequence containing each element from 1 to N once, and only once. 112 | */ 113 | public static int isPermutation(int[] arr) { 114 | int n = arr.length; 115 | 116 | Set numbers = new HashSet<>(n); 117 | 118 | for (int el : arr) { 119 | if (el > n) 120 | return 0; 121 | numbers.add(el); 122 | } 123 | 124 | return numbers.size() == n ? 1 : 0; 125 | } 126 | 127 | 128 | /** 129 | * This function applies a set of operations over an array of n counters 130 | * 131 | * @param n number of counters to be returned 132 | * @param op Array containing the operations to be applied to the counters. 133 | * @return an Array with the last state after applying the operations. 134 | */ 135 | public static int[] counterOperations(int n, int[] op) { 136 | int[] counters = new int[n]; 137 | int baseUpdateValue = -1; 138 | int currentMax = -1; 139 | 140 | for (int el : op) { 141 | if (el == n + 1) { 142 | // Mark the current value to be used as a base for the next increment. 143 | // The next increment for any position should be baseUpdateValue + 1 144 | baseUpdateValue = currentMax; 145 | } else { 146 | // Since the position (index) is the counter value - 1 147 | int pos = el - 1; 148 | if (counters[pos] < baseUpdateValue) { 149 | // The value was not updated yet 150 | counters[pos] = baseUpdateValue + 1; 151 | } else 152 | counters[pos] = counters[pos] + 1; 153 | 154 | // If the value updated is now the max of all the elements we update the current max 155 | if (counters[pos] > currentMax) { 156 | currentMax = counters[pos]; 157 | } 158 | } 159 | } 160 | 161 | // We need to update the remaining values if they were not updated on the for loop 162 | for (int i = 0; i < counters.length; i++) { 163 | if (counters[i] < baseUpdateValue) { 164 | counters[i] = baseUpdateValue; 165 | } 166 | } 167 | 168 | return counters; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/main/java/com/codingmaniacs/codility/NumericChallenges.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.codility; 2 | 3 | import java.util.Arrays; 4 | 5 | public class NumericChallenges { 6 | /** 7 | * Given a number it shuffles the digits taking one from the front and one from the end until we reach the middle. 8 | * 9 | * @param number Number to be shuffled 10 | * @return Number with the original digits shuffled. 11 | */ 12 | public static int shuffleNumber(int number) { 13 | 14 | if (number < 10) 15 | return number; 16 | 17 | String numberStr = String.valueOf(number); 18 | int length = numberStr.length(); 19 | StringBuilder sb = new StringBuilder(); 20 | 21 | for (int i = 0; i < length / 2; i++) { 22 | sb.append(numberStr.charAt(i)); 23 | sb.append(numberStr.charAt(length - i - 1)); 24 | } 25 | if (length % 2 != 0) { 26 | sb.append(numberStr.charAt(length / 2)); 27 | } 28 | return Integer.valueOf(sb.toString()); 29 | } 30 | 31 | /** 32 | * Finds the binary gap of the given number 33 | * Binary gap is the max number of consecutive zeros between ones on the binary representation of the number. 34 | * 35 | * @param number Number 36 | * @return Integer representing the binary gap on the given number. 37 | */ 38 | public static int findBinaryGap(int number) { 39 | String binaryRep = Integer.toBinaryString(number); 40 | 41 | String trimmedRep = binaryRep.substring(1, binaryRep.lastIndexOf("1")); 42 | 43 | return Arrays 44 | .stream(trimmedRep.split("1")) 45 | .mapToInt(String::length) 46 | .max() 47 | .orElse(0); 48 | 49 | } 50 | 51 | /** 52 | * Returns the minimum number of plays a player can make to earn {{@code chips}} using max of {{@code allInPlays}} plays 53 | * 54 | * @param chips Number of chips the player earned on his visit to the casino. 55 | * @param allInPlays Number of all in moves that he used. 56 | * @return Minimum number of plays a player can make to earn {{@code chips}} 57 | */ 58 | public static int minimumPlays(int chips, int allInPlays) { 59 | if (allInPlays == 0) { 60 | return chips - 1; 61 | } 62 | 63 | int plays = 0; 64 | 65 | // loop while we have chips or while we have all in plays to make 66 | while (chips > 1 && allInPlays > 0) { 67 | if (chips % 2 == 0) { 68 | allInPlays--; 69 | chips /= 2; 70 | plays++; 71 | } else { 72 | chips--; 73 | plays++; 74 | } 75 | } 76 | 77 | // Sum the rest of the chips 78 | if (chips > 1) { 79 | plays += chips - 1; 80 | } 81 | return plays; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/codingmaniacs/codility/StringChallenges.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.codility; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class StringChallenges { 6 | /** 7 | * Given a phrase it counts the max number of words of the longest sentence. 8 | * 9 | * @param phrase Phrase containing sentences that we need to analyze. 10 | * @return Max number of words on the longest sentence. 11 | */ 12 | static int countMaxWords(String phrase) { 13 | if (phrase == null || phrase.isEmpty()) 14 | return 0; 15 | 16 | return Stream 17 | .of(phrase.split("[?!.]")) 18 | .map(String::trim) 19 | .mapToInt(sentence -> sentence.split("\\s+").length) 20 | .max() 21 | .orElse(0); 22 | } 23 | 24 | 25 | /** 26 | * Given a line of shoes (L,R), we need to find the number of workers that can work on them given the condition that 27 | * A worker can work only on a group where the group contains the same number of L and R shoes. 28 | * 29 | * @param lineOfShoes String representing the line of shoes that we are processing. 30 | * @return Number of workers that can be assigned to work on the shoes. 31 | */ 32 | public static int countMinWorkers(String lineOfShoes) { 33 | if (lineOfShoes.length() == 2) 34 | return 1; 35 | 36 | int workers = 0; 37 | int lCount = 0, rCount = 0; 38 | 39 | for (Character shoe : lineOfShoes.toCharArray()) { 40 | if (shoe.toString().equals("L")) { 41 | lCount++; 42 | } else { 43 | rCount++; 44 | } 45 | if (lCount == rCount) { 46 | workers++; 47 | } 48 | } 49 | return workers; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/codingmaniacs/hackerrank/CollectionChallenges.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.hackerrank; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class CollectionChallenges { 7 | /** 8 | * Returns an array containing the odd numbers between bottom and top 9 | * 10 | * @param bottom Lower bound 11 | * @param top Top bound 12 | * @return array containing all the odd numbers between lower and top 13 | */ 14 | public static int[] oddNumbers(int bottom, int top) { 15 | List numbers = new ArrayList(); 16 | int lBound = bottom; 17 | if (!isOddNumber(lBound)) 18 | lBound = lBound + 1; 19 | 20 | while (lBound <= top) { 21 | numbers.add(lBound); 22 | lBound = lBound + 2; 23 | } 24 | return toIntArray(numbers); 25 | } 26 | 27 | /** 28 | * Returns an array containing all the int values of the list. 29 | * 30 | * @param numList List of integers to be transformed 31 | * @return array of ints. 32 | */ 33 | private static int[] toIntArray(List numList) { 34 | int[] numbers = new int[numList.size()]; 35 | for (int i = 0; i < numList.size(); i++) { 36 | numbers[i] = numList.get(i); 37 | } 38 | return numbers; 39 | } 40 | 41 | /** 42 | * Returns if the given number is odd 43 | * 44 | * @param n number 45 | * @return boolean if the number is odd 46 | */ 47 | private static boolean isOddNumber(int n) { 48 | return !(n % 2 == 0); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/codingmaniacs/hackerrank/StringChallenges.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.hackerrank; 2 | 3 | public class StringChallenges { 4 | public static String reduceString(String s) { 5 | if (s == null) { 6 | return null; 7 | } 8 | String[] letters = s.split(""); 9 | StringBuilder sb = new StringBuilder(); 10 | boolean toggleCase = false; 11 | for (String l : letters) { 12 | if (l.equals("_")) { 13 | sb.deleteCharAt(sb.length() - 1); 14 | } else if (l.equals("+")) { 15 | toggleCase = true; 16 | } else { 17 | boolean isUpper = l.matches("[A-Z]"); 18 | sb.append(toggleCase ? isUpper ? l.toLowerCase() : l.toUpperCase() : l); 19 | toggleCase = false; 20 | } 21 | 22 | } 23 | return sb.toString(); 24 | } 25 | 26 | public static boolean equal(String s1, String s2) { 27 | if (s1 == null && s2 == null ) { 28 | return true; 29 | } 30 | if (s1 == null || s2 == null ) { 31 | return false; 32 | } 33 | return reduceString(s1).equals(reduceString(s2)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/codingmaniacs/others/CollectionChallenges.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.regex.Matcher; 6 | import java.util.regex.Pattern; 7 | 8 | public class CollectionChallenges { 9 | 10 | private static final Pattern pattern = Pattern.compile("^(\\d+)\\s(\\w+)\\s(.*)$"); 11 | 12 | @SuppressWarnings("unused") 13 | private enum LogLevel { 14 | OFF, 15 | FATAL, 16 | ERROR, 17 | WARNING, 18 | INFO, 19 | DEBUG, 20 | TRACE, 21 | ALL 22 | } 23 | 24 | private static class LogEntry { 25 | private final Long timestamp; 26 | private final LogLevel level; 27 | private final String content; 28 | 29 | LogEntry(Long timestamp, LogLevel logLevel, String content) { 30 | this.timestamp = timestamp; 31 | this.level = logLevel; 32 | this.content = content; 33 | } 34 | 35 | public LogLevel getLevel() { 36 | return level; 37 | } 38 | 39 | public Long getTimestamp() { 40 | return timestamp; 41 | } 42 | 43 | @Override 44 | public String toString() { 45 | return timestamp + " " + level + " " + content; 46 | } 47 | } 48 | 49 | public static LogEntry getLogEntryFromLine(String logLine) { 50 | Matcher matcher = pattern.matcher(logLine); 51 | 52 | long ts = 0L; 53 | LogLevel ll = LogLevel.OFF; 54 | String content = ""; 55 | 56 | while (matcher.find()) { 57 | ts = Long.parseLong(matcher.group(1)); 58 | ll = LogLevel.valueOf(matcher.group(2)); 59 | content = matcher.group(3); 60 | } 61 | 62 | return new LogEntry(ts, ll, content); 63 | } 64 | 65 | public static String[] sortLogs(String[] myLogInfo) { 66 | Comparator comparator = Comparator.comparing(LogEntry::getLevel) 67 | .thenComparing(LogEntry::getTimestamp); 68 | 69 | return Arrays.stream(myLogInfo) 70 | .map(CollectionChallenges::getLogEntryFromLine) 71 | .sorted(comparator) 72 | .map(LogEntry::toString) 73 | .toArray(String[]::new); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/codingmaniacs/others/StringChallenges.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | class StringChallenges { 10 | /** 11 | * Given a string it reverses the order of the chars 12 | * 13 | * @param str String 14 | * @return String on reverse order 15 | */ 16 | static String reverse(String str) { 17 | if (str.length() == 0) return str; 18 | else { 19 | int last = str.length() - 1; 20 | return str.charAt(last) + reverse(str.substring(0, last)); 21 | } 22 | } 23 | 24 | /** 25 | * Given a string, we should find the first occurrence of some letter 26 | * 27 | * @param str String to be used 28 | * @return Returns the letter duplicated. 29 | */ 30 | static String findFirstRepeatedChar(String str) { 31 | if (str == null || str.isEmpty()) 32 | return ""; 33 | 34 | final Map occ = new HashMap<>(26); 35 | 36 | for (int i = 0; i < str.length(); i++) { 37 | final String shard = Character.toString(str.charAt(i)); 38 | if (occ.containsKey(shard)) { 39 | return shard; 40 | } 41 | occ.putIfAbsent(shard, 1); 42 | } 43 | return ""; 44 | } 45 | 46 | /** 47 | * Given a String and its true length, transform the string to a URL friendly string by replacing the spaces by %20 48 | * 49 | * @param str String to be transformed 50 | * @param trueLength True size of the string without the trailing spaces. 51 | * @return A URL friendly string with the spaces replaced. 52 | */ 53 | static String URLlify(String str, int trueLength) { 54 | if (str.length() == trueLength) 55 | return str; 56 | 57 | char[] chars = str.toCharArray(); 58 | int spaces = 0; 59 | 60 | // Count spaces 61 | for (int i = 0; i < trueLength; i++) { 62 | if (chars[i] == ' ') { 63 | spaces++; 64 | } 65 | } 66 | 67 | if (trueLength < str.length()) chars[trueLength] = '\0'; 68 | 69 | // Replace the string backwards so we don't need to worry about overriding data. 70 | int index = trueLength + spaces * 2; 71 | for (int j = trueLength - 1; j >= 0; j--) { 72 | if (chars[j] == ' ') { 73 | chars[index - 1] = '0'; 74 | chars[index - 2] = '2'; 75 | chars[index - 3] = '%'; 76 | index = index - 3; 77 | } else { 78 | chars[index - 1] = chars[j]; 79 | index--; 80 | } 81 | } 82 | 83 | return new String(chars); 84 | } 85 | 86 | public static String balancedBraces(String str) { 87 | String[] braces = str.split(""); 88 | 89 | Map symbolPairs = Stream.of(new String[][] { 90 | { "{", "}" }, 91 | { "[", "]" }, 92 | { "(", ")" }, 93 | }).collect(Collectors.toMap(data -> data[0], data -> data[1])); 94 | 95 | Map result = Stream.of(new [][] { 96 | { "{", 0 }, 97 | { "[", 0 }, 98 | { "(", 0 }, 99 | }).collect(Collectors.toMap(data -> data[0], data -> data[1])); 100 | 101 | String currentSymbol = braces[0]; 102 | int counter = 1; 103 | for (int i = 1; i < braces.length - 1; i++) { 104 | if (braces[i].equals(symbolPairs.getOrDefault(currentSymbol, ""))) { 105 | currentSymbol = braces[i + 1]; 106 | counter--; 107 | } else { 108 | currentSymbol = braces[i]; 109 | counter++; 110 | } 111 | } 112 | 113 | return counter==0 ? "YES" : "NO"; 114 | 115 | } 116 | 117 | public static String[] balancedBraces(String[] str) { 118 | return Arrays.stream(str).map(StringChallenges::balancedBraces).toArray(String[]::new); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/test/java/com/codingmaniacs/books/StringChallengesTests.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.books; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertEquals; 6 | 7 | public class StringChallengesTests { 8 | @Test 9 | public void doesAlphanumericContainUniqueChars() { 10 | String word = "alphanumeric"; 11 | 12 | boolean hasUniqueChars = StringChallenges.hasUniqueChars(word); 13 | assertEquals("This should be false as there are two (a) on this word", false, hasUniqueChars); 14 | } 15 | 16 | @Test 17 | public void doesMomContainUniqueChars() { 18 | String word = "mom"; 19 | 20 | boolean hasUniqueChars = StringChallenges.hasUniqueChars(word); 21 | assertEquals("This should be false as there are two (m) on this word", false, hasUniqueChars); 22 | } 23 | 24 | @Test 25 | public void doesAbcContainUniqueChars() { 26 | String word = "abc"; 27 | 28 | boolean hasUniqueChars = StringChallenges.hasUniqueChars(word); 29 | assertEquals("This should be true as all letters are unique", true, hasUniqueChars); 30 | } 31 | 32 | @Test 33 | public void doesEnableContainUniqueChars() { 34 | String word = "abode"; 35 | 36 | boolean hasUniqueChars = StringChallenges.hasUniqueChars(word); 37 | assertEquals("This should be true as all letters are unique", true, hasUniqueChars); 38 | } 39 | 40 | @Test 41 | public void doesMomContainUniqueCharsHash() { 42 | String word = "mom"; 43 | 44 | boolean hasUniqueChars = StringChallenges.hasUniqueCharsHash(word); 45 | assertEquals("This should be false as there are two (m) on this word", false, hasUniqueChars); 46 | } 47 | 48 | @Test 49 | public void isPermutationWithOnlyOneValue() { 50 | String word1 = "word"; 51 | 52 | boolean isPermutation = StringChallenges.isPermutation(word1, null); 53 | assertEquals("This should be false as we have one word missing to compare", false, isPermutation); 54 | } 55 | 56 | @Test 57 | public void isPermutationDifferentLength() { 58 | String word = "word", otherWord = "other"; 59 | 60 | boolean isPermutation = StringChallenges.isPermutation(word, otherWord); 61 | assertEquals("This should be false as the lengths are different", false, isPermutation); 62 | } 63 | 64 | @Test 65 | public void isCatPermutationOfTac() { 66 | String word1 = "cat", word2 = "tac"; 67 | 68 | boolean isPermutation = StringChallenges.isPermutation(word1, word2); 69 | assertEquals("This should be true as cat is a permutation of tac", true, isPermutation); 70 | } 71 | 72 | @Test 73 | public void isTomatoPermutationOfOtamoc() { 74 | String word1 = "tomato", word2 = "otamoc"; 75 | 76 | boolean isPermutation = StringChallenges.isPermutation(word1, word2); 77 | assertEquals("This should be false as tomato is not a permutation of otamoc", false, isPermutation); 78 | } 79 | 80 | @Test 81 | public void isPermutationPermutationOfPermutation() { 82 | String word1 = "permutation", word2 = "permutation"; 83 | 84 | boolean isPermutation = StringChallenges.isPermutation(word1, word2); 85 | assertEquals("This should be true as it's the same word", true, isPermutation); 86 | } 87 | 88 | @Test 89 | public void isCatPermutationOfTacWithDifferentCase() { 90 | String word1 = "Cat", word2 = "Tac"; 91 | 92 | boolean isPermutation = StringChallenges.isPermutation(word1, word2); 93 | assertEquals("This should be true as cat is a permutation of tac", true, isPermutation); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/test/java/com/codingmaniacs/codility/CollectionChallengesTests.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.codility; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class CollectionChallengesTests { 8 | 9 | @Test 10 | public void validateNormalArraySolvable() { 11 | int[] numbers = {1, 5, 3, 3, 7}; 12 | boolean success = CollectionChallenges.isOrderedBySingleSwap(numbers.clone()); 13 | assertTrue("It should be true we get to [1,3,3,5,7] in one swap", success); 14 | } 15 | 16 | @Test 17 | public void validateNormalArrayUnsolvable() { 18 | int[] numbers = {1, 3, 5, 3, 4}; 19 | boolean success = CollectionChallenges.isOrderedBySingleSwap(numbers.clone()); 20 | assertFalse("It should be false as we get to [1,3,3,4,5] in two swaps", success); 21 | } 22 | 23 | @Test 24 | public void validateShortArraySolvable() { 25 | int[] numbers = {1, 5, 3}; 26 | boolean success = CollectionChallenges.isOrderedBySingleSwap(numbers.clone()); 27 | assertTrue("It should be true as we get to [1,3,5] in one swap", success); 28 | } 29 | 30 | @Test 31 | public void validateUnaryArraySolvable() { 32 | int[] numbers = {1}; 33 | boolean success = CollectionChallenges.isOrderedBySingleSwap(numbers.clone()); 34 | assertTrue("It should be true as we don't require swap (already sorted)", success); 35 | } 36 | 37 | @Test 38 | public void validateAlreadySortedArray() { 39 | int[] numbers = {1, 2, 3, 4, 5, 6}; 40 | boolean success = CollectionChallenges.isOrderedBySingleSwap(numbers.clone()); 41 | assertTrue("It should be true as we don't require swap (already sorted)", success); 42 | } 43 | 44 | @Test 45 | public void validateLongArrayUnsolvable() { 46 | int[] numbers = {1, 3, 5, 5, 8, 2, 1}; 47 | boolean success = CollectionChallenges.isOrderedBySingleSwap(numbers.clone()); 48 | assertFalse("It should be false as we get to [1,1,2,3,5,5,8] in three swaps", success); 49 | } 50 | 51 | @Test 52 | public void arrayShiftRightWhereNEqualsK() { 53 | int[] numbers = {1, 2, 3, 4}; 54 | int[] result = CollectionChallenges.arrayShiftRight(numbers, 4); 55 | int[] expected = {1, 2, 3, 4}; 56 | assertArrayEquals(expected, result); 57 | } 58 | 59 | @Test 60 | public void arrayShiftRightWhereNLessThanK() { 61 | int[] numbers = {1, 2, 3, 4}; 62 | int[] result = CollectionChallenges.arrayShiftRight(numbers, 3); 63 | int[] expected = {2, 3, 4, 1}; 64 | assertArrayEquals(expected, result); 65 | } 66 | 67 | @Test 68 | public void arrayShiftRightFiveElements() { 69 | int[] numbers = {3, 8, 9, 7, 6}; 70 | int[] result = CollectionChallenges.arrayShiftRight(numbers, 3); 71 | int[] expected = {9, 7, 6, 3, 8}; 72 | assertArrayEquals(expected, result); 73 | } 74 | 75 | @Test 76 | public void arrayShiftRightEmpty() { 77 | int[] numbers = {}; 78 | int[] result = CollectionChallenges.arrayShiftRight(numbers, 3); 79 | int[] expected = {}; 80 | assertArrayEquals(expected, result); 81 | } 82 | 83 | @Test 84 | public void arrayShiftRightOneElement() { 85 | int[] numbers = {1}; 86 | int[] result = CollectionChallenges.arrayShiftRight(numbers, 3); 87 | int[] expected = {1}; 88 | assertArrayEquals(expected, result); 89 | } 90 | 91 | @Test 92 | public void arrayShiftRightKGreaterThanN() { 93 | int[] numbers = {1, 2, 3}; 94 | int[] result = CollectionChallenges.arrayShiftRight(numbers, 6); 95 | int[] expected = {1, 2, 3}; 96 | assertArrayEquals(expected, result); 97 | } 98 | 99 | @Test 100 | public void findFrogJumpsShortSequence() { 101 | int[] leaves = {1, 3, 2, 4}; 102 | int target = 2; 103 | int result = CollectionChallenges.findFrogJumpsOverLeaves(target, leaves); 104 | int expected = 2; 105 | assertEquals(expected, result); 106 | } 107 | 108 | @Test 109 | public void findFrogJumpsLongSequence() { 110 | int[] leaves = {1, 3, 1, 4, 2, 3, 5, 4}; 111 | int target = 5; 112 | int result = CollectionChallenges.findFrogJumpsOverLeaves(target, leaves); 113 | int expected = 6; 114 | assertEquals(expected, result); 115 | } 116 | 117 | @Test 118 | public void findIfArrayIsPermDuplicatedElements() { 119 | int[] arr = {1, 1}; 120 | int result = CollectionChallenges.isPermutation(arr); 121 | assertEquals(0, result); 122 | } 123 | 124 | @Test 125 | public void findIfArrayIsPermShortUnorderedArr() { 126 | int[] arr = {2, 1}; 127 | int result = CollectionChallenges.isPermutation(arr); 128 | assertEquals(1, result); 129 | } 130 | 131 | @Test 132 | public void findIfArrayIsPermShortOrderedArr() { 133 | int[] arr = {1, 2}; 134 | int result = CollectionChallenges.isPermutation(arr); 135 | assertEquals(1, result); 136 | } 137 | 138 | @Test 139 | public void findIfArrayIsPermLongUnorderedArr() { 140 | int[] arr = {4, 1, 3, 2}; 141 | int result = CollectionChallenges.isPermutation(arr); 142 | assertEquals(1, result); 143 | } 144 | 145 | @Test 146 | public void findIfArrayIsPermLongArrMissingEl() { 147 | int[] arr = {4, 1, 3}; 148 | int result = CollectionChallenges.isPermutation(arr); 149 | assertEquals(0, result); 150 | } 151 | 152 | @Test 153 | public void counterOperationsOneIncreaseOperation() { 154 | int[] arr = {3}; 155 | int n = 5; 156 | int[] expected = {0, 0, 1, 0, 0}; 157 | int[] result = CollectionChallenges.counterOperations(n, arr); 158 | assertArrayEquals(expected, result); 159 | } 160 | 161 | @Test 162 | public void counterOperationsOneUpdateAllOperation() { 163 | int[] arr = {6}; 164 | int n = 5; 165 | int[] expected = {0, 0, 0, 0, 0}; 166 | int[] result = CollectionChallenges.counterOperations(n, arr); 167 | assertArrayEquals(expected, result); 168 | } 169 | 170 | @Test 171 | public void counterOperationsOneUpdateAllAfterIncrease() { 172 | int[] arr = {3, 6}; 173 | int n = 5; 174 | int[] expected = {1, 1, 1, 1, 1}; 175 | int[] result = CollectionChallenges.counterOperations(n, arr); 176 | assertArrayEquals(expected, result); 177 | } 178 | 179 | 180 | @Test 181 | public void counterOperationsOnlyIncreaseSamePosition() { 182 | int[] arr = {1, 1, 1, 1, 1}; 183 | int n = 5; 184 | int[] expected = {5, 0, 0, 0, 0}; 185 | int[] result = CollectionChallenges.counterOperations(n, arr); 186 | assertArrayEquals(expected, result); 187 | } 188 | 189 | @Test 190 | public void counterOperationsOnlyIncreaseDifferentPositions() { 191 | int[] arr = {4, 2, 2, 3}; 192 | int n = 4; 193 | int[] expected = {0, 2, 1, 1}; 194 | int[] result = CollectionChallenges.counterOperations(n, arr); 195 | assertArrayEquals(expected, result); 196 | } 197 | 198 | @Test 199 | public void counterOperationsOnlyMax() { 200 | int[] arr = {2, 5, 5}; 201 | int n = 4; 202 | int[] expected = {1, 1, 1, 1}; 203 | int[] result = CollectionChallenges.counterOperations(n, arr); 204 | assertArrayEquals(expected, result); 205 | } 206 | 207 | @Test 208 | public void counterOperationsComplexSequence() { 209 | int[] arr = {3, 4, 4, 6, 1, 4, 4}; 210 | int n = 5; 211 | int[] expected = {3, 2, 2, 4, 2}; 212 | int[] result = CollectionChallenges.counterOperations(n, arr); 213 | assertArrayEquals(expected, result); 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/test/java/com/codingmaniacs/codility/NumericChallengesTests.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.codility; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertEquals; 6 | 7 | public class NumericChallengesTests { 8 | @Test 9 | public void shuffleNumber() { 10 | int number = 123456; 11 | 12 | int expectedNumber = 162534; 13 | int shuffledNumber = NumericChallenges.shuffleNumber(number); 14 | assertEquals("The number should be shuffled", expectedNumber, shuffledNumber); 15 | } 16 | 17 | @Test 18 | public void shuffleSmallNumber() { 19 | int number = 123; 20 | 21 | int expectedNumber = 132; 22 | int shuffledNumber = NumericChallenges.shuffleNumber(number); 23 | assertEquals("The number should be shuffled", expectedNumber, shuffledNumber); 24 | } 25 | 26 | @Test 27 | public void shuffleOneDigitNumber() { 28 | int number = 1; 29 | 30 | int expectedNumber = 1; 31 | int shuffledNumber = NumericChallenges.shuffleNumber(number); 32 | assertEquals("It should return the same number as no shuffle was applied", expectedNumber, shuffledNumber); 33 | } 34 | 35 | @Test 36 | public void shuffleNegativeNumber() { 37 | int number = -1; 38 | 39 | int expectedNumber = -1; 40 | int shuffledNumber = NumericChallenges.shuffleNumber(number); 41 | assertEquals("It should return the same number as no shuffle was applied", expectedNumber, shuffledNumber); 42 | } 43 | 44 | @Test 45 | public void binaryGapOfFive() { 46 | int number = 5; 47 | 48 | int expectedGap = 1; 49 | int binaryGap = NumericChallenges.findBinaryGap(number); 50 | assertEquals("It should return one because that's the binary gap on 5 (0101)", expectedGap, binaryGap); 51 | } 52 | 53 | @Test 54 | public void binaryGapOfTwenty() { 55 | int number = 20; 56 | 57 | int expectedGap = 1; 58 | int binaryGap = NumericChallenges.findBinaryGap(number); 59 | assertEquals("It should return two because that's the binary gap on 20 (10100)", expectedGap, binaryGap); 60 | } 61 | 62 | @Test 63 | public void binaryGapOfFifteen() { 64 | int number = 15; 65 | 66 | int expectedGap = 0; 67 | int binaryGap = NumericChallenges.findBinaryGap(number); 68 | assertEquals("It should return zero because there's no binary gap on 15 (11111)", expectedGap, binaryGap); 69 | } 70 | 71 | @Test 72 | public void binaryGapOfBigNumber() { 73 | int number = 1041; 74 | 75 | int expectedGap = 5; 76 | int binaryGap = NumericChallenges.findBinaryGap(number); 77 | assertEquals("It should return five because there's no binary gap on 1041 (10000010001)", expectedGap, binaryGap); 78 | } 79 | 80 | @Test 81 | public void binaryGapOfLongestNumber() { 82 | int number = 1148223232; 83 | 84 | int expectedGap = 5; 85 | int binaryGap = NumericChallenges.findBinaryGap(number); 86 | assertEquals("It should return five because there's no binary gap on 1148223232 (01000100011100000111111100000000)", expectedGap, binaryGap); 87 | } 88 | 89 | @Test 90 | public void findTheNumberOfPlaysNoAllIns() { 91 | int chips = 8; 92 | int allInPlays = 0; 93 | int result = NumericChallenges.minimumPlays(chips, allInPlays); 94 | assertEquals("It should return seven as there's no all ins and we have eight chips", 7, result); 95 | } 96 | 97 | @Test 98 | public void findTheNumberOfPlaysTwoAllIns() { 99 | int chips = 18; 100 | int allInPlays = 2; 101 | int result = NumericChallenges.minimumPlays(chips, allInPlays); 102 | assertEquals("It should return six as it's the minimum plays to reach 18", 6, result); 103 | } 104 | 105 | @Test 106 | public void findTheNumberOfPlaysLotsOfAllIns() { 107 | int chips = 10; 108 | int allInPlays = 10; 109 | int result = NumericChallenges.minimumPlays(chips, allInPlays); 110 | assertEquals("It should return four as it's the minimum plays to reach 10 (we don't use all the all ins", 4, result); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/test/java/com/codingmaniacs/codility/StringChallengesTests.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.codility; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertEquals; 6 | 7 | public class StringChallengesTests { 8 | 9 | @Test 10 | public void countWordsNormalPhrase() { 11 | String basePhrase = "We test coders. Give us a try?"; 12 | int expectedWordCount = 4; 13 | 14 | int maxWords = StringChallenges.countMaxWords(basePhrase); 15 | assertEquals("We should have 4 words", expectedWordCount, maxWords); 16 | } 17 | 18 | @Test 19 | public void countWordsComplexPhrase() { 20 | String basePhrase = "Forget CVs..Save time . x x"; 21 | int expectedWordCount = 2; 22 | 23 | int maxWords = StringChallenges.countMaxWords(basePhrase); 24 | assertEquals("We should have 2 words", expectedWordCount, maxWords); 25 | } 26 | 27 | @Test 28 | public void countWordsSingleWord() { 29 | String basePhrase = "Success"; 30 | int expectedWordCount = 1; 31 | 32 | int maxWords = StringChallenges.countMaxWords(basePhrase); 33 | assertEquals("This should be a single word", expectedWordCount, maxWords); 34 | } 35 | 36 | @Test 37 | public void countWordsEmptyString() { 38 | String basePhrase = ""; 39 | int expectedWordCount = 0; 40 | 41 | int maxWords = StringChallenges.countMaxWords(basePhrase); 42 | assertEquals("No words expected on empty string", expectedWordCount, maxWords); 43 | } 44 | 45 | @Test 46 | public void countWordsOnlySymbolsString() { 47 | String basePhrase = "!!!!!!!!!!!!!!!"; 48 | int expectedWordCount = 0; 49 | 50 | int maxWords = StringChallenges.countMaxWords(basePhrase); 51 | assertEquals("No words expected since the string contains only symbols", expectedWordCount, maxWords); 52 | } 53 | 54 | @Test 55 | public void getMinimumWorkersOnlyOnePair() { 56 | String lineOfShoes = "LR"; 57 | int expectedWorkers = 1; 58 | 59 | int workers = StringChallenges.countMinWorkers(lineOfShoes); 60 | assertEquals("One worker should work on this as we have only one pair", expectedWorkers, workers); 61 | } 62 | 63 | @Test 64 | public void getMinimumWorkersOnlyOnePairReverse() { 65 | String lineOfShoes = "RL"; 66 | int expectedWorkers = 1; 67 | 68 | int workers = StringChallenges.countMinWorkers(lineOfShoes); 69 | assertEquals("One worker should work on this as we have only one pair", expectedWorkers, workers); 70 | } 71 | 72 | @Test 73 | public void getMinimumWorkersMixedPairsLength() { 74 | String lineOfShoes = "RLRRLLRLRRLL"; 75 | int expectedWorkers = 4; 76 | 77 | int workers = StringChallenges.countMinWorkers(lineOfShoes); 78 | assertEquals( 79 | "Four workers should work on this line as we have four clear groups", 80 | expectedWorkers, 81 | workers); 82 | } 83 | 84 | @Test 85 | public void getMinimumWorkersComplexLine() { 86 | String lineOfShoes = "LLRLRLRLRLRLRR"; 87 | int expectedWorkers = 1; 88 | 89 | int workers = StringChallenges.countMinWorkers(lineOfShoes); 90 | assertEquals( 91 | "One worker should work on this line since LL has it's pair at the end", 92 | expectedWorkers, 93 | workers); 94 | } 95 | 96 | 97 | @Test 98 | public void getMinimumWorkersComplexLineRepeated() { 99 | String lineOfShoes = "LLRLRLRLRLRLRRLLRLRLRLRLRLRRLLRLRLRLRLRLRRLLRLRLRLRLRLRR"; 100 | int expectedWorkers = 4; 101 | 102 | int workers = StringChallenges.countMinWorkers(lineOfShoes); 103 | assertEquals( 104 | "Four workers should work on this line as it's a mix of a previous one", 105 | expectedWorkers, 106 | workers); 107 | } 108 | 109 | @Test 110 | public void getMinimumWorkersComplexLineRepeatedWithExtraPair() { 111 | String lineOfShoes = "LLRLRLRLRLRLRRLLRLRLRLRLRLRRLLRLRLRLRLRLRRLLRLRLRLRLRLRRLR"; 112 | int expectedWorkers = 5; 113 | 114 | int workers = StringChallenges.countMinWorkers(lineOfShoes); 115 | assertEquals( 116 | "Five workers should work on this line as it's a mix of a previous one + a pair", 117 | expectedWorkers, 118 | workers); 119 | } 120 | 121 | @Test 122 | public void getMinimumWorkersWorstCase() { 123 | String lineOfShoes = "LLRLRLRLRLRLRLLRLRLRLRLRLRRLLRLRLRLRLRLRRLLRLRLRLRLRLRRLRR"; 124 | int expectedWorkers = 1; 125 | 126 | int workers = StringChallenges.countMinWorkers(lineOfShoes); 127 | assertEquals( 128 | "One worker should work on this line since a L on the middle has it's pair at the end", 129 | expectedWorkers, 130 | workers); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/test/java/com/codingmaniacs/hackerrank/CollectionChallengesTests.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.hackerrank; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertArrayEquals; 6 | 7 | public class CollectionChallengesTests { 8 | @Test 9 | public void generateOddsSmallRangeStartsAndEndInOdds() { 10 | int[] numbers = CollectionChallenges.oddNumbers(5, 11); 11 | int[] expected = {5, 7, 9, 11}; 12 | assertArrayEquals(expected, numbers); 13 | } 14 | 15 | @Test 16 | public void generateOddsSmallRangeStartsAndEndInEvens() { 17 | int[] numbers = CollectionChallenges.oddNumbers(4, 8); 18 | int[] expected = {5, 7}; 19 | assertArrayEquals(expected, numbers); 20 | } 21 | 22 | @Test 23 | public void generateOddsOneEvenValue() { 24 | int[] numbers = CollectionChallenges.oddNumbers(2, 2); 25 | int[] expected = {}; 26 | assertArrayEquals(expected, numbers); 27 | } 28 | 29 | @Test 30 | public void generateOddsOneOddValue() { 31 | int[] numbers = CollectionChallenges.oddNumbers(3, 3); 32 | int[] expected = {3}; 33 | assertArrayEquals(expected, numbers); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/codingmaniacs/hackerrank/StringChallengesTests.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.hackerrank; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class StringChallengesTests { 8 | @Test 9 | public void reduceStringRemovingChar() { 10 | String s = "eGymm_"; 11 | String reducedString = StringChallenges.reduceString(s); 12 | String expected = "eGym"; 13 | assertEquals(expected, reducedString); 14 | } 15 | 16 | @Test 17 | public void reduceStringUppercase() { 18 | String s = "e+gym"; 19 | String reducedString = StringChallenges.reduceString(s); 20 | String expected = "eGym"; 21 | assertEquals(expected, reducedString); 22 | } 23 | 24 | @Test 25 | public void reduceStringCombined() { 26 | String s = "ee_+Gym"; 27 | String reducedString = StringChallenges.reduceString(s); 28 | String expected = "egym"; 29 | assertEquals(expected, reducedString); 30 | } 31 | 32 | @Test 33 | public void reduceStringCombined1() { 34 | String s = "+ee_+Gym___"; 35 | String reducedString = StringChallenges.reduceString(s); 36 | String expected = "E"; 37 | assertEquals(expected, reducedString); 38 | } 39 | 40 | @Test 41 | public void reduceStringEmpty1() { 42 | String s = "+a+b+c+D+E_____"; 43 | String reducedString = StringChallenges.reduceString(s); 44 | String expected = ""; 45 | assertEquals(expected, reducedString); 46 | } 47 | 48 | @Test 49 | public void reduceStringNull() { 50 | String s = null; 51 | String reducedString = StringChallenges.reduceString(s); 52 | String expected = null; 53 | assertEquals(expected, reducedString); 54 | } 55 | 56 | @Test 57 | public void reduceStringEmpty() { 58 | String s = ""; 59 | String reducedString = StringChallenges.reduceString(s); 60 | String expected = ""; 61 | assertEquals(expected, reducedString); 62 | } 63 | 64 | @Test 65 | public void compareStrings() { 66 | String s1 = "e+gym"; 67 | String s2 = "eGymm_"; 68 | 69 | boolean equals = StringChallenges.equal(s1, s2); 70 | assertTrue(equals); 71 | } 72 | 73 | @Test 74 | public void compareStrings1() { 75 | String s1 = "+ee_+Gym___"; 76 | String s2 = "E"; 77 | 78 | boolean equals = StringChallenges.equal(s1, s2); 79 | assertTrue(equals); 80 | } 81 | 82 | @Test 83 | public void compareStrings2() { 84 | String s1 = null; 85 | String s2 = null; 86 | 87 | boolean equals = StringChallenges.equal(s1, s2); 88 | assertTrue(equals); 89 | } 90 | 91 | @Test 92 | public void compareStrings3() { 93 | String s1 = ""; 94 | String s2 = ""; 95 | 96 | boolean equals = StringChallenges.equal(s1, s2); 97 | assertTrue(equals); 98 | } 99 | @Test 100 | public void compareStrings4() { 101 | String s1 = null; 102 | String s2 = ""; 103 | 104 | boolean equals = StringChallenges.equal(s1, s2); 105 | assertFalse(equals); 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/test/java/com/codingmaniacs/others/CollectionChallengesTests.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.others; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertArrayEquals; 6 | 7 | public class CollectionChallengesTests { 8 | 9 | @Test 10 | public void sortLogListByLogLevelBasic() { 11 | String[] myLogInfo = { 12 | "1592777662 DEBUG com.codingmaniacs.core.TransactionContext", 13 | "1592777661 INFO com.codingmaniacs.services.account.PurgeManager", 14 | "1592777663 WARNING com.codingmaniacs.core.tc.Connector"}; 15 | 16 | String[] expected = { 17 | "1592777663 WARNING com.codingmaniacs.core.tc.Connector", 18 | "1592777661 INFO com.codingmaniacs.services.account.PurgeManager", 19 | "1592777662 DEBUG com.codingmaniacs.core.TransactionContext", 20 | }; 21 | 22 | String[] result = CollectionChallenges.sortLogs(myLogInfo); 23 | assertArrayEquals("The list should be ordered considering the level precedence", expected, result); 24 | } 25 | 26 | @Test 27 | public void sortLogListByLogLevelMixed() { 28 | String[] myLogInfo = { 29 | "1592777662 DEBUG com.codingmaniacs.core.TransactionContext", 30 | "1592777661 INFO com.codingmaniacs.services.account.PurgeManager", 31 | "1592777663 WARNING com.codingmaniacs.core.tc.Connector", 32 | "1592777112 DEBUG com.codingmaniacs.core.Transaction", 33 | "1592777000 INFO com.codingmaniacs.services.account.PurgeIterator", 34 | "1592777345 INFO com.codingmaniacs.services.account.PurgeApp"}; 35 | 36 | String[] expected = { 37 | "1592777663 WARNING com.codingmaniacs.core.tc.Connector", 38 | "1592777000 INFO com.codingmaniacs.services.account.PurgeIterator", 39 | "1592777345 INFO com.codingmaniacs.services.account.PurgeApp", 40 | "1592777661 INFO com.codingmaniacs.services.account.PurgeManager", 41 | "1592777112 DEBUG com.codingmaniacs.core.Transaction", 42 | "1592777662 DEBUG com.codingmaniacs.core.TransactionContext", 43 | }; 44 | 45 | String[] result = CollectionChallenges.sortLogs(myLogInfo); 46 | assertArrayEquals("The list should be ordered considering the level precedence", expected, result); 47 | } 48 | 49 | @Test 50 | public void sortLogListByLogLevelMixedLong() { 51 | final String[] myLogInfo = { 52 | "1592777662 DEBUG com.codingmaniacs.core.TransactionContext", 53 | "1592777661 INFO com.codingmaniacs.services.account.PurgeManager", 54 | "1592777663 WARNING com.codingmaniacs.core.tc.Connector", 55 | "1592777112 DEBUG com.codingmaniacs.core.Transaction", 56 | "1592777000 INFO com.codingmaniacs.services.account.PurgeIterator", 57 | "1592777345 INFO com.codingmaniacs.services.account.PurgeApp", 58 | "1592777245 WARNING com.codingmaniacs.core.TransactionManager", 59 | "1592777350 INFO com.codingmaniacs.core.lab.Factory", 60 | "1592777880 WARNING com.codingmaniacs.services.account.Iterator", 61 | "1592777320 INFO com.codingmaniacs.core.TransactionContext", 62 | "1592777224 DEBUG com.codingmaniacs.core.context.Scheduler", 63 | "1592777450 DEBUG com.codingmaniacs.services.account.PurgeApp", 64 | "1592777333 WARNING com.codingmaniacs.core.TransactionManager", 65 | "1592777665 INFO com.codingmaniacs.services.account.PurgeManager", 66 | "1592777543 WARNING com.codingmaniacs.services.account.Integrator"}; 67 | String[] expected = { 68 | "1592777245 WARNING com.codingmaniacs.core.TransactionManager", 69 | "1592777333 WARNING com.codingmaniacs.core.TransactionManager", 70 | "1592777543 WARNING com.codingmaniacs.services.account.Integrator", 71 | "1592777663 WARNING com.codingmaniacs.core.tc.Connector", 72 | "1592777880 WARNING com.codingmaniacs.services.account.Iterator", 73 | "1592777000 INFO com.codingmaniacs.services.account.PurgeIterator", 74 | "1592777320 INFO com.codingmaniacs.core.TransactionContext", 75 | "1592777345 INFO com.codingmaniacs.services.account.PurgeApp", 76 | "1592777350 INFO com.codingmaniacs.core.lab.Factory", 77 | "1592777661 INFO com.codingmaniacs.services.account.PurgeManager", 78 | "1592777665 INFO com.codingmaniacs.services.account.PurgeManager", 79 | "1592777112 DEBUG com.codingmaniacs.core.Transaction", 80 | "1592777224 DEBUG com.codingmaniacs.core.context.Scheduler", 81 | "1592777450 DEBUG com.codingmaniacs.services.account.PurgeApp", 82 | "1592777662 DEBUG com.codingmaniacs.core.TransactionContext", 83 | }; 84 | 85 | 86 | String[] result = CollectionChallenges.sortLogs(myLogInfo); 87 | assertArrayEquals("The list should be ordered considering the level precedence", expected, result); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/com/codingmaniacs/others/StringChallengesTests.java: -------------------------------------------------------------------------------- 1 | package com.codingmaniacs.others; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertArrayEquals; 6 | import static org.junit.Assert.assertEquals; 7 | 8 | public class StringChallengesTests { 9 | 10 | @Test 11 | public void reverseRecursiveEmptyString() { 12 | String str = ""; 13 | String expected = ""; 14 | 15 | String result = StringChallenges.reverse(str); 16 | assertEquals("The reverse of an empty string is the same empty string", expected, result); 17 | } 18 | 19 | @Test 20 | public void reverseRecursiveSingleCharString() { 21 | String str = "a"; 22 | String expected = "a"; 23 | 24 | String result = StringChallenges.reverse(str); 25 | assertEquals("The reverse of a single char is the same char", expected, result); 26 | } 27 | 28 | @Test 29 | public void reverseRecursiveAB() { 30 | String str = "ab"; 31 | String expected = "ba"; 32 | 33 | String result = StringChallenges.reverse(str); 34 | assertEquals("The reverse of ab is ba", expected, result); 35 | } 36 | 37 | @Test 38 | public void reverseRecursiveMultipleRepetitions() { 39 | String str = "aaa"; 40 | String expected = "aaa"; 41 | 42 | String result = StringChallenges.reverse(str); 43 | assertEquals("The reverse of aaa is aaa", expected, result); 44 | } 45 | 46 | @Test 47 | public void reverseRecursiveComplexString() { 48 | String str = "longer and complex words"; 49 | String expected = "sdrow xelpmoc dna regnol"; 50 | 51 | String result = StringChallenges.reverse(str); 52 | assertEquals("The reverse of an empty string is the same empty string", expected, result); 53 | } 54 | 55 | @Test 56 | public void findFirstOccurrenceOfCharEmptyString() { 57 | String str = ""; 58 | String expected = ""; 59 | 60 | String result = StringChallenges.findFirstRepeatedChar(str); 61 | assertEquals("There's not repeated char on an empty string", expected, result); 62 | } 63 | 64 | @Test 65 | public void findFirstOccurrenceOfCharNullString() { 66 | 67 | String expected = ""; 68 | 69 | String result = StringChallenges.findFirstRepeatedChar(null); 70 | assertEquals("There's not repeated char on an null string", expected, result); 71 | } 72 | 73 | @Test 74 | public void findFirstOccurrenceOfCharOneElementString() { 75 | String str = "a"; 76 | String expected = ""; 77 | 78 | String result = StringChallenges.findFirstRepeatedChar(str); 79 | assertEquals("Since there's no duplicates it should return \"\"", expected, result); 80 | } 81 | 82 | @Test 83 | public void findFirstOccurrenceOfChaTwoRepeatedElementString() { 84 | String str = "aa"; 85 | String expected = "a"; 86 | 87 | String result = StringChallenges.findFirstRepeatedChar(str); 88 | assertEquals("Since the letter a is repeated once, that's the solution", expected, result); 89 | } 90 | 91 | @Test 92 | public void findFirstOccurrenceOfCharLongerString() { 93 | String str = "bdcdba"; 94 | String expected = "d"; 95 | 96 | String result = StringChallenges.findFirstRepeatedChar(str); 97 | assertEquals("Since the letter a is repeated once, that's the solution", expected, result); 98 | } 99 | 100 | @Test 101 | public void transformStringToURLNoSpaces() { 102 | String str = "helloworld"; 103 | int trueLength = 10; 104 | String expected = "helloworld"; 105 | 106 | String result = StringChallenges.URLlify(str, trueLength); 107 | assertEquals("We don't have spaces to parse so we expect the same string", expected, result); 108 | } 109 | 110 | @Test 111 | public void transformStringToURLTwoSpaces() { 112 | String str = "hello world! example "; 113 | int trueLength = 20; 114 | String expected = "hello%20world!%20example"; 115 | 116 | String result = StringChallenges.URLlify(str, trueLength); 117 | assertEquals(expected, result); 118 | } 119 | 120 | @Test 121 | public void transformStringToURLFourSpaces() { 122 | String str = "this is my friendly command "; 123 | int trueLength = 27; 124 | String expected = "this%20is%20my%20friendly%20command"; 125 | 126 | String result = StringChallenges.URLlify(str, trueLength); 127 | assertEquals(expected, result); 128 | } 129 | 130 | @Test 131 | public void checkBalancedBracesYES() { 132 | String str = "(){}[]"; 133 | String expected = "YES"; 134 | 135 | String result = StringChallenges.balancedBraces(str); 136 | assertEquals(expected, result); 137 | } 138 | 139 | @Test 140 | public void checkBalancedBracesNO() { 141 | String str = "{[}]}"; 142 | String expected = "NO"; 143 | 144 | String result = StringChallenges.balancedBraces(str); 145 | assertEquals(expected, result); 146 | } 147 | 148 | @Test 149 | public void checkBalancedBracesNested() { 150 | String str = "[](){()}"; 151 | String expected = "YES"; 152 | 153 | String result = StringChallenges.balancedBraces(str); 154 | assertEquals(expected, result); 155 | } 156 | 157 | @Test 158 | public void checkBalancedBracesMultiple() { 159 | 160 | String[] str = new String[]{"{[}]}", "(){}[]"}; 161 | String[] expected = new String[]{"NO", "YES"}; 162 | 163 | String[] result = StringChallenges.balancedBraces(str); 164 | assertArrayEquals(expected, result); 165 | } 166 | 167 | } 168 | --------------------------------------------------------------------------------