├── haskell
├── 03-logic-and-codes
│ ├── P47.hs
│ ├── P48.hs
│ ├── P49.hs
│ └── P46.hs
├── 01-lists
│ ├── P06.hs
│ ├── P14.hs
│ ├── P17.hs
│ ├── P22.hs
│ ├── P15.hs
│ ├── P18.hs
│ ├── P10.hs
│ ├── P25.hs
│ ├── P01.hs
│ ├── P16.hs
│ ├── P20.hs
│ ├── P21.hs
│ ├── P07.hs
│ ├── P19.hs
│ ├── P24.hs
│ ├── P13.hs
│ ├── P04.hs
│ ├── P03.hs
│ ├── P05.hs
│ ├── P09.hs
│ ├── P08.hs
│ ├── P12.hs
│ ├── P23.hs
│ ├── P26.hs
│ ├── P28.hs
│ ├── P02.hs
│ ├── P27.hs
│ └── P11.hs
└── 02-arithmetic
│ ├── P34.hs
│ ├── P39.hs
│ ├── P38.hs
│ ├── P41.hs
│ ├── P40.hs
│ ├── P37.hs
│ ├── P31.hs
│ ├── P33.hs
│ ├── P32.hs
│ ├── P36.hs
│ └── P35.hs
├── scala
├── project
│ ├── plugins.sbt
│ └── build.properties
├── build.sbt
├── src
│ ├── main
│ │ └── scala
│ │ │ └── com
│ │ │ └── shekhargulati
│ │ │ ├── ninetynine_problems
│ │ │ ├── _02_arithmetic
│ │ │ │ ├── P41.scala
│ │ │ │ ├── P38.scala
│ │ │ │ ├── P40.scala
│ │ │ │ ├── P33.scala
│ │ │ │ ├── P37.scala
│ │ │ │ ├── P32.scala
│ │ │ │ ├── P36.scala
│ │ │ │ ├── P39.scala
│ │ │ │ ├── P34.scala
│ │ │ │ ├── P31.scala
│ │ │ │ └── P35.scala
│ │ │ ├── _03_logic_and_codes
│ │ │ │ ├── P47.scala
│ │ │ │ ├── P48.scala
│ │ │ │ ├── P50.scala
│ │ │ │ ├── P49.scala
│ │ │ │ └── P46.scala
│ │ │ ├── _01_lists
│ │ │ │ ├── P25.scala
│ │ │ │ ├── P24.scala
│ │ │ │ ├── P06.scala
│ │ │ │ ├── P10.scala
│ │ │ │ ├── P02.scala
│ │ │ │ ├── P17.scala
│ │ │ │ ├── P05.scala
│ │ │ │ ├── P04.scala
│ │ │ │ ├── P03.scala
│ │ │ │ ├── P01.scala
│ │ │ │ ├── P14.scala
│ │ │ │ ├── P22.scala
│ │ │ │ ├── P20.scala
│ │ │ │ ├── P26.scala
│ │ │ │ ├── P12.scala
│ │ │ │ ├── P18.scala
│ │ │ │ ├── P15.scala
│ │ │ │ ├── P11.scala
│ │ │ │ ├── P23.scala
│ │ │ │ ├── P07.scala
│ │ │ │ ├── P19.scala
│ │ │ │ ├── P16.scala
│ │ │ │ ├── P28.scala
│ │ │ │ ├── P13.scala
│ │ │ │ ├── P21.scala
│ │ │ │ └── P08.scala
│ │ │ └── _04_binary_trees
│ │ │ │ ├── BinaryTree.scala
│ │ │ │ └── P51.scala
│ │ │ ├── tadm
│ │ │ └── ch03
│ │ │ │ └── Problem3_2.scala
│ │ │ └── random
│ │ │ ├── RandomProblem01.scala
│ │ │ └── MovieScheduler.scala
│ └── test
│ │ └── scala
│ │ └── com
│ │ └── shekhargulati
│ │ └── ninetynine_problems
│ │ ├── _02_arithmetic
│ │ ├── P37Test.scala
│ │ ├── P38Test.scala
│ │ ├── P41Test.scala
│ │ ├── P40Test.scala
│ │ ├── P33Test.scala
│ │ ├── P39Test.scala
│ │ ├── P32Test.scala
│ │ ├── P35Test.scala
│ │ ├── P36Test.scala
│ │ ├── P31Test.scala
│ │ └── P34Test.scala
│ │ ├── _03_logic_and_codes
│ │ ├── P50Test.scala
│ │ ├── P49Test.scala
│ │ └── P46Test.scala
│ │ ├── _01_lists
│ │ ├── P24Test.scala
│ │ ├── P25Test.scala
│ │ ├── P12Test.scala
│ │ ├── P05Test.scala
│ │ ├── P01Test.scala
│ │ ├── P22Test.scala
│ │ ├── P11Test.scala
│ │ ├── P23Test.scala
│ │ ├── P18Test.scala
│ │ ├── P10Test.scala
│ │ ├── P14Test.scala
│ │ ├── P15Test.scala
│ │ ├── P06Test.scala
│ │ ├── P20Test.scala
│ │ ├── P04Test.scala
│ │ ├── P02Test.scala
│ │ ├── P26Test.scala
│ │ ├── P13Test.scala
│ │ ├── P28Test.scala
│ │ ├── P03Test.scala
│ │ └── P17Test.scala
│ │ └── _04_binary_trees
│ │ └── P51Test.scala
└── .gitignore
├── java8
├── settings.gradle
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── .mvn
│ └── wrapper
│ │ └── maven-wrapper.properties
├── src
│ ├── main
│ │ └── java
│ │ │ └── com
│ │ │ └── shekhargulati
│ │ │ ├── ninetynine_problems
│ │ │ ├── _02_arithmetic
│ │ │ │ ├── P41.java
│ │ │ │ ├── P38.java
│ │ │ │ ├── P39.java
│ │ │ │ ├── P31.java
│ │ │ │ ├── P40.java
│ │ │ │ ├── P37.java
│ │ │ │ ├── P32.java
│ │ │ │ ├── P33.java
│ │ │ │ ├── P36.java
│ │ │ │ ├── P34.java
│ │ │ │ └── P35.java
│ │ │ ├── _03_logic_and_codes
│ │ │ │ ├── P47.java
│ │ │ │ ├── P48.java
│ │ │ │ ├── P49.java
│ │ │ │ └── P46.java
│ │ │ └── _01_lists
│ │ │ │ ├── P18.java
│ │ │ │ ├── P25.java
│ │ │ │ ├── P24.java
│ │ │ │ ├── P22.java
│ │ │ │ ├── P10.java
│ │ │ │ ├── P19.java
│ │ │ │ ├── P14.java
│ │ │ │ ├── P15.java
│ │ │ │ ├── CollectionUtils.java
│ │ │ │ ├── P06.java
│ │ │ │ ├── P17.java
│ │ │ │ ├── P11.java
│ │ │ │ ├── P16.java
│ │ │ │ ├── P03.java
│ │ │ │ ├── P04.java
│ │ │ │ ├── P02.java
│ │ │ │ ├── P12.java
│ │ │ │ ├── P13.java
│ │ │ │ ├── P08.java
│ │ │ │ ├── P20.java
│ │ │ │ ├── P21.java
│ │ │ │ ├── P09.java
│ │ │ │ ├── P07.java
│ │ │ │ ├── P26.java
│ │ │ │ ├── P23.java
│ │ │ │ ├── P01.java
│ │ │ │ ├── P28.java
│ │ │ │ └── P05.java
│ │ │ ├── tadm
│ │ │ ├── ch04
│ │ │ │ ├── excercises
│ │ │ │ │ ├── Problem4_6.java
│ │ │ │ │ ├── Problem4_5.java
│ │ │ │ │ ├── Problem4_2.java
│ │ │ │ │ └── Problem4_1.java
│ │ │ │ └── examples
│ │ │ │ │ ├── SelectionSort.java
│ │ │ │ │ └── MergeSort.java
│ │ │ └── ch03
│ │ │ │ ├── Problem3_4.java
│ │ │ │ └── Problem3_2.java
│ │ │ ├── leetcode
│ │ │ └── algorithms
│ │ │ │ └── Problem03.java
│ │ │ ├── random
│ │ │ ├── algebra
│ │ │ │ └── RandomProblem005.java
│ │ │ ├── tree
│ │ │ │ └── Tree.java
│ │ │ ├── RandomProblem002.java
│ │ │ ├── RandomProblem004.java
│ │ │ └── RandomProblem003.java
│ │ │ ├── IntPair.java
│ │ │ ├── codegolf
│ │ │ └── AcronymMaker.java
│ │ │ └── fortytwo_problems
│ │ │ └── Problem01.java
│ └── test
│ │ └── java
│ │ └── com
│ │ └── shekhargulati
│ │ ├── random
│ │ ├── algebra
│ │ │ └── RandomProblem005Test.java
│ │ ├── RandomProblem003Test.java
│ │ ├── RandomProblem004Test.java
│ │ └── RandomProblem002Test.java
│ │ ├── ninetynine_problems
│ │ ├── _02_arithmetic
│ │ │ ├── P38Test.java
│ │ │ ├── P37Test.java
│ │ │ ├── P39Test.java
│ │ │ ├── P40Test.java
│ │ │ ├── P31Test.java
│ │ │ ├── P41Test.java
│ │ │ ├── P32Test.java
│ │ │ ├── P33Test.java
│ │ │ ├── P35Test.java
│ │ │ └── P34Test.java
│ │ ├── _01_lists
│ │ │ ├── P24Test.java
│ │ │ ├── P22Test.java
│ │ │ ├── P14Test.java
│ │ │ ├── P15Test.java
│ │ │ ├── P18Test.java
│ │ │ ├── P17Test.java
│ │ │ ├── P12Test.java
│ │ │ ├── P25Test.java
│ │ │ ├── P20Test.java
│ │ │ ├── P06Test.java
│ │ │ ├── P01Test.java
│ │ │ ├── P08Test.java
│ │ │ ├── P04Test.java
│ │ │ ├── P03Test.java
│ │ │ ├── P11Test.java
│ │ │ ├── P19Test.java
│ │ │ ├── P05Test.java
│ │ │ ├── P10Test.java
│ │ │ ├── P13Test.java
│ │ │ ├── P23Test.java
│ │ │ ├── P02Test.java
│ │ │ ├── P26Test.java
│ │ │ ├── P16Test.java
│ │ │ └── P28Test.java
│ │ └── _03_logic_and_codes
│ │ │ ├── P46Test.java
│ │ │ └── P49Test.java
│ │ ├── tadm
│ │ ├── ch04
│ │ │ ├── excercises
│ │ │ │ ├── Problem4_6Test.java
│ │ │ │ ├── Problem4_5Test.java
│ │ │ │ ├── Problem4_1Test.java
│ │ │ │ └── Problem4_2Test.java
│ │ │ └── examples
│ │ │ │ └── SelectionSortTest.java
│ │ └── ch03
│ │ │ └── Problem3_2Test.java
│ │ ├── fortytwo_problems
│ │ └── Problem01Test.java
│ │ ├── leetcode
│ │ ├── Problem03Test.java
│ │ └── algorithms
│ │ │ └── Problem05Test.java
│ │ └── codegolf
│ │ └── AcronymMakerTest.java
├── build.gradle
├── pom.xml
└── .gitignore
├── LICENSE
└── README.md
/haskell/03-logic-and-codes/P47.hs:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/haskell/03-logic-and-codes/P48.hs:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/scala/project/plugins.sbt:
--------------------------------------------------------------------------------
1 | logLevel := Level.Warn
--------------------------------------------------------------------------------
/scala/project/build.properties:
--------------------------------------------------------------------------------
1 | sbt.version = 0.13.8
--------------------------------------------------------------------------------
/java8/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = '99-problems-java8'
2 |
3 |
--------------------------------------------------------------------------------
/haskell/01-lists/P06.hs:
--------------------------------------------------------------------------------
1 | isPalindrome :: Eq a => [a] -> Bool
2 | isPalindrome list = (list == (reverse list))
3 |
--------------------------------------------------------------------------------
/java8/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/biubiu/99-problems/master/java8/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/haskell/01-lists/P14.hs:
--------------------------------------------------------------------------------
1 | -- Duplicate the elements of a list
2 |
3 | duplicate :: [a] -> [a]
4 | duplicate list = concatMap (\x -> [x,x]) list
5 |
--------------------------------------------------------------------------------
/java8/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P34.hs:
--------------------------------------------------------------------------------
1 | module P34 where
2 | import P31
3 |
4 | primeNumbers :: [Int] -> [Int]
5 | primeNumbers range = filter (\number -> isPrime number) range
6 |
--------------------------------------------------------------------------------
/haskell/01-lists/P17.hs:
--------------------------------------------------------------------------------
1 | -- (*) Split a list into two parts; the length of the first part is given
2 |
3 | split :: [a] -> Int -> ([a],[a])
4 | split list n = splitAt n list
5 |
--------------------------------------------------------------------------------
/haskell/01-lists/P22.hs:
--------------------------------------------------------------------------------
1 | module P22 where
2 | -- (*) Create a list containing all integers within a given range
3 |
4 | range :: Int -> Int -> [Int]
5 | range start end = [start..end]
6 |
--------------------------------------------------------------------------------
/scala/build.sbt:
--------------------------------------------------------------------------------
1 | name := "99-problems-scala"
2 |
3 | version := "1.0"
4 |
5 | scalaVersion := "2.11.7"
6 |
7 | libraryDependencies += "org.scalatest" % "scalatest_2.11" % "2.2.4" % "test"
--------------------------------------------------------------------------------
/haskell/01-lists/P15.hs:
--------------------------------------------------------------------------------
1 | -- (**) Duplicate the elements of a list a given number of times
2 |
3 | duplicate :: [a] -> Int -> [a]
4 | duplicate list n = concatMap (\x -> replicate n x) list
5 |
--------------------------------------------------------------------------------
/haskell/01-lists/P18.hs:
--------------------------------------------------------------------------------
1 | -- (**) Extract a slice from a list
2 |
3 | slice :: [a] -> Int -> Int -> [a]
4 | slice list start end = fst (splitAt (end-start) (snd (splitAt (start-1) list)))
5 |
--------------------------------------------------------------------------------
/haskell/01-lists/P10.hs:
--------------------------------------------------------------------------------
1 | module P10 where
2 | import P09
3 |
4 | -- Run-length encoding of a list
5 | encode :: Eq a => [a] -> [(Int,a)]
6 | encode xs = map (\ll -> (length ll, head ll)) (pack xs)
7 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P39.hs:
--------------------------------------------------------------------------------
1 | import P38
2 | -- 2.09 (**) Calculate Euler's totient function phi(m).
3 |
4 | totient_phi :: Int -> Int
5 | totient_phi m = length (filter (\r -> (coprime r m)) [1..m])
6 |
--------------------------------------------------------------------------------
/haskell/01-lists/P25.hs:
--------------------------------------------------------------------------------
1 | import P23
2 | -- (*) Generate a random permutation of the elements of a list
3 |
4 | import System.Random
5 |
6 | randomPermutation list = sequence (randomSelect list (length list))
7 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P38.hs:
--------------------------------------------------------------------------------
1 | module P38 where
2 | -- (*) Determine whether two positive integer numbers are coprime.
3 |
4 | coprime :: Int -> Int -> Bool
5 | coprime first second = (gcd first second) == 1
6 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P41.hs:
--------------------------------------------------------------------------------
1 | -- (*) Compare the two methods of calculating Euler's totient function.
2 | -- There is no code required to be written. Just run the solutions in P39 and P40 and compare timing.
3 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P40.hs:
--------------------------------------------------------------------------------
1 | import P33
2 | -- (**) Calculate Euler's totient function phi(m) (2).
3 |
4 | phi :: Int -> Int
5 | phi m = product (map (\t -> ((fst t) - 1)*((fst t) ^ ((snd t) - 1))) (primeFactorsMult m))
6 |
--------------------------------------------------------------------------------
/haskell/01-lists/P01.hs:
--------------------------------------------------------------------------------
1 | last1 :: [a] -> a
2 | last1 xs = last xs
3 |
4 | lastRecursive :: [a] -> a
5 | lastRecursive [] = error "No last element found in empty list"
6 | lastRecursive [x] = x
7 | lastRecursive (x:xs) = lastRecursive xs
8 |
--------------------------------------------------------------------------------
/haskell/01-lists/P16.hs:
--------------------------------------------------------------------------------
1 | -- (**) Drop every N'th element from a list
2 | dropEveryNth :: [a] -> Int -> [a]
3 | dropEveryNth list 0 = list
4 | dropEveryNth list n = map (\x -> snd x) (filter (\x -> (fst x) `mod` 3 /= 0) (zip [1..] list))
5 |
--------------------------------------------------------------------------------
/haskell/03-logic-and-codes/P49.hs:
--------------------------------------------------------------------------------
1 | -- (**) Gray code.
2 |
3 | gray :: Int -> [String]
4 | gray 1 = ["0","1"]
5 | gray n = (map (\s -> "0"++s) original) ++ (map (\s -> "1"++s) (reverse original))
6 | where original = gray (n-1)
7 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P37.hs:
--------------------------------------------------------------------------------
1 | -- (**) Determine the greatest common divisor of two positive integer numbers.
2 |
3 | gcd' :: Int -> Int -> Int
4 | gcd' a 0 = a
5 | gcd' 0 b = b
6 | gcd' a b | a > b = gcd' (a-b) b
7 | gcd' a b = gcd' a (b-a)
8 |
--------------------------------------------------------------------------------
/haskell/01-lists/P20.hs:
--------------------------------------------------------------------------------
1 | module P20 where
2 | -- (*) Remove the K'th element from a list
3 | removeAt :: [a] -> Int -> ([a],a)
4 | removeAt list k = let (first, second) = splitAt k list
5 | in ((init first) ++ second, last first)
6 |
--------------------------------------------------------------------------------
/haskell/01-lists/P21.hs:
--------------------------------------------------------------------------------
1 | -- (*) Insert an element at a given position into a list
2 |
3 | insertAt :: [a] -> Int -> a -> [a]
4 | insertAt list pos a = let (first, second) = splitAt (pos - 1) list
5 | in (first ++ [a]) ++ second
6 |
--------------------------------------------------------------------------------
/haskell/01-lists/P07.hs:
--------------------------------------------------------------------------------
1 | data NestedList a = Elem a | List [NestedList a]
2 |
3 | -- flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])
4 | flatten :: NestedList a -> [a]
5 | flatten (Elem x) = [x]
6 | flatten (List x) = concatMap flatten x
7 |
--------------------------------------------------------------------------------
/haskell/01-lists/P19.hs:
--------------------------------------------------------------------------------
1 | -- (**) Rotate a list N places to the left
2 |
3 | rotate :: [a] -> Int -> [a]
4 | rotate list n
5 | | n < 0 = rotate list ((length list) + n)
6 | |otherwise = let (first, second) = splitAt n list
7 | in second ++ first
8 |
--------------------------------------------------------------------------------
/haskell/01-lists/P24.hs:
--------------------------------------------------------------------------------
1 | import P22
2 | import P23
3 | -- (*) Lotto: Draw N different random numbers from the set 1..M
4 |
5 | import System.Random
6 |
7 | randomSelect_lotto :: Int -> (Int, Int) -> IO [Int]
8 | randomSelect_lotto n (start, end) = sequence (randomSelect (range start end) n)
9 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P31.hs:
--------------------------------------------------------------------------------
1 | module P31 where
2 | -- (**) Determine whether a given integer number is prime.
3 |
4 | isPrime :: Int -> Bool
5 | isPrime number | number < 2 = error "number should b greater than 2"
6 | isPrime number = not (any (\n -> number `mod` n == 0) [2..(number `div` 2)])
7 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P41.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | /**
4 | * (*) Compare the two methods of calculating Euler's totient function.
5 | * Check P41Test
6 | */
7 | public class P41 {
8 | }
9 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P33.hs:
--------------------------------------------------------------------------------
1 | module P33 where
2 | import P32
3 | import P10
4 | import Data.Tuple
5 | -- (**) Determine the prime factors of a given positive integer (2).
6 |
7 | primeFactorsMult :: Int -> [(Int, Int)]
8 | primeFactorsMult number = map (\t -> swap t) (encode (primeFactors number))
9 |
--------------------------------------------------------------------------------
/java8/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Nov 22 11:37:27 IST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-bin.zip
7 |
--------------------------------------------------------------------------------
/haskell/01-lists/P13.hs:
--------------------------------------------------------------------------------
1 | -- (**) Run-length encoding of a list (direct solution)
2 |
3 | encode_direct :: Eq a => [a] -> [(Int, a)]
4 | encode_direct [] = []
5 | encode_direct (x:xs) = let (first, remaining) = span (== x) xs
6 | in ((length first) + 1, x) : encode_direct remaining
7 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P41.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | /**
4 | * (*) Compare the two methods of calculating Euler's totient function.
5 | * Check P41Test.
6 | */
7 | object P41 {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P47.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes;
2 |
3 | /**
4 | * 3.02 (*) Truth tables for logical expressions (2).
5 | *
6 | * Skipping this problem for now.
7 | */
8 | public class P47 {
9 | }
10 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P48.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes;
2 |
3 | /**
4 | * 3.03 (**) Truth tables for logical expressions (3).
5 | *
6 | * Skipping this problem for now.
7 | */
8 | public class P48 {
9 | }
10 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P47.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes
2 |
3 | /**
4 | * 3.02 (*) Truth tables for logical expressions (2).
5 | *
6 | * Skipping this problem for now.
7 | */
8 | object P47 {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P48.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes
2 |
3 | /**
4 | * 3.03 (**) Truth tables for logical expressions (3).
5 | *
6 | * Skipping this problem for now.
7 | */
8 | object P48 {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/haskell/01-lists/P04.hs:
--------------------------------------------------------------------------------
1 | length' :: [a] -> Int
2 | length' list = length list
3 |
4 | lengthRecursive :: [a] -> Int
5 | lengthRecursive [] = 0
6 | lengthRecursive list = lengthRecursive' list 0
7 |
8 | lengthRecursive' :: [a] -> Int -> Int
9 | lengthRecursive' [] n = n
10 | lengthRecursive' (x:xs) n = lengthRecursive' xs (n+1)
11 |
--------------------------------------------------------------------------------
/haskell/01-lists/P03.hs:
--------------------------------------------------------------------------------
1 | -- using built-in function
2 | kth :: [a] -> Int -> a
3 | kth [] k = error "List is empty"
4 | kth list k = list !! k
5 |
6 | -- using recursive approach
7 | kthRecursive :: [a] -> Int -> a
8 | kthRecursive [] k = error "List is empty"
9 | kthRecursive (x:xs) 0 = x
10 | kthRecursive (x:xs) k = kthRecursive xs (k-1)
11 |
--------------------------------------------------------------------------------
/haskell/01-lists/P05.hs:
--------------------------------------------------------------------------------
1 | -- built-in function
2 | reverse' :: [a] -> [a]
3 | reverse' list = reverse list
4 |
5 | -- using recursion
6 |
7 | reverseRecursive :: [a] -> [a]
8 | reverseRecursive list = reverseRecursive' list []
9 |
10 | reverseRecursive' [] dest = dest
11 | reverseRecursive' (x:xs) dest = reverseRecursive' xs ([x] ++ dest)
12 |
--------------------------------------------------------------------------------
/haskell/01-lists/P09.hs:
--------------------------------------------------------------------------------
1 | module P09 where
2 | -- Pack consecutive duplicates of list elements into sublists.
3 | -- If a list contains repeated elements they should be placed in separate sublists.
4 | pack :: Eq a => [a] -> [[a]]
5 | pack [] = []
6 | pack (x:xs) = let (first, remaining) = span (== x) xs
7 | in (x:first) : pack remaining
8 |
--------------------------------------------------------------------------------
/java8/build.gradle:
--------------------------------------------------------------------------------
1 | group 'com.shekhargulati'
2 | version '1.0-SNAPSHOT'
3 |
4 | apply plugin: 'java'
5 |
6 | sourceCompatibility = 1.8
7 |
8 | repositories {
9 | mavenCentral()
10 | }
11 |
12 | dependencies {
13 | testCompile group: 'junit', name: 'junit', version: '4.12'
14 | testCompile 'org.hamcrest:hamcrest-all:1.3'
15 | }
16 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P25.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (*) Generate a random permutation of the elements of a list.
5 | */
6 | object P25 {
7 |
8 | def randomPermutation[T](list: List[T]): List[T] = P23.randomSelectR(list, list.size)
9 | }
10 |
--------------------------------------------------------------------------------
/haskell/01-lists/P08.hs:
--------------------------------------------------------------------------------
1 | compress :: Eq a => [a] -> [a]
2 | compress [] = []
3 | compress (x:xs) = x : compress (dropWhile (== x) xs)
4 |
5 | compress' :: Eq a => [a] -> [a]
6 | compress' list = compressR list []
7 |
8 | compressR :: Eq a => [a] -> [a] -> [a]
9 | compressR [] r = r
10 | compressR (x:xs) r = compressR (dropWhile (== x) xs) (r ++ [x])
11 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P38.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | /**
4 | * (*) Determine whether two positive integer numbers are coprime.
5 | */
6 | object P38 {
7 |
8 | def coprime(first: Int, second: Int): Boolean = P37.gcd(first, second) == 1
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/haskell/03-logic-and-codes/P46.hs:
--------------------------------------------------------------------------------
1 | -- 3.01 (**) Truth tables for logical expressions.
2 |
3 | import Text.Printf
4 |
5 | --table :: (Bool -> Bool -> Bool) -> [String]
6 | table fx = [(a, b, (fx a b)) | a <- [True,False], b <- [True,False]]
7 |
8 | and' :: Bool -> Bool -> Bool
9 | and' a b = a && b
10 |
11 | or' :: Bool -> Bool -> Bool
12 | or' a b = a || b
13 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P24.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (*) Lotto: Draw N different random numbers from the set 1..M
5 | */
6 | object P24 {
7 |
8 | def randomSelect(n: Int, range: (Int, Int)): List[Int] = P23.randomSelectR(P22.range(range._1, range._2), n)
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_04_binary_trees/BinaryTree.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._04_binary_trees
2 |
3 | /*
4 | A binary tree is either empty or it is composed of a root element and two successors,
5 | which are binary trees themselves.
6 | */
7 | case class BinaryTree[+T](x: T, left: BinaryTree[T], right: BinaryTree[T])
--------------------------------------------------------------------------------
/haskell/01-lists/P12.hs:
--------------------------------------------------------------------------------
1 | -- (**) Decode a run-length encoded list
2 |
3 | decode :: Eq a => [Either a (Int, a)] -> [a]
4 | decode list = _decode list []
5 |
6 | _decode :: Eq a => [Either a (Int, a)] -> [a] -> [a]
7 | _decode (Left x: xs) result = _decode xs (result ++ [x])
8 | _decode (Right (n,e): xs ) result = _decode xs (result ++ (take n (repeat e)))
9 | _decode [] result = result
10 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P38.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | /**
4 | * (*) Determine whether two positive integer numbers are coprime.
5 | */
6 | public class P38 {
7 |
8 | public static boolean coprime(int first, int second) {
9 | return P37.gcd(first, second) == 1;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P18.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * (**) Extract a slice from a list
7 | */
8 | public class P18 {
9 |
10 | public static List slice(List list, int start, int end) {
11 | return list.subList(start - 1, end);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P40.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | /**
4 | * (**) Calculate Euler's totient function phi(m) (2).
5 | */
6 | object P40 {
7 |
8 | def phi(m: Int): Int = {
9 | P33.primeFactorsMult(m).map { case (p1, m1) => (p1 - 1) * Math.pow(p1, m1 - 1) }.product.toInt
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/haskell/01-lists/P23.hs:
--------------------------------------------------------------------------------
1 | module P23 where
2 | import P20
3 |
4 | -- (**) Extract a given number of randomly selected elements from a list
5 |
6 | import System.Random (randomRIO)
7 |
8 | pick :: [a] -> IO a
9 | pick xs = randomRIO (0, length xs - 1) >>= return . (xs !!)
10 |
11 | randomSelect :: [a] -> Int -> [IO a]
12 | randomSelect xs 0 = []
13 | randomSelect xs n = [pick xs] ++ (randomSelect xs (n-1))
14 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_04_binary_trees/P51.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._04_binary_trees
2 |
3 | /**
4 | * (*) Check whether a given term represents a binary tree
5 | */
6 | object P51 {
7 |
8 | /*
9 | Our tree will only allow well formed trees so skipping this problem.
10 | */
11 | def isTree[T](tree: BinaryTree[T]): Boolean = true
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P25.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * (*) Generate a random permutation of the elements of a list.
7 | */
8 | public class P25 {
9 |
10 | public static List randomPermutation(List list) {
11 | return P23.randomSelectR(list, list.size());
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P39.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import java.util.stream.IntStream;
4 |
5 | /**
6 | * (**) Calculate Euler's totient function phi(m).
7 | */
8 | public class P39 {
9 |
10 | public static long phi(int m) {
11 | return IntStream.rangeClosed(1, m).filter(r -> P38.coprime(r, m)).count();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P24.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * (*) Lotto: Draw N different random numbers from the set 1..M
7 | */
8 | public class P24 {
9 |
10 | public static List randomSelect(int n, int start, int end) {
11 | return P23.randomSelect(P22.range(start, end), n);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/random/algebra/RandomProblem005Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random.algebra;
2 |
3 | import org.junit.Test;
4 |
5 | public class RandomProblem005Test {
6 |
7 | @Test
8 | public void shouldEvaluateAPolynomial() throws Exception {
9 | System.out.println(RandomProblem005.eval(10, 5, 2));
10 | System.out.println(RandomProblem005.evaluatePolynomialAt(10, 5, 2));
11 | }
12 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P37Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P37Test extends FunSpec with Matchers {
6 |
7 | describe("P37 Spec") {
8 | it("greatest common divisior of 36 and 63 is 9") {
9 | val result = P37.gcd(36, 63)
10 | result should be(9)
11 | }
12 | }
13 |
14 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P38Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P38Test extends FunSpec with Matchers {
6 |
7 | describe("P38 Spec") {
8 | it("35 and 64 are coprime") {
9 | val coprime: Boolean = P38.coprime(35, 64)
10 | coprime should be(true)
11 | }
12 | }
13 |
14 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P38Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertTrue;
6 |
7 | public class P38Test {
8 |
9 | @Test
10 | public void shouldSay35And64IsCoprime() throws Exception {
11 | boolean coprime = P38.coprime(35, 64);
12 | assertTrue(coprime);
13 | }
14 | }
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P32.hs:
--------------------------------------------------------------------------------
1 | module P32 where
2 | import P31
3 | -- (**) Determine the prime factors of a given positive integer.
4 |
5 | --primeFactors :: Int -> [Int]
6 | primeFactors number = concat (filter (\xs -> (length xs) > 0) [(factors number n) | n <- [2..(quot number 2)], isPrime n])
7 |
8 | -- factors :: Int -> Int -> [Int]
9 | factors number f
10 | | number `mod` f == 0 = f : (factors (quot number f) f)
11 | factors _ f = []
12 |
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P36.hs:
--------------------------------------------------------------------------------
1 | import P35
2 | -- (**) A list of Goldbach compositions.
3 |
4 | goldbach_list :: [Int] -> [(Int, [Int])]
5 | goldbach_list range = map (\even -> (even, (goldbach even))) (filter (\even -> even > 2) (filter (\n -> n `mod` 2 == 0) range))
6 |
7 |
8 | goldbach_list1 :: Int -> [Int] -> [(Int, [Int])]
9 | goldbach_list1 number range = filter (\t -> (((!!) (snd t) 0) > number) && (((!!) (snd t) 1) > number))(goldbach_list range)
10 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/tadm/ch04/excercises/Problem4_6Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.excercises;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertTrue;
6 |
7 | public class Problem4_6Test {
8 |
9 | @Test
10 | public void shouldFindAPair() throws Exception {
11 | boolean pair = Problem4_6.findPair(new int[]{4, 3, 7}, new int[]{3, 2, 1}, 5);
12 | assertTrue(pair);
13 | }
14 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P06.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * Find out whether a list is a palindrome
5 | */
6 | object P06 {
7 |
8 | def isPalindrome[T](list: List[T]): Boolean = {
9 | P05.reverse(list) == list
10 | }
11 |
12 | def isPalindrome_reverseRecursive[T](list: List[T]): Boolean = {
13 | P05.reverseRecursive(list) == list
14 | }
15 |
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P33.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import com.shekhargulati.ninetynine_problems._01_lists.P10
4 |
5 | /**
6 | * (**) Determine the prime factors of a given positive integer (2)
7 | */
8 | object P33 {
9 |
10 | def primeFactorsMult(number: Int): List[(Int, Int)] = P10.encode(P32.primeFactors(number)).map { case (t1, t2) => (t2, t1) }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P50Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P50Test extends FunSpec with Matchers {
6 |
7 | describe("P50Spec"){
8 | it("should generate huffman code"){
9 | val code = P50.huffman(List(("1", 5), ("2", 7), ("3", 10), ("4", 15), ("5", 20), ("6", 45)))
10 |
11 | }
12 | }
13 |
14 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P31.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import java.util.stream.LongStream;
4 |
5 | /**
6 | * (**) Determine whether a given integer number is prime.
7 | */
8 | public class P31 {
9 |
10 | public static boolean isPrime(long number) {
11 | return !LongStream.rangeClosed(2, Math.round(Math.sqrt(number))).anyMatch(n -> number % n == 0);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P10.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (*) Run-length encoding of a list.
5 | * {{{
6 | * encode(List("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"))
7 | * }}}
8 | */
9 | object P10 {
10 |
11 | def encode[T](list: List[T]): List[(Int, T)] = {
12 | P09.pack_span(list).map(l => (l.size, l.head))
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P37Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.CoreMatchers.equalTo;
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class P37Test {
9 |
10 | @Test
11 | public void gcdOf36And63Is9() throws Exception {
12 | int gcd = P37.gcd(36, 63);
13 | assertThat(gcd, equalTo(9));
14 | }
15 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P39Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.CoreMatchers.equalTo;
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class P39Test {
9 |
10 | @Test
11 | public void shouldSayPhiOf10Is4() throws Exception {
12 | long phi = P39.phi(10);
13 | assertThat(phi, equalTo(4L));
14 | }
15 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P37.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | /**
4 | * (**) Determine the greatest common divisor of two positive integer numbers.
5 | */
6 | object P37 {
7 |
8 | def gcd(first: Int, second: Int): Int = (first, second) match {
9 | case (0, b) => b
10 | case (a, 0) => a
11 | case (a, b) if a > b => gcd(a - b, b)
12 | case (a, b) => gcd(a, b - a)
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/haskell/01-lists/P26.hs:
--------------------------------------------------------------------------------
1 | module P26 where
2 | -- (**) Generate the combinations of K distinct objects chosen from the N elements of a list
3 |
4 | import Data.List
5 |
6 | combinations :: [a] -> Int -> [[a]]
7 | combinations list k = filter (\l -> length l == k) (subsequences list)
8 |
9 | combinations1 :: [a] -> Int -> [[a]]
10 | combinations1 [] _ = []
11 | combinations1 list 1 = map (\x -> [x]) list
12 | combinations1 (x:xs) k = (map (\l -> (x:l)) (combinations1 xs (k-1))) ++ (combinations1 xs k)
13 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/tadm/ch04/excercises/Problem4_5Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.excercises;
2 |
3 | import org.hamcrest.CoreMatchers;
4 | import org.junit.Test;
5 |
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class Problem4_5Test {
9 |
10 | @Test
11 | public void shouldFindMode() throws Exception {
12 | int mode = Problem4_5.mode(new int[]{4, 6, 6, 3, 3, 3, 2, 4, 3, 1});
13 | assertThat(mode, CoreMatchers.equalTo(3));
14 |
15 | }
16 | }
--------------------------------------------------------------------------------
/haskell/01-lists/P28.hs:
--------------------------------------------------------------------------------
1 | -- (**) Sorting a list of lists according to length of sublists
2 | import Data.Function (on)
3 | import Data.List (sortBy, groupBy)
4 | import Data.Ord (comparing)
5 |
6 | lsort :: [[a]] -> [[a]]
7 | lsort list = sortBy compareListLength list
8 | where compareListLength xs1 xs2 = length xs1 `compare` length xs2
9 |
10 | lfsort :: [[a]] -> [[a]]
11 | lfsort list = concat groups
12 | where groups = lsort (groupBy byLength (lsort list))
13 | byLength xs1 xs2 = (length xs1) == (length xs2)
14 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P22.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.List;
4 | import java.util.stream.IntStream;
5 |
6 | import static java.util.stream.Collectors.toList;
7 |
8 | /**
9 | * (*) Create a list containing all integers within a given range
10 | */
11 | public class P22 {
12 |
13 | public static List range(int start, int end) {
14 | return IntStream.rangeClosed(start, end).boxed().collect(toList());
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/tadm/ch04/examples/SelectionSortTest.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.examples;
2 |
3 | import org.hamcrest.CoreMatchers;
4 | import org.junit.Test;
5 |
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class SelectionSortTest {
9 |
10 | @Test
11 | public void shouldSortNumbersInAscendingOrder() throws Exception {
12 | int[] sortedArr = SelectionSort.sort(new int[]{2, 5, 1, 3, 4});
13 | assertThat(sortedArr, CoreMatchers.equalTo(new int[]{1, 2, 3, 4, 5}));
14 | }
15 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P02.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | object P02 {
4 |
5 | def secondLast[T](list: List[T]): T = list match {
6 | case x :: (_ :: Nil) => x
7 | case x :: xs => secondLast(xs)
8 | case _ => throw new NoSuchElementException("Can't find secondLast element from a list with less than 2 elements")
9 | }
10 |
11 | def secondLast1[T](list: List[T]): T = if (list.isEmpty) throw new NoSuchElementException else list.init.last
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P24Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P24Test extends FunSpec with Matchers {
6 |
7 | describe("P24 Spec") {
8 | it("should give 6 random number between 1 and 49") {
9 | val randomList: List[Int] = P24.randomSelect(6, (1, 49))
10 | randomList should have length 6
11 | println(randomList) // One possible output List(18, 47, 6, 43, 48, 38)
12 | }
13 | }
14 |
15 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P17.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (*) Split a list into two parts; the length of the first part is given.
5 | * {{{
6 | * split(List("a", "b", "c", "d", "e", "f", "g", "h", "i", "k"), 3)
7 | * }}}
8 | */
9 | object P17 {
10 |
11 | def split[T](list: List[T], n: Int): (List[T], List[T]) = list.splitAt(n)
12 |
13 | def split_take_drop[T](list: List[T], n: Int): (List[T], List[T]) = (list.take(n), list.drop(n))
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P41Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P41Test extends FunSpec with Matchers {
6 |
7 | describe("P41 Spec") {
8 | it("calculate phi of 10090 using P39 solution"){
9 | val p = P39.totient_phi(10090)
10 | p should be(4032)
11 | }
12 |
13 | it("calculate phi of 10090 using P40 solution"){
14 | val p = P40.phi(10090)
15 | p should be(4032)
16 | }
17 | }
18 |
19 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P10.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.AbstractMap.SimpleEntry;
4 | import java.util.List;
5 |
6 | import static java.util.stream.Collectors.toList;
7 |
8 | /**
9 | * (*) Run-length encoding of a list.
10 | */
11 | public class P10 {
12 |
13 | public static List> encode(List list) {
14 | return P09.pack(list).stream().map(l -> new SimpleEntry<>(l.size(), l.get(0))).collect(toList());
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P40.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | /**
4 | * (**) Calculate Euler's totient function phi(m) (2).
5 | */
6 | public class P40 {
7 |
8 | public static int phi(int m) {
9 | return P33.primeFactorsMult(m)
10 | .stream()
11 | .map(entry -> (entry.getKey() - 1) * Math.pow(entry.getKey(), entry.getValue() - 1))
12 | .mapToInt(Double::intValue)
13 | .reduce(1, (i1, i2) -> i1 * i2);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P05.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.annotation.tailrec
4 |
5 | /**
6 | * Reverse a list
7 | */
8 | object P05 {
9 |
10 | def reverse[T](list: List[T]): List[T] = list.reverse
11 |
12 | def reverseRecursive[T](list: List[T]): List[T] = {
13 | @tailrec
14 | def tail(src: List[T], dest: List[T]): List[T] = src match {
15 | case Nil => dest
16 | case x :: xs => tail(xs, x +: dest)
17 | }
18 | tail(list, List())
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P19.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | /**
7 | * (**) Rotate a list N places to the left
8 | */
9 | public class P19 {
10 |
11 | public static List rotate(List list, int n) {
12 | n = n < 0 ? list.size() + n : n;
13 | Map> split = P17.split(list, n);
14 | List result = split.get(false);
15 | result.addAll(split.get(true));
16 | return result;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P04.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * Find the number of elements of a list
5 | */
6 | object P04 {
7 |
8 | def length[T](list: List[T]): Int = list.size
9 |
10 | def length1[T](list: List[T]): Int = list.map(_ => 1).sum
11 |
12 | def lengthRecursive[T](list: List[T]): Int = {
13 | def rec(list: List[T], length: Int): Int = list match {
14 | case x :: xs => rec(xs, length + 1)
15 | case Nil => length
16 | }
17 | rec(list, 0)
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P25Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P25Test extends FunSpec with Matchers {
6 |
7 | describe("P25 Spec") {
8 | it("should generate random permutation of elements of a list") {
9 | val permutation: List[String] = P25.randomPermutation(List("a", "b", "c", "d", "e", "f"))
10 | permutation should have length 6
11 | permutation should contain theSameElementsAs List("a", "b", "c", "d", "e", "f")
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P40Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P40Test extends FunSpec with Matchers {
6 |
7 | describe("P40 Spec"){
8 | it("phi of 10 is 4"){
9 | val p = P40.phi(10)
10 | p should be(4)
11 | }
12 |
13 | it("phi of 9 is 6"){
14 | val p = P40.phi(9)
15 | p should be(6)
16 | }
17 |
18 | it("phi of 99 is 60"){
19 | val p = P40.phi(99)
20 | p should be(60)
21 | }
22 | }
23 |
24 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P14.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 |
4 | import java.util.List;
5 | import java.util.stream.Stream;
6 |
7 | import static java.util.stream.Collectors.toList;
8 |
9 | /**
10 | * (*) Duplicate the elements of a list
11 | *
12 | * duplicate(Arrays.asList("a", "b", "c", "d"))
13 | *
14 | */
15 | public class P14 {
16 |
17 | public static List duplicate(List list) {
18 | return list.stream().flatMap(e -> Stream.of(e, e)).collect(toList());
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P12Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P12Test extends FunSpec with Matchers {
6 |
7 | describe("decode spec") {
8 | it("should decode an run-length encoded list") {
9 | val decoded: List[String] = P12.decode(List((4, "a"), "b", (2, "c"), (2, "a"), "d", (4, "e")))
10 | decoded should have length 14
11 | decoded should equal(List("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"))
12 | }
13 | }
14 |
15 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P40Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.CoreMatchers.equalTo;
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class P40Test {
9 |
10 | @Test
11 | public void phiOf10Is4() throws Exception {
12 | int p = P40.phi(10);
13 | assertThat(p, equalTo(4));
14 | }
15 |
16 | @Test
17 | public void phiOf99Is60() throws Exception {
18 | int p = P40.phi(99);
19 | assertThat(p, equalTo(60));
20 | }
21 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P32.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import scala.collection.mutable
4 |
5 | /**
6 | * (**) Determine the prime factors of a given positive integer.
7 | */
8 | object P32 {
9 |
10 | def primeFactors(number: Int): List[Int] = {
11 | val factors = mutable.ListBuffer[Int]()
12 | for (f <- 2 to number / 2 if P31.isPrime(f)) {
13 | var n = number
14 | while (n % f == 0) {
15 | n = n / f
16 | factors.append(f)
17 | }
18 | }
19 | factors.toList
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/tadm/ch03/Problem3_2.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch03
2 |
3 | /**
4 | * Write a program to reverse the direction of a given singly-linked list.
5 | * In other words, after the reversal all pointers should now point backwards. Your algorithm should take linear time.
6 | */
7 | object Problem3_2 {
8 |
9 | def reverse[T](list: List[T]): List[T] = list match {
10 | case head :: tail => reverse(tail) :+ head
11 | case _ => Nil
12 | }
13 |
14 | def main(args: Array[String]) {
15 | val numbers = List(1, 2, 3)
16 | println(reverse(numbers))
17 |
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P03.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * Find the K'th element of a list.
5 | *
6 | * The first element of a list has index 0
7 | */
8 | object P03 {
9 |
10 | def kth[T](list: List[T], k: Int): T = list(k)
11 |
12 | def kth1[T](list: List[T], k: Int): T = list.take(k + 1).last
13 |
14 | def kthRecursive[T](list: List[T], k: Int): T = list match {
15 | case x :: xs if k == 0 => x
16 | case x :: xs => kthRecursive(xs, k - 1)
17 | case _ => throw new NoSuchElementException
18 | }
19 |
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P05Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P05Test extends FunSpec with Matchers {
6 |
7 | describe("Reverse a list (built-in)") {
8 | it("should reverse a list") {
9 | P05.reverse(List(1, 2, 3, 4, 5)) should equal(List(5, 4, 3, 2, 1))
10 | }
11 | }
12 |
13 | describe("Reverse a list (recursive)") {
14 | it("should reverse a list") {
15 | P05.reverseRecursive(List(1, 2, 3, 4, 5)) should equal(List(5, 4, 3, 2, 1))
16 | }
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P36.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | /**
4 | * (**) A list of Goldbach compositions.
5 | */
6 | object P36 {
7 |
8 | def goldbach_list(range: Range): List[(Int, (Int, Int))] = {
9 | range.filter(_ % 2 == 0).filter(_ > 2).map(even => {
10 | val g = P35.goldbach(even)
11 | (even, (g.head, g.last))
12 | }).toList
13 | }
14 |
15 | def goldbach_list1(range: Range, gt: Int): List[(Int, (Int, Int))] = {
16 | goldbach_list(range).filter(g => g._2._1 > gt && g._2._2 > gt)
17 | }
18 |
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P01Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P01Test extends FunSpec with Matchers {
6 |
7 | describe("P01 List builtin method") {
8 | it("should find last element") {
9 | val last = P01.last(List("a", "b", "c", "d"))
10 | last should be("d")
11 | }
12 | }
13 |
14 | describe("P01 List recursive method") {
15 | it("should find last element") {
16 | val last = P01.lastRecursion(List("a", "b", "c", "d"))
17 | last should be("d")
18 | }
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P33Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P33Test extends FunSpec with Matchers {
6 |
7 | describe("P33 Spec") {
8 |
9 | it("[[3,2],[5,1],[7,1]] is prime factors multiples of 315") {
10 | val fs = P33.primeFactorsMult(315)
11 | fs should be(List((3, 2), (5, 1), (7, 1)))
12 | }
13 |
14 | it("[[3,1],[11,1]] is prime factors multiples of 33") {
15 | val fs = P33.primeFactorsMult(33)
16 | fs should be(List((3, 1), (11, 1)))
17 | }
18 |
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P37.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | /**
4 | * (**) Determine the greatest common divisor of two positive integer numbers.
5 | */
6 | public class P37 {
7 |
8 | public static int gcd(int first, int second) {
9 | if (first == 0) {
10 | return second;
11 | } else if (second == 0) {
12 | return first;
13 | } else if (first > second) {
14 | return gcd(first - second, second);
15 | } else {
16 | return gcd(first, second - first);
17 | }
18 |
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P01.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import java.util.NoSuchElementException
4 |
5 | object P01 {
6 |
7 | /*
8 | Using the built in last function of a list
9 | */
10 | def last[T](list: List[T]): T = list.last
11 |
12 | /*
13 | Using recursion we ignore the first element until we have a list with only one element
14 | */
15 | def lastRecursion[T](list: List[T]): T = list match {
16 | case x :: Nil => x
17 | case _ :: xs => lastRecursion(xs)
18 | case _ => throw new NoSuchElementException("list is empty")
19 | }
20 |
21 |
22 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P39.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | /**
4 | * 2.09 (**) Calculate Euler's totient function phi(m).
5 | */
6 | object P39 {
7 |
8 | def totient_phi(m: Int): Int = (1 to m).count(r => P38.coprime(m, r))
9 |
10 |
11 | /**
12 | * The cototient of n is defined as n – φ(n), i.e. the number of positive integers less than or equal to n that are divisible by at least one prime that also divides n.
13 | *
14 | * @param m number
15 | * @return cototient
16 | */
17 | def cototient(m: Int): Int = m - totient_phi(m)
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P31Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertFalse;
6 | import static org.junit.Assert.assertTrue;
7 |
8 | public class P31Test {
9 |
10 | @Test
11 | public void shouldSay7IsAPrimeNumber() throws Exception {
12 | boolean prime = P31.isPrime(7);
13 | assertTrue(prime);
14 | }
15 |
16 | @Test
17 | public void shouldSay10IsNotAPrimeNumber() throws Exception {
18 | boolean prime = P31.isPrime(10);
19 | assertFalse(prime);
20 | }
21 |
22 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P14.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (*) Duplicate the elements of a list
5 | *
6 | * {{{
7 | * duplicate(List("a", "b", "c", "d"))
8 | * }}}
9 | */
10 | object P14 {
11 |
12 | /**
13 | * Using flatMap
14 | */
15 | def duplicate[T](list: List[T]): List[T] = list.flatMap(e => List(e, e))
16 |
17 |
18 | /**
19 | * Using recursion
20 | */
21 | def duplicate_recursion[T](list: List[T]): List[T] = list match {
22 | case x :: xs => x +: x +: duplicate_recursion(xs)
23 | case Nil => Nil
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/haskell/01-lists/P02.hs:
--------------------------------------------------------------------------------
1 | -- Using built-in functions
2 | secondLast :: [a] -> a
3 | secondLast [] = error "Can't find secondLast element from a list with less than 2 elements"
4 | secondLast [x] = error "Can't find secondLast element from a list with less than 2 elements"
5 | secondLast list = last (init list)
6 |
7 | -- Using recursion
8 | secondLastRecursion :: [a] -> a
9 | secondLastRecursion [] = error "Can't find secondLast element from a list with less than 2 elements"
10 | secondLastRecursion [x] = error "Can't find secondLast element from a list with less than 2 elements"
11 | secondLastRecursion (x:(y:[])) = x
12 | secondLastRecursion (x:xs) = secondLastRecursion xs
13 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P15.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 |
4 | import java.util.Collections;
5 | import java.util.List;
6 |
7 | import static java.util.stream.Collectors.toList;
8 |
9 | /**
10 | * (**) Duplicate the elements of a list a given number of times.
11 | *
12 | * duplicate(Arrays.asList("a", "b", "c", "d"))
13 | *
14 | */
15 | public class P15 {
16 |
17 | public static List duplicate(final List list, final int times) {
18 | return list.stream().flatMap(e -> Collections.nCopies(times, e).stream()).collect(toList());
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P24Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 |
7 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
8 | import static org.junit.Assert.assertThat;
9 |
10 | public class P24Test {
11 |
12 | @Test
13 | public void shouldGive6RandomNumbersFromARangeStartingFrom1To49() throws Exception {
14 | List randomList = P24.randomSelect(6, 1, 49);
15 | assertThat(randomList, hasSize(6));
16 | System.out.println(randomList); // One possible output [47, 30, 36, 38, 11, 1]
17 | }
18 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P22.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.annotation.tailrec
4 |
5 | /**
6 | * (*) Create a list containing all integers within a given range
7 | */
8 | object P22 {
9 |
10 | def range(start: Int, end: Int): List[Int] = start to end toList
11 |
12 | def rangeR(start: Int, end: Int): List[Int] = {
13 | @tailrec
14 | def range(list: List[Int], cur: Int): List[Int] = {
15 | if (cur <= end) {
16 | range(list :+ cur, cur + 1)
17 | } else {
18 | list
19 | }
20 | }
21 |
22 | range(List(), start)
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P41Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.CoreMatchers.equalTo;
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class P41Test {
9 |
10 | @Test
11 | public void shouldCalculatePhiOf10090UsingP39() throws Exception {
12 | long p = P39.phi(10090);
13 | assertThat(p, equalTo(4032L));
14 | }
15 |
16 | @Test
17 | public void shouldCalculatePhiOf10090UsingP40() throws Exception {
18 | long p = P40.phi(10090);
19 | assertThat(p, equalTo(4032L));
20 | }
21 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/CollectionUtils.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.LinkedList;
5 | import java.util.stream.Stream;
6 |
7 | import static java.util.stream.Collectors.toCollection;
8 |
9 | public abstract class CollectionUtils {
10 |
11 | public static LinkedList linkedList(T... elements) {
12 | return Stream.of(elements).collect(toCollection(LinkedList::new));
13 | }
14 |
15 | public static ArrayDeque arrayDeque(T... elements) {
16 | return Stream.of(elements).collect(toCollection(ArrayDeque::new));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/fortytwo_problems/Problem01Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.fortytwo_problems;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.AbstractMap.SimpleEntry;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
9 | import static org.junit.Assert.assertThat;
10 |
11 | public class Problem01Test {
12 |
13 | @Test
14 | public void shouldCreatePairsByMinOfMaximumSumOfPairs() throws Exception {
15 | List> pairs = Problem01.pairs(new int[]{1, 9, 3, 5});
16 | assertThat(pairs, contains(new SimpleEntry<>(1, 9), new SimpleEntry<>(3, 5)));
17 | }
18 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P22Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 |
7 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
8 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
9 | import static org.junit.Assert.assertThat;
10 |
11 | public class P22Test {
12 |
13 | @Test
14 | public void shouldCreateARangeBetween4And9() throws Exception {
15 | List range = P22.range(4, 9);
16 | assertThat(range, hasSize(6));
17 | assertThat(range, contains(4, 5, 6, 7, 8, 9));
18 |
19 | }
20 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P34.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | /**
4 | * (*) A list of prime numbers.
5 | */
6 | object P34 {
7 |
8 | def primeNumbers(range: Range): List[Int] = range.filter(number => P31.isPrime(number)).toList
9 |
10 | def primeNumbers_sieve(range: Range): List[Int] = {
11 | val start = 2
12 | val numbers = start to range.last
13 |
14 | def p(numbers: List[Int]): List[Int] = numbers match {
15 | case n :: remaining => n +: p(remaining.filter(_ % n != 0))
16 | case _ => Nil
17 | }
18 | p(numbers.toList).filter(_ >= range.head)
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P20.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (*) Remove the K'th element from a list
5 | */
6 | object P20 {
7 |
8 | /*
9 | Using built in take drop
10 | */
11 | def removeAt[T](list: List[T], k: Int): (List[T], T) = (list.take(k - 1) ++ list.drop(k), list(k - 1))
12 |
13 | def removeAt0[T](list: List[T], k: Int): (List[T], T) = (list.take(k) ++ list.drop(k + 1), list(k))
14 |
15 | /*
16 | Using splitAt
17 | */
18 | def removeAt_splitAt[T](list: List[T], k: Int): (List[T], T) = {
19 | val (first, second) = list.splitAt(k)
20 | (first.init ++ second, first.last)
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/haskell/01-lists/P27.hs:
--------------------------------------------------------------------------------
1 | import P26
2 | import Data.List
3 | -- (**) Group the elements of a set into disjoint subsets
4 |
5 | -- In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a predicate that generates all the possibilities via backtracking
6 | group3 :: Eq a => [a] -> [[[a]]]
7 | group3 xs = [[c2,c3,((xs \\ c2) \\ c3)] |c2 <- (combinations xs 2),c3 <- (combinations (xs \\ c2) 3)]
8 |
9 | -- Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups
10 | group' :: Eq a => [a] -> [Int] -> [[[a]]]
11 | group' xs [] = [[]]
12 | group' xs (n:ns) = [c:cg |c <- (combinations xs n), cg <- (group' (xs \\ c) ns)]
13 |
--------------------------------------------------------------------------------
/haskell/01-lists/P11.hs:
--------------------------------------------------------------------------------
1 | import P09
2 |
3 | -- (*) Modified run-length encoding
4 | encode_modified :: Eq a => [a] -> [Either a (Int,a)]
5 | encode_modified xs = map (\ll -> tupleOrElement ll) (pack xs)
6 |
7 | tupleOrElement :: [a] -> Either a (Int,a)
8 | tupleOrElement (x:[]) = Left x
9 | tupleOrElement ll = Right (length ll, head ll)
10 |
11 | -- Another implementation using custom data type
12 | data ElementOrTuple a = Elem a | Tuple Int a deriving (Eq, Show)
13 | encode_modified' :: Eq a => [a] -> [ElementOrTuple a]
14 | encode_modified' list = map (\ll -> _encode_helper ll) (pack list)
15 |
16 | _encode_helper :: [a] -> ElementOrTuple a
17 | _encode_helper (x:[]) = Elem x
18 | _encode_helper ll = Tuple (length ll) (head ll)
19 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/tadm/ch04/excercises/Problem4_6.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.excercises;
2 |
3 | import java.util.Arrays;
4 |
5 | public class Problem4_6 {
6 |
7 | public static boolean findPair(int[] s1, int[] s2, int x) {
8 | /*
9 | Sort one array let say s2
10 | for each el in s1
11 | do a binary search in s2 for x-el
12 | if found return el and (x-el)
13 | */
14 | Arrays.sort(s2);
15 | for (int f : s1) {
16 | int s = x - f;
17 | if (Arrays.binarySearch(s2, s) >= 0) {
18 | return true;
19 | }
20 | }
21 | return false;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P26.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (**) Generate the combinations of K distinct objects chosen from the N elements of a list
5 | */
6 | object P26 {
7 |
8 | /**
9 | * Using built-in combinations function
10 | */
11 | def combinations[T](list: List[T], k: Int): List[List[T]] = list.combinations(k).toList
12 |
13 | def combinations1[T](list: List[T], k: Int): List[List[T]] = {
14 | list match {
15 | case x :: xs if k == 1 => list.map(List(_))
16 | case x :: xs => combinations1(xs, k - 1).map(x :: _) ::: combinations1(xs, k)
17 | case Nil => Nil
18 | }
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P06.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Objects;
6 |
7 | /**
8 | * Find out whether a list is a palindrome.
9 | */
10 | public class P06 {
11 |
12 | public static boolean isPalindrome(List list) {
13 | List original = new ArrayList<>(list);
14 | P05.reverse(list);
15 | return Objects.equals(list, original);
16 | }
17 |
18 | public static boolean isPalindrome_IntStream(List list) {
19 | List reversed = P05.reverse_IntStream(list);
20 | return Objects.equals(list, reversed);
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P12.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.annotation.tailrec
4 |
5 | /**
6 | * (**) Decode a run-length encoded list.
7 | * {{{
8 | * decode(List((4, "a"), "b", (2, "c"), (2, "a"), "d", (4, "e")))
9 | * }}}
10 | */
11 | object P12 {
12 |
13 | def decode[T](encoded: List[Any]): List[T] = {
14 | @tailrec
15 | def decodeR(encoded: List[Any], result: List[T]): List[T] = encoded match {
16 | case ((n: Int, e: T) :: xs) => decodeR(xs, result ++ List.fill(n)(e))
17 | case ((e: T) :: xs) => decodeR(xs, result :+ e)
18 | case Nil => result
19 | }
20 | decodeR(encoded, List())
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P18.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.annotation.tailrec
4 |
5 | /**
6 | * (**) Extract a slice from a list
7 | */
8 | object P18 {
9 |
10 | def slice[T](list: List[T], start: Int, end: Int): List[T] = list.slice(start - 1, end)
11 |
12 | def sliceR[T](list: List[T], start: Int, end: Int): List[T] = {
13 | @tailrec
14 | def slice(list: List[T], cur: Int, acc: List[T]): List[T] = list match {
15 | case x :: xs if cur >= start - 1 && cur < end => slice(xs, cur + 1, acc :+ x)
16 | case x :: xs => slice(xs, cur + 1, acc)
17 | case _ => acc
18 | }
19 | slice(list, 0, List())
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_04_binary_trees/P51Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._04_binary_trees
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P51Test extends FunSpec with Matchers {
6 |
7 | describe("Tree") {
8 | it("is a binary tree if it is empty") {
9 | P51.isTree(null) should be(true)
10 | }
11 |
12 | it("is a binary tree if it only consists on root node") {
13 | P51.isTree(BinaryTree(1, null, null)) should be(true)
14 | }
15 |
16 | it("is a binary tree if it consists of root node and left and right nodes") {
17 | P51.isTree(BinaryTree(3, BinaryTree(2, null, null), BinaryTree(5, null, null))) should be(true)
18 | }
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P15.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (**) Duplicate the elements of a list a given number of times.
5 | *
6 | * {{{
7 | * duplicateTimes(List("a", "b", "c"), 3)
8 | * }}}
9 | */
10 | object P15 {
11 |
12 | /*
13 | Using flatMap and List.fill
14 | */
15 | def duplicateTimes[T](list: List[T], times: Int): List[T] = list.flatMap(x => List.fill(times)(x))
16 |
17 |
18 | /*
19 | Using recursion
20 | */
21 | def duplicateTimes_recursion[T](list: List[T], times: Int): List[T] = list match {
22 | case x :: xs => List.fill(times)(x) ++ duplicateTimes_recursion(xs, times)
23 | case Nil => Nil
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P32.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.stream.IntStream;
6 |
7 | /**
8 | * (**) Determine the prime factors of a given positive integer.
9 | */
10 | public class P32 {
11 |
12 | public static List primeFactors(int number) {
13 | List fs = new ArrayList<>();
14 | IntStream.rangeClosed(2, number / 2).filter(P31::isPrime).forEach(f -> {
15 | int n = number;
16 | while (n % f == 0) {
17 | n = n / f;
18 | fs.add(f);
19 | }
20 | });
21 | return fs;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P22Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P22Test extends FunSpec with Matchers {
6 |
7 | describe("P22 Spec") {
8 | it("should give a range between 4 to 9 both inclusive") {
9 | val range: List[Int] = P22.range(4, 9)
10 | range should have length 6
11 | range should be(List(4, 5, 6, 7, 8, 9))
12 | }
13 | }
14 |
15 | describe("P22 Spec recursive") {
16 | it("should give a range between 4 to 9 both inclusive") {
17 | val range: List[Int] = P22.rangeR(4, 9)
18 | range should have length 6
19 | range should be(List(4, 5, 6, 7, 8, 9))
20 | }
21 | }
22 |
23 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P39Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P39Test extends FunSpec with Matchers {
6 |
7 | describe("P39 Spec"){
8 | it("10 has 4 Euler totient"){
9 | val phi = P39.totient_phi(10)
10 | phi should be(4)
11 | }
12 |
13 | it("9 has 6 Euler totient"){
14 | val phi = P39.totient_phi(9)
15 | phi should be(6)
16 | }
17 |
18 | it("6 has 2 Euler totient"){
19 | val phi = P39.totient_phi(6)
20 | phi should be(2)
21 | }
22 |
23 | it("6 has 4 cototient"){
24 | val c = P39.cototient(6)
25 | c should be(4)
26 | }
27 |
28 | }
29 |
30 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P33.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import com.shekhargulati.ninetynine_problems._01_lists.P10;
4 |
5 | import java.util.AbstractMap.SimpleEntry;
6 | import java.util.List;
7 |
8 | import static java.util.stream.Collectors.toList;
9 |
10 | /**
11 | * (**) Determine the prime factors of a given positive integer (2)
12 | */
13 | public class P33 {
14 |
15 | public static List> primeFactorsMult(int number) {
16 | return P10.encode(P32.primeFactors(number))
17 | .stream()
18 | .map(e -> new SimpleEntry<>(e.getValue(), e.getKey()))
19 | .collect(toList());
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P50.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes
2 |
3 | /**
4 | * (***) Huffman code.
5 | */
6 | object P50 {
7 |
8 | class Tree[T](data: (Int, T), left: Tree[T], right: Tree[T])
9 |
10 | def huffman(fs: List[(String, Int)]): List[(String, String)] = {
11 | val sortedFs = fs.sortBy { case (_, f) => f }
12 | println(sortedFs)
13 |
14 | val firstTwoElements: List[(String, Int)] = sortedFs.take(2)
15 | val tree: Tree[String] = new Tree((firstTwoElements.map(_._2).sum, "*"), new Tree[String](firstTwoElements.head.swap, null, null), new Tree[String](firstTwoElements.last.swap, null, null))
16 |
17 | sortedFs.drop(2)
18 |
19 | ???
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/leetcode/algorithms/Problem03.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.leetcode.algorithms;
2 |
3 | /**
4 | * Longest substring without repeating characters
5 | */
6 | public class Problem03 {
7 |
8 | public static String substring(final String input) {
9 | StringBuilder subStr = new StringBuilder();
10 | String[] chars = input.split("");
11 | for (String ch : chars) {
12 | int indexCh = subStr.indexOf(ch);
13 | if (indexCh == -1) {
14 | subStr.append(ch);
15 | } else {
16 | subStr = new StringBuilder(subStr.substring(indexCh + 1));
17 | subStr.append(ch);
18 | }
19 | }
20 | return subStr.toString();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P14Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
9 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P14Test {
13 |
14 | @Test
15 | public void shouldDuplicateElementsInAList() throws Exception {
16 | List duplicates = P14.duplicate(Arrays.asList("a", "b", "c", "d"));
17 | assertThat(duplicates, hasSize(8));
18 | assertThat(duplicates, contains("a", "a", "b", "b", "c", "c", "d", "d"));
19 | }
20 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P15Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
9 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P15Test {
13 |
14 | @Test
15 | public void shouldDuplicateElementsInAList() throws Exception {
16 | List duplicates = P15.duplicate(Arrays.asList("a", "b", "c"), 3);
17 | assertThat(duplicates, hasSize(9));
18 | assertThat(duplicates, contains("a", "a", "a", "b", "b", "b", "c", "c", "c"));
19 | }
20 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P18Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
9 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P18Test {
13 |
14 | @Test
15 | public void shouldGiveSliceOfAList() throws Exception {
16 | List slice = P18.slice(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "k"), 3, 7);
17 | assertThat(slice, hasSize(5));
18 | assertThat(slice, contains("c", "d", "e", "f", "g"));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P17Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 | import java.util.Map;
8 |
9 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P17Test {
13 |
14 | @Test
15 | public void shouldSplitInTwoHalves() throws Exception {
16 | Map> result = P17.split(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "k"), 3);
17 | assertThat(result.get(true), contains("a", "b", "c"));
18 | assertThat(result.get(false), contains("d", "e", "f", "g", "h", "i", "k"));
19 | }
20 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P32Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 |
7 | import static org.hamcrest.core.IsCollectionContaining.hasItems;
8 | import static org.junit.Assert.assertThat;
9 |
10 | public class P32Test {
11 |
12 | @Test
13 | public void shouldFindPrimeFactorsOf315() throws Exception {
14 | List primeFactors = P32.primeFactors(315);
15 | assertThat(primeFactors, hasItems(3, 3, 5, 7));
16 | }
17 |
18 | @Test
19 | public void shouldFindPrimeFactorsOf33() throws Exception {
20 | List primeFactors = P32.primeFactors(33);
21 | assertThat(primeFactors, hasItems(3, 11));
22 | }
23 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P17.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.AbstractMap.SimpleEntry;
4 | import java.util.List;
5 | import java.util.Map;
6 | import java.util.stream.IntStream;
7 |
8 | import static java.util.stream.Collectors.*;
9 |
10 | /**
11 | * (*) Split a list into two parts; the length of the first part is given
12 | */
13 | public class P17 {
14 |
15 | public static Map> split(List list, int n) {
16 | return IntStream
17 | .range(0, list.size())
18 | .mapToObj(i -> new SimpleEntry<>(i, list.get(i)))
19 | .collect(partitioningBy(entry -> entry.getKey() < n, mapping(SimpleEntry::getValue, toList())));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P11Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P11Test extends FunSpec with Matchers {
6 |
7 | describe("encode-modified spec") {
8 | it("should apply modified run-length on list") {
9 | val encodedList: List[Any] = P11.encode_modified(List("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"))
10 | encodedList should have size 6
11 | encodedList(0) should equal((4, "a"))
12 | encodedList(1) should equal("b")
13 | encodedList(2) should equal((2, "c"))
14 | encodedList(3) should equal((2, "a"))
15 | encodedList(4) should equal("d")
16 | encodedList(5) should equal((4, "e"))
17 | }
18 | }
19 |
20 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P11.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (*) Modified run-length encoding
5 | *
6 | * Modify the result of problem 1.10 in such a way that if an element has no duplicates it is simply copied into the result list.
7 | * Only elements with duplicates are transferred as [N,E] terms.
8 | *
9 | * {{{
10 | * encode_modified(List("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"))
11 | * }}}
12 | *
13 | */
14 | object P11 {
15 |
16 | def encode_modified[T](list: List[T]): List[Any] = {
17 | P09.pack_span(list).map(ll => ll match {
18 | case x :: Nil => x
19 | case x :: xs => (ll.length, x)
20 | case Nil => Nil
21 | })
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P23Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P23Test extends FunSpec with Matchers {
6 |
7 | describe("P23 Spec") {
8 | it("should randomly select three elements") {
9 | val randomElements: List[String] = P23.randomSelect(List("a", "b", "c", "d", "e", "f", "g", "h"), 3)
10 | randomElements should have length 3
11 | }
12 | }
13 |
14 | describe("P23 Spec recursive without duplicates") {
15 | it("should randomly select three elements") {
16 | val randomElements: List[String] = P23.randomSelect(List("a", "b", "c", "d", "e", "f", "g", "h"), 3)
17 | println(randomElements)
18 | randomElements should have length 3
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/haskell/02-arithmetic/P35.hs:
--------------------------------------------------------------------------------
1 | module P35 where
2 | import P34
3 | -- (**) Goldbach's conjecture.
4 | -- Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system). Write a predicate to find the two prime numbers that sum up to a given even integer.
5 |
6 | goldbach :: Int -> [Int]
7 | goldbach 2 = []
8 | goldbach number = _goldbach number (primeNumbers [2..number])
9 |
10 | _goldbach :: Int -> [Int] -> [Int]
11 | _goldbach number (p:rp)
12 | | elem (number - p) (p:rp) = [p, (number - p)]
13 | _goldbach number (p:rp) = _goldbach number rp
14 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P11.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.AbstractMap.SimpleEntry;
4 | import java.util.List;
5 |
6 | import static java.util.stream.Collectors.toList;
7 |
8 | /**
9 | * (*) Modified run-length encoding
10 | *
11 | * encode_modified(Arrays.asList("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"))
12 | *
13 | */
14 | public class P11 {
15 |
16 | public static List encode_modified(List list) {
17 | return P09.pack(list).stream().map(l -> {
18 | if (l.size() == 1) {
19 | return l.get(0);
20 | }
21 | return new SimpleEntry<>(l.size(), l.get(0));
22 | }).collect(toList());
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P16.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.AbstractMap.SimpleEntry;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 | import java.util.stream.IntStream;
7 |
8 | /**
9 | * <(**) Drop every N'th element from a list/b>
10 | */
11 | public class P16 {
12 |
13 | public static List dropEveryNth(List list, int n) {
14 | if (n == 0) {
15 | return list;
16 | }
17 | return IntStream.range(0, list.size())
18 | .mapToObj(i -> new SimpleEntry<>(list.get(i), i))
19 | .filter(entry -> (entry.getValue() + 1) % n != 0)
20 | .map(SimpleEntry::getKey)
21 | .collect(Collectors.toList());
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/random/algebra/RandomProblem005.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random.algebra;
2 |
3 | /**
4 | * Write a program that can evaluate a polynomial
5 | * p(x) = ao + a1x^1 + a2x^2 + .... + anx^n
6 | *
7 | * https://en.wikipedia.org/wiki/Horner%27s_method
8 | */
9 | public class RandomProblem005 {
10 |
11 | public static int evaluatePolynomialAt(int n, int a, int x) {
12 | int result = a;
13 | for (int i = 1; i <= n; i++) {
14 | result = result + Double.valueOf(a * Math.pow(x, i)).intValue();
15 | }
16 | return result;
17 | }
18 |
19 | public static int eval(int n, int a, int x) {
20 | int res = 0;
21 | for (int i = n; i >= 0; i--) {
22 | res = (res * x) + a;
23 | }
24 | return res;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/leetcode/Problem03Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.leetcode;
2 |
3 | import com.shekhargulati.leetcode.algorithms.Problem03;
4 | import org.junit.Test;
5 |
6 | import static org.hamcrest.CoreMatchers.equalTo;
7 | import static org.junit.Assert.assertThat;
8 |
9 | public class Problem03Test {
10 |
11 | @Test
12 | public void shouldFindLongestSubstring() throws Exception {
13 | final String input = "abcabc";
14 | String substring = Problem03.substring(input);
15 | assertThat(substring, equalTo("abc"));
16 | }
17 |
18 | @Test
19 | public void shouldFindLongestSubstringIn_bbbbb() throws Exception {
20 | final String input = "bbbb";
21 | String substring = Problem03.substring(input);
22 | assertThat(substring, equalTo("b"));
23 | }
24 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/tadm/ch04/examples/SelectionSort.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.examples;
2 |
3 | public class SelectionSort {
4 |
5 | public static int[] sort(int[] arr) {
6 | for (int i = 0; i < arr.length; i++) {
7 | int min = findMinIndex(arr, i);
8 | swap(arr, i, min);
9 | }
10 | return arr;
11 | }
12 |
13 | private static void swap(int[] arr, int i, int min) {
14 | int tmp = arr[i];
15 | arr[i] = arr[min];
16 | arr[min] = tmp;
17 | }
18 |
19 | private static int findMinIndex(int[] arr, int i) {
20 | int min = i;
21 | for (int j = i + 1; j < arr.length; j++) {
22 | if (arr[j] < arr[min]) {
23 | min = j;
24 | }
25 | }
26 | return min;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P18Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P18Test extends FunSpec with Matchers {
6 |
7 | describe("P18 Spec") {
8 | it("should return list between two indexes") {
9 | val result = P18.slice(List("a", "b", "c", "d", "e", "f", "g", "h", "i", "k"), 3, 7)
10 | result should have length 5
11 | result should be(List("c", "d", "e", "f", "g"))
12 | }
13 | }
14 |
15 | describe("P18 Spec recursion") {
16 | it("should return list between two indexes") {
17 | val result = P18.sliceR(List("a", "b", "c", "d", "e", "f", "g", "h", "i", "k"), 3, 7)
18 | result should have length 5
19 | result should be(List("c", "d", "e", "f", "g"))
20 | }
21 | }
22 |
23 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P10Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P10Test extends FunSpec with Matchers {
6 |
7 | describe("encode a list spec") {
8 | it("should encode consecutive duplicate elements") {
9 | val list = List("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e")
10 | val encodedList: List[(Int, String)] = P10.encode(list)
11 | encodedList should have size 6
12 | encodedList(0) should equal((4, "a"))
13 | encodedList(1) should equal((1, "b"))
14 | encodedList(2) should equal((2, "c"))
15 | encodedList(3) should equal((2, "a"))
16 | encodedList(4) should equal((1, "d"))
17 | encodedList(5) should equal((4, "e"))
18 | }
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/random/RandomProblem003Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.CoreMatchers.equalTo;
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class RandomProblem003Test {
9 |
10 | @Test
11 | public void performMatrixMultiplicationOfTwoArrays() throws Exception {
12 | int[][] a = {
13 | {1, 2, 3},
14 | {4, 5, 6}
15 | };
16 |
17 | int[][] b = {
18 | {7, 8},
19 | {9, 10},
20 | {11, 12}
21 | };
22 |
23 | int[][] result = {
24 | {58, 64},
25 | {139, 154}
26 | };
27 |
28 | int[][] c = RandomProblem003.matrixMultiplication(a, b);
29 | assertThat(c, equalTo(result));
30 | }
31 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P32Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P32Test extends FunSpec with Matchers {
6 |
7 | describe("Problem 32 Spec") {
8 |
9 | it("[2,2,2] are prime factors of 8") {
10 | val fs = P32.primeFactors(8)
11 | fs should be(List(2, 2, 2))
12 | }
13 |
14 | it("[2,2,3] are prime factors of 12") {
15 | val fs = P32.primeFactors(12)
16 | fs should be(List(2, 2, 3))
17 | }
18 |
19 | it("[3,3,5,7] are prime factors of 315") {
20 | val fs = P32.primeFactors(315)
21 | fs should be(List(3, 3, 5, 7))
22 | }
23 |
24 | it("[3,11] are prime factors of 33") {
25 | val fs = P32.primeFactors(33)
26 | fs should be(List(3, 11))
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P35Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P35Test extends FunSpec with Matchers {
6 |
7 | describe("P35 Spec") {
8 | it("8 is the sum of 5 and 3 prime numbers") {
9 | val numbers = P35.goldbach(8)
10 | numbers should have length 2
11 | numbers should be(List(3, 5))
12 | }
13 |
14 | it("4 is the sum of 2 and 2 prime numbers") {
15 | val numbers = P35.goldbach(4)
16 | numbers should have length 2
17 | numbers should be(List(2, 2))
18 | }
19 |
20 | it("28 is the sum of 5 and 23 prime numbers") {
21 | val numbers = P35.goldbach(28)
22 | numbers should have length 2
23 | numbers should be(List(5, 23))
24 | }
25 |
26 | }
27 |
28 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P49Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P49Test extends FunSpec with Matchers {
6 |
7 | describe("P49 Spec") {
8 | it("gray code of n=1 is ['0','1']") {
9 | val graySequence = P49.gray(1)
10 | graySequence should be(List("0", "1"))
11 | }
12 |
13 | it("gray code of n=2 is ['00','01','11','10']") {
14 | val graySequence = P49.gray(2)
15 | graySequence should be(List("00", "01", "11", "10"))
16 | }
17 |
18 | it("gray code of n=3 is ['000', '001', '011', '010', '110', '111', '101', '100']") {
19 | val graySequence = P49.gray(3)
20 | graySequence should be(List("000", "001", "011", "010", "110", "111", "101", "100"))
21 | }
22 |
23 | }
24 |
25 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P23.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.util.Random
4 |
5 | /**
6 | * (**) Extract a given number of randomly selected elements from a list
7 | */
8 | object P23 {
9 |
10 | /*
11 | Easy solution by generating a random sequence of numbers.
12 | This solution may not be ideal as this can produce duplicates
13 | */
14 | def randomSelect[T](list: List[T], n: Int): List[T] = {
15 | val randomSeq = Seq.fill(n)(Random.nextInt(list.size))
16 | randomSeq.map(r => list(r)).toList
17 | }
18 |
19 | def randomSelectR[T](list: List[T], n: Int): List[T] = {
20 | if (n == 0) {
21 | Nil
22 | } else {
23 | val (l, el) = P20.removeAt0(list, Random.nextInt(list.size))
24 | el :: randomSelectR(l, n - 1)
25 | }
26 |
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/tadm/ch03/Problem3_2Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch03;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.LinkedList;
6 | import java.util.List;
7 | import java.util.stream.IntStream;
8 | import java.util.stream.Stream;
9 |
10 | import static java.util.stream.Collectors.toCollection;
11 | import static org.hamcrest.CoreMatchers.equalTo;
12 | import static org.junit.Assert.assertThat;
13 |
14 | public class Problem3_2Test {
15 |
16 | @Test
17 | public void shouldReverseALinkedList() throws Exception {
18 | List numbers = IntStream.rangeClosed(1, 10).boxed().collect(toCollection(LinkedList::new));
19 | List reversedNumbers = new Problem3_2().reverse(numbers);
20 | assertThat(reversedNumbers, equalTo(Stream.of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1).collect(toCollection(LinkedList::new))));
21 | }
22 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P07.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (**) Flatten a nested list structure
5 | *
6 | * Transform a list, possibly holding lists as elements into a 'flat' list by replacing each list with its elements (recursively).
7 | *
8 | */
9 | object P07 {
10 |
11 | def flatten(list: List[Any]): List[Any] = {
12 | var result = List[Any]()
13 | for (el <- list) {
14 | el match {
15 | case xs: List[Any] =>
16 | result = result ++: flatten(xs)
17 | case _ =>
18 | result = result :+ el
19 | }
20 | }
21 | result
22 | }
23 |
24 | def flatten_flatMap(list: List[Any]): List[Any] = list.flatMap(el => el match {
25 | case xs: List[Any] => flatten_flatMap(xs)
26 | case _ => List(el)
27 | })
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/tadm/ch04/excercises/Problem4_5.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.excercises;
2 |
3 | import java.util.Arrays;
4 |
5 | public class Problem4_5 {
6 |
7 | public static int mode(int[] numbers) {
8 | Arrays.sort(numbers);
9 | int modeCount = 0;
10 | int mode = 0;
11 | int prev = numbers[0];
12 | int currentCount = 0;
13 | for (int i = 1; i < numbers.length; i++) {
14 | int cur = numbers[i];
15 | if (prev == cur) {
16 | currentCount++;
17 | } else {
18 | if (currentCount > modeCount) {
19 | modeCount = currentCount;
20 | mode = prev;
21 | }
22 | prev = cur;
23 | currentCount = 0;
24 | }
25 | }
26 | return mode;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/random/RandomProblem004Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.CoreMatchers.equalTo;
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class RandomProblem004Test {
9 |
10 | @Test
11 | public void sumOfFirst10NumbersIs55() throws Exception {
12 | int sumOfNNumbers = RandomProblem004.sumOfNNumbers(10);
13 | assertThat(sumOfNNumbers, equalTo(55));
14 | }
15 |
16 | @Test
17 | public void squareOf10Is100() throws Exception {
18 | int square = RandomProblem004.squareOfANumber(10);
19 | assertThat(square, equalTo(100));
20 | }
21 |
22 | @Test
23 | public void sumOfFirst10NumbersIs55_1() throws Exception {
24 | int sum = RandomProblem004.sumOfNNumbers1(10);
25 | assertThat(sum, equalTo(55));
26 |
27 | }
28 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P03.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.LinkedList;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 |
7 | /**
8 | * Find the Kth element of a list.
9 | */
10 | public class P03 {
11 |
12 | public static T kth(final List list, final int k) {
13 | return list.get(k);
14 | }
15 |
16 | public static T kthRecursive(final LinkedList list, final int k) {
17 | if (k == 0) {
18 | return list.getFirst();
19 | }
20 | return kthRecursive(new LinkedList<>(list.subList(1, list.size())), k - 1);
21 | }
22 |
23 | public static T kthStream(final List list, final int k) {
24 | return list.stream().limit(k + 1).collect(Collectors.toCollection(LinkedList::new)).getLast();
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P14Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P14Test extends FunSpec with Matchers {
6 |
7 | describe("P14 Spec") {
8 | it("should duplicate elements in a list") {
9 | val duplicateList: List[String] = P14.duplicate(List("a", "b", "c", "d"))
10 | duplicateList should have length 8
11 | duplicateList should equal(List("a", "a", "b", "b", "c", "c", "d", "d"))
12 | }
13 | }
14 |
15 | describe("P14 Spec (recursion)") {
16 | it("should duplicate elements in a list") {
17 | val duplicateList: List[String] = P14.duplicate_recursion(List("a", "b", "c", "d"))
18 | duplicateList should have length 8
19 | duplicateList should equal(List("a", "a", "b", "b", "c", "c", "d", "d"))
20 | }
21 | }
22 |
23 |
24 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P15Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P15Test extends FunSpec with Matchers {
6 |
7 | describe("P15 Spec") {
8 | it("should duplicate N times elements of a list") {
9 | val duplicates: List[String] = P15.duplicateTimes(List("a", "b", "c"), 3)
10 | duplicates should have length 9
11 | duplicates should equal(List("a", "a", "a", "b", "b", "b", "c", "c", "c"))
12 | }
13 | }
14 |
15 | describe("P15 Spec recursion") {
16 | it("should duplicate N times elements of a list") {
17 | val duplicates: List[String] = P15.duplicateTimes_recursion(List("a", "b", "c"), 3)
18 | duplicates should have length 9
19 | duplicates should equal(List("a", "a", "a", "b", "b", "b", "c", "c", "c"))
20 | }
21 | }
22 |
23 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P46Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes
2 |
3 | import com.shekhargulati.ninetynine_problems._03_logic_and_codes.P46.{and, or}
4 | import org.scalatest.{FunSpec, Matchers}
5 |
6 | class P46Test extends FunSpec with Matchers {
7 |
8 | describe("P46 Spec") {
9 | it("should generate truth table of a given logical expression") {
10 | val tableContents = P46.table((a: Boolean, b: Boolean) => and(a, or(a, b)))
11 | val result = """A B result
12 | |true true true
13 | |true false true
14 | |false true false
15 | |false false false
16 | |""".stripMargin
17 |
18 | tableContents should be(result)
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P12Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.AbstractMap.SimpleEntry;
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P12Test {
13 |
14 | @Test
15 | public void shouldDecodeEncodedList() throws Exception {
16 | List encoded = P12.decode(
17 | Arrays.asList(
18 | new SimpleEntry<>(4, "a"),
19 | "b",
20 | new SimpleEntry<>(2, "c"),
21 | new SimpleEntry<>(2, "a"),
22 | "d",
23 | new SimpleEntry<>(4, "e")));
24 |
25 | assertThat(encoded, hasSize(14));
26 | }
27 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P25Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 | import java.util.stream.Stream;
7 |
8 | import static java.util.stream.Collectors.toList;
9 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
10 | import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
11 | import static org.junit.Assert.assertThat;
12 |
13 | public class P25Test {
14 |
15 | @Test
16 | public void shouldGenerateRandomPermutationOfElementsOfAList() throws Exception {
17 | List permutation = P25.randomPermutation(Stream.of("a", "b", "c", "d", "e", "f").collect(toList()));
18 | System.out.println(permutation);
19 | assertThat(permutation, hasSize(6));
20 | assertThat(permutation, containsInAnyOrder("a", "b", "c", "d", "e", "f"));
21 | }
22 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P20Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 |
7 | import static org.hamcrest.CoreMatchers.equalTo;
8 | import static org.junit.Assert.assertThat;
9 |
10 | public class P20Test {
11 |
12 | @Test
13 | public void shouldRemoveKthElementFromList() throws Exception {
14 | Object[] result = P20.removeAt(Arrays.asList("a", "b", "c", "d"), 2);
15 | assertThat(result[0], equalTo(Arrays.asList("a", "c", "d")));
16 | assertThat(result[1], equalTo("b"));
17 | }
18 |
19 | @Test
20 | public void shouldRemoveKthElementFromList_() throws Exception {
21 | Object[] result = P20.removeAt_splitAt(Arrays.asList("a", "b", "c", "d"), 2);
22 | assertThat(result[0], equalTo(Arrays.asList("a", "c", "d")));
23 | assertThat(result[1], equalTo("b"));
24 | }
25 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P36Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P36Test extends FunSpec with Matchers {
6 |
7 | describe("P36 Spec") {
8 | it("should produce a list of goldbach compositions") {
9 | val goldaCompositions = P36.goldbach_list(9 to 20)
10 | goldaCompositions should have length 6
11 | goldaCompositions should be(List((10, (3, 7)), (12, (5, 7)), (14, (3, 11)), (16, (3, 13)), (18, (5, 13)), (20, (3, 17))))
12 | }
13 |
14 | it("should produce a list of goldbach compositions where both primes are greater than 50") {
15 | val goldaCompositions = P36.goldbach_list1(1 to 2000, 50)
16 | goldaCompositions should have length 4
17 | goldaCompositions should be(List((992, (73, 919)), (1382, (61, 1321)), (1856, (67, 1789)), (1928, (61, 1867))))
18 | }
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P04.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * Find the number of elements of a list
7 | */
8 | public class P04 {
9 |
10 | public static int length(List list) {
11 | return list.size();
12 | }
13 |
14 | public static long lengthStream(List list) {
15 | return list.stream().count();
16 | }
17 |
18 | public static long lengthStream1(List list) {
19 | return list.stream().mapToInt(x -> 1).sum();
20 | }
21 |
22 | public static int lengthRecursive(List list) {
23 | return _lengthRecursive(list, 0);
24 | }
25 |
26 | private static int _lengthRecursive(List list, int i) {
27 | if (list.isEmpty()) {
28 | return i;
29 | }
30 | return _lengthRecursive(list.subList(1, list.size()), ++i);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/tadm/ch04/excercises/Problem4_1Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.excercises;
2 |
3 | import org.hamcrest.CoreMatchers;
4 | import org.junit.Test;
5 |
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import static org.junit.Assert.assertThat;
10 |
11 | public class Problem4_1Test {
12 |
13 | @Test
14 | public void shouldDistributePlayersIntoTwoUnfairTeams() throws Exception {
15 | List players = Arrays.asList(new Player("a", 10), new Player("b", 7), new Player("c", 11), new Player("d", 2), new Player("e", 4), new Player("f", 15));
16 |
17 | List> teams = Problem4_1.teams(players);
18 | assertThat(teams.get(0), CoreMatchers.equalTo(Arrays.asList(new Player("d", 2), new Player("e", 4), new Player("b", 7))));
19 | assertThat(teams.get(1), CoreMatchers.equalTo(Arrays.asList(new Player("a", 10), new Player("c", 11), new Player("f", 15))));
20 |
21 | }
22 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/IntPair.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati;
2 |
3 | import java.util.Objects;
4 |
5 | public class IntPair {
6 |
7 | public int first;
8 | public int second;
9 |
10 | public IntPair(int first, int second) {
11 | this.first = first;
12 | this.second = second;
13 | }
14 |
15 | @Override
16 | public String toString() {
17 | return "IntPair{" +
18 | "first=" + first +
19 | ", second=" + second +
20 | '}';
21 | }
22 |
23 | @Override
24 | public boolean equals(Object o) {
25 | if (this == o) return true;
26 | if (o == null || getClass() != o.getClass()) return false;
27 | IntPair intPair = (IntPair) o;
28 | return first == intPair.first &&
29 | second == intPair.second;
30 | }
31 |
32 | @Override
33 | public int hashCode() {
34 | return Objects.hash(first, second);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/random/RandomProblem01.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random
2 |
3 | /**
4 | * You are given two list of sizes n and m where n >> m i.e n is much bigger than m.
5 | * You have to find the fastest way to find intersection between n and m.
6 | *
7 | * Possible problem: You have a big list of valid account numbers and a small list of fraud accounts and your job is to find
8 | * if there are any valid accounts in the fraud list.
9 | */
10 | object RandomProblem01 {
11 |
12 | def intersection[T](nList: Vector[T], mList: Vector[T]): Vector[T] = {
13 | /*
14 | 1. Sort the mList
15 | 2. Iterate over nList and for each element do a binary search in the mList
16 | 3. If else is found, then add to the result list
17 | 4. Else skip the element
18 | 5. Return the result list
19 | */
20 | // for (el <- nList if mList.sorted.contains(el)) yield {
21 | // el
22 | // }
23 | ???
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P06Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P06Test extends FunSpec with Matchers {
6 |
7 | describe("Palindrome (reverse built-in)") {
8 | it("should return true when list is palindrome") {
9 | P06.isPalindrome(List("x", "a", "m", "a", "x")) should be(true)
10 | }
11 |
12 | it("should return false when list is not palindrome") {
13 | P06.isPalindrome(List(1, 2, 3, 4, 5)) should be(false)
14 | }
15 | }
16 |
17 | describe("Palindrome (reverse recursive)") {
18 | it("should return true when list is palindrome") {
19 | P06.isPalindrome_reverseRecursive(List("x", "a", "m", "a", "x")) should be(true)
20 | }
21 |
22 | it("should return false when list is not palindrome") {
23 | P06.isPalindrome_reverseRecursive(List(1, 2, 3, 4, 5)) should be(false)
24 | }
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/tadm/ch03/Problem3_4.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch03;
2 |
3 | /**
4 | * Design a dictionary data structure in which search, insertion, and deletion can all be processed in O(1) time
5 | * in the worst case.
6 | * You may assume the set elements are integers drawn from a finite set 1, 2, .., n, and initialization can take O(n) time.
7 | */
8 | public class Problem3_4 {
9 |
10 | /*
11 | The solution can be implemented using an array as we have a finite dataset as shown below.
12 | */
13 |
14 |
15 | }
16 |
17 |
18 | class Dictionary {
19 |
20 | private int[] arr;
21 |
22 | public Dictionary(int n) {
23 | this.arr = new int[n];
24 | }
25 |
26 | public void insert(int el) {
27 | this.arr[el - 1] = el;
28 | }
29 |
30 | public int search(int el) {
31 | return this.arr[el - 1];
32 | }
33 |
34 |
35 | public void delete(int el) {
36 | this.arr[el - 1] = -1;
37 | }
38 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P02.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.LinkedList;
4 | import java.util.List;
5 | import java.util.NoSuchElementException;
6 |
7 | public class P02 {
8 |
9 | public static T secondLast(List list) {
10 | if (list.size() < 2) {
11 | throw new NoSuchElementException("Can't find secondLast element from a list with less than 2 elements");
12 | }
13 | return list.get(list.size() - 2);
14 | }
15 |
16 | public static T secondLastRecursion(LinkedList list) {
17 | if (list.size() < 2) {
18 | throw new NoSuchElementException("Can't find secondLast element from a list with less than 2 elements");
19 | }
20 | if (list.size() == 2) {
21 | return list.getFirst();
22 | }
23 | return secondLastRecursion(new LinkedList<>(list.subList(1, list.size())));
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P12.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.AbstractMap.SimpleEntry;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.stream.Stream;
7 |
8 | import static java.util.stream.Collectors.toList;
9 |
10 | /**
11 | * (**) Decode a run-length encoded list.
12 | *
13 | * decode(Arrays.asList((4, "a"), "b", (2, "c"), (2, "a"), "d", (4, "e")))
14 | *
15 | */
16 | public class P12 {
17 |
18 | public static List decode(List encoded) {
19 | return encoded.stream().flatMap(e -> {
20 | if (e instanceof SimpleEntry) {
21 | SimpleEntry entry = (SimpleEntry) e;
22 | return Collections.nCopies(entry.getKey(), entry.getValue()).stream();
23 | }
24 | return Stream.of((T) e);
25 | }).collect(toList());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P33Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.AbstractMap.SimpleEntry;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.core.IsCollectionContaining.hasItems;
9 | import static org.junit.Assert.assertThat;
10 |
11 | public class P33Test {
12 |
13 | @Test
14 | public void shouldFindPrimeFactorsOf315() throws Exception {
15 | List> primeFactors = P33.primeFactorsMult(315);
16 | assertThat(primeFactors, hasItems(new SimpleEntry<>(3, 2), new SimpleEntry<>(5, 1), new SimpleEntry<>(7, 1)));
17 | }
18 |
19 | @Test
20 | public void shouldFindPrimeFactorsOf33() throws Exception {
21 | List> primeFactors = P33.primeFactorsMult(33);
22 | assertThat(primeFactors, hasItems(new SimpleEntry<>(3, 1), new SimpleEntry<>(11, 1)));
23 | }
24 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P19.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.annotation.tailrec
4 |
5 | /**
6 | * (**) Rotate a list N places to the left
7 | */
8 | object P19 {
9 |
10 | /*
11 | Using split function defined in P17
12 | */
13 | def rotate[T](list: List[T], n: Int): List[T] = {
14 | val (first, second) = P17.split(list, makeNPositive(list, n))
15 | second ++: first
16 | }
17 |
18 | /*
19 | Using recursion
20 | */
21 | def rotateR[T](list: List[T], n: Int): List[T] = {
22 | @tailrec
23 | def rotate(list: List[T], result: List[T], cur: Int, n: Int): List[T] = list match {
24 | case x :: xs if cur < n => rotate(xs, result :+ x, cur + 1, n)
25 | case l => l ++ result
26 | }
27 | rotate(list, List(), 0, makeNPositive(list, n))
28 | }
29 |
30 | private def makeNPositive[T](list: List[T], n: Int): Int = if (n < 0) list.length + n else n
31 |
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/tadm/ch03/Problem3_2.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch03;
2 |
3 | import java.util.LinkedList;
4 | import java.util.List;
5 | import java.util.Stack;
6 |
7 | /**
8 | * Write a program to reverse the direction of a given singly-linked list.
9 | * In other words, after the reversal all pointers should now point backwards.
10 | * Your algorithm should take linear time.
11 | */
12 | public class Problem3_2 {
13 |
14 | public List reverse(List list) {
15 | /*
16 | Algorithm:
17 | 1. Maintain a stack
18 | 2. Iterate over all the elements in a list and put that on the stack
19 | 3. Then empty the stack into a new LinkedList
20 | */
21 | Stack stack = new Stack<>();
22 | list.forEach(stack::push);
23 | List reversed = new LinkedList<>();
24 | while (!stack.isEmpty()) {
25 | reversed.add(stack.pop());
26 | }
27 | return reversed;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/codegolf/AcronymMaker.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.codegolf;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | import static java.util.stream.Collectors.joining;
7 |
8 | /**
9 | * Your goal is to make a program that converts an input to its acronym.
10 | * Your input is guaranteed to have only letters and spaces. The input will have exactly one space between words.
11 | * You must output the acronym of the input.
12 | *
13 | * https://codegolf.stackexchange.com/questions/75448/making-an-acronym
14 | */
15 | public class AcronymMaker {
16 |
17 | private static final List STOP_WORDS = Arrays.asList("AND", "OR", "BY", "OF");
18 |
19 | public static String acronym(final String input) {
20 | return Arrays
21 | .stream(input.toUpperCase().split("\\s"))
22 | .filter(word -> !STOP_WORDS.contains(word))
23 | .map(w -> String.valueOf(w.charAt(0)))
24 | .collect(joining(""));
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P46Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes;
2 |
3 | import org.junit.Test;
4 |
5 | import static com.shekhargulati.ninetynine_problems._03_logic_and_codes.P46.and;
6 | import static com.shekhargulati.ninetynine_problems._03_logic_and_codes.P46.or;
7 | import static org.hamcrest.CoreMatchers.equalTo;
8 | import static org.hamcrest.CoreMatchers.is;
9 | import static org.junit.Assert.assertThat;
10 |
11 |
12 | public class P46Test {
13 |
14 | @Test
15 | public void shouldGenerateTruthTable() throws Exception {
16 | String table = P46.table((a, b) -> and(a, or(a, b)));
17 | String result = "A B result\n" +
18 | "true true true\n" +
19 | "true false true\n" +
20 | "false true false\n" +
21 | "false false false";
22 |
23 | assertThat(table, is(equalTo(result)));
24 | }
25 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/random/tree/Tree.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random.tree;
2 |
3 | import java.util.Objects;
4 |
5 | public class Tree {
6 |
7 | T item;
8 | Tree left;
9 | Tree right;
10 | Tree parent;
11 | }
12 |
13 | class TreeOperations {
14 |
15 | public > Tree search(Tree tree, T item) {
16 | if (Objects.equals(tree.item, item)) {
17 | return tree;
18 | }
19 | if (tree.item.compareTo(item) < 0) {
20 | return search(tree.left, item);
21 | } else {
22 | return search(tree.right, item);
23 | }
24 | }
25 |
26 | public T min(Tree tree) {
27 | if (tree.left == null) {
28 | return tree.item;
29 | }
30 | return min(tree.left);
31 | }
32 |
33 | public T max(Tree tree) {
34 | if (tree.right == null) {
35 | return tree.item;
36 | }
37 | return max(tree.right);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P13.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.AbstractMap.SimpleEntry;
4 | import java.util.LinkedList;
5 | import java.util.List;
6 | import java.util.Objects;
7 |
8 | /**
9 | * (**) Run-length encoding of a list (direct solution)
10 | */
11 | public class P13 {
12 |
13 | public static List> encode_direct(List list) {
14 | LinkedList> result = new LinkedList<>();
15 | String lastElem = null;
16 | for (String elem : list) {
17 | if (Objects.equals(lastElem, elem)) {
18 | SimpleEntry last = result.removeLast();
19 | result.add(new SimpleEntry<>(last.getKey() + 1, elem));
20 | } else {
21 | result.add(new SimpleEntry<>(1, elem));
22 | lastElem = elem;
23 | }
24 | }
25 | return result;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P16.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 |
4 | /**
5 | * (**) Drop every N'th element from a list
6 | * {{{
7 | * dropEveryNth(List("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), 3)
8 | * }}}
9 | */
10 | object P16 {
11 |
12 | /*
13 | n is one based.
14 | */
15 | def dropEveryNth[T](list: List[T], n: Int): List[T] = {
16 | if (n == 0) {
17 | list
18 | } else {
19 | list.zipWithIndex.withFilter(t => if ((t._2 + 1) % n == 0) false else true).map(_._1)
20 | }
21 | }
22 |
23 | def dropEveryNth_recursive[T](list: List[T], n: Int): List[T] = {
24 | def drop(list: List[T], n: Int, index: Int): List[T] = {
25 | list match {
26 | case x :: xs if index % n != 0 => x +: drop(xs, n, index + 1)
27 | case x :: xs if index % n == 0 => drop(xs, n, index + 1)
28 | case _ => Nil
29 | }
30 | }
31 |
32 | if (n == 0) list else drop(list, n, 1)
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/random/RandomProblem002.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random;
2 |
3 | /**
4 | * Given a text and a string pattern check if pattern exist in the text.
5 | */
6 | public class RandomProblem002 {
7 |
8 | public static boolean patternExistInText(String text, String pattern) {
9 | /*
10 | Algorithm:
11 | 1. Find length of text n
12 | 2. Find length of pattern m
13 | 3. Iterate over length of text
14 | 4. For each character of the text check if the pattern exist from the index to index + m
15 | 5. If number of characters equal the length of m, we have found the pattern.
16 | */
17 | int n = text.length();
18 | int m = pattern.length();
19 | for (int i = 0; i < n - m; i++) {
20 | int j = 0;
21 | while (j < m && text.charAt(i + j) == pattern.charAt(j)) {
22 | j++;
23 | }
24 | if (j == m) return true;
25 | }
26 | return false;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P20Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P20Test extends FunSpec with Matchers {
6 |
7 | describe("P20 spec") {
8 | it("should remove kth element from a list") {
9 | val result = P20.removeAt(List("a", "b", "c", "d"), 2)
10 | result._1 should equal(List("a", "c", "d"))
11 | result._2 should equal("b")
12 | }
13 | }
14 |
15 |
16 | describe("P20 spec 0 based") {
17 | it("should remove kth element from a list") {
18 | val result = P20.removeAt0(List("a", "b", "c", "d"), 1)
19 | result._1 should equal(List("a", "c", "d"))
20 | result._2 should equal("b")
21 | }
22 | }
23 |
24 |
25 | describe("P20 spec splitAt") {
26 | it("should remove kth element from a list") {
27 | val result = P20.removeAt_splitAt(List("a", "b", "c", "d"), 2)
28 | result._1 should equal(List("a", "c", "d"))
29 | result._2 should equal("b")
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P49Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 |
7 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
8 | import static org.junit.Assert.assertThat;
9 |
10 | public class P49Test {
11 |
12 | @Test
13 | public void shouldFindGrayCodeWhenNIs1() throws Exception {
14 | List graySequence = P49.gray(1);
15 | assertThat(graySequence, contains("0", "1"));
16 | }
17 |
18 | @Test
19 | public void shouldFindGrayCodeWhenNIs2() throws Exception {
20 | List graySequence = P49.gray(2);
21 | assertThat(graySequence, contains("00", "01", "11", "10"));
22 | }
23 |
24 | @Test
25 | public void shouldFindGrayCodeWhenNIs3() throws Exception {
26 | List graySequence = P49.gray(3);
27 | assertThat(graySequence, contains("000", "001", "011", "010", "110", "111", "101", "100"));
28 | }
29 |
30 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P08.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Objects;
6 |
7 | /**
8 | * (**) Eliminate consecutive duplicates of list elements
9 | * If a list contains repeated elements they should be replaced with a single copy of the element.
10 | * The order of the elements should not be changed.
11 | *
12 | *
13 | * compress(Arrays.asList(a,a,a,a,b,c,c,a,a,d,e,e,e,e))
14 | * [a,b,c,d,e]
15 | *
16 | */
17 | public class P08 {
18 |
19 | public static List compress(List list) {
20 | Objects.requireNonNull(list, "Please make sure list is not null");
21 | List result = new ArrayList<>();
22 | T lastElement = null;
23 | for (T e : list) {
24 | if (!Objects.equals(lastElement, e)) {
25 | result.add(e);
26 | }
27 | lastElement = e;
28 | }
29 | return result;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/java8/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.shekhargulati
7 | 99-problems
8 | 1.0-SNAPSHOT
9 | jar
10 |
11 |
12 | UTF-8
13 | 1.8
14 | 1.8
15 |
16 |
17 |
18 |
19 | junit
20 | junit
21 | 4.12
22 | test
23 |
24 |
25 | org.hamcrest
26 | hamcrest-all
27 | 1.3
28 | test
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/random/RandomProblem002Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random;
2 |
3 | import org.junit.Test;
4 |
5 | import java.nio.file.Files;
6 | import java.nio.file.Paths;
7 |
8 | import static java.util.stream.Collectors.joining;
9 | import static org.junit.Assert.assertFalse;
10 | import static org.junit.Assert.assertTrue;
11 |
12 | public class RandomProblem002Test {
13 |
14 | @Test
15 | public void shouldGiveTrueWhenPatternExistInText() throws Exception {
16 | String text = Files.lines(Paths.get("src", "test", "resources", "book.txt")).collect(joining());
17 | boolean patternExists = RandomProblem002.patternExistInText(text, "prudent");
18 | assertTrue(patternExists);
19 | }
20 |
21 | @Test
22 | public void shouldGiveFalseWhenPatternDoesNotExistInText() throws Exception {
23 | String text = Files.lines(Paths.get("src", "test", "resources", "book.txt")).collect(joining());
24 | boolean patternExists = RandomProblem002.patternExistInText(text, "awesome");
25 | assertFalse(patternExists);
26 | }
27 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P36.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import java.util.AbstractMap.SimpleEntry;
4 | import java.util.List;
5 | import java.util.stream.IntStream;
6 |
7 | import static java.util.stream.Collectors.toList;
8 |
9 | /**
10 | * (**) A list of Goldbach compositions.
11 | */
12 | public class P36 {
13 |
14 | public static List>> goldbach_list(IntStream range) {
15 | return range
16 | .filter(n -> n % 2 == 0)
17 | .filter(even -> even > 2)
18 | .mapToObj(even -> new SimpleEntry<>(even, P35.goldbach(even)))
19 | .collect(toList());
20 | }
21 |
22 | public static List>> goldbach_list1(IntStream range, int greaterThan) {
23 | return goldbach_list(range)
24 | .stream()
25 | .filter(g -> g.getValue().get(0) > greaterThan && g.getValue().get(1) > greaterThan)
26 | .collect(toList());
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/random/RandomProblem004.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random;
2 |
3 | /**
4 | * Functions corresponding to loops
5 | */
6 | public class RandomProblem004 {
7 |
8 | /**
9 | * f(n) = n*(n+1)/2
10 | */
11 | public static int sumOfNNumbers(int n) {
12 | int sum = 0;
13 | for (int i = 1; i <= n; i++) {
14 | sum += i;
15 | }
16 | return sum;
17 | }
18 |
19 |
20 | /**
21 | * f(n) = n*n
22 | */
23 | public static int squareOfANumber(int n) {
24 | int square = 0;
25 | for (int i = 1; i <= n; i++) {
26 | for (int j = 1; j <= n; j++) {
27 | square += 1;
28 | }
29 | }
30 | return square;
31 | }
32 |
33 | /**
34 | * f(n) = n*(n+1)/2
35 | */
36 | public static int sumOfNNumbers1(int n) {
37 | int sum = 0;
38 | for (int i = 1; i <= n; i++) {
39 | for (int j = 1; j <= i; j++) {
40 | sum += 1;
41 | }
42 | }
43 |
44 | return sum;
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P20.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | /**
8 | * (*) Remove the K'th element from a list
9 | */
10 | public class P20 {
11 |
12 | public static Object[] removeAt(List list, int k) {
13 | List input = new ArrayList<>(list);
14 | T kth = input.remove(k - 1);
15 | return new Object[]{input, kth};
16 | }
17 |
18 | public static Object[] removeAt0(List list, int k) {
19 | List input = new ArrayList<>(list);
20 | T kth = input.remove(k);
21 | return new Object[]{input, kth};
22 | }
23 |
24 | public static Object[] removeAt_splitAt(List list, int k) {
25 | Map> split = P17.split(list, k);
26 | List first = split.get(true);
27 | List second = split.get(false);
28 | T kth = first.remove(k - 1);
29 | first.addAll(second);
30 | return new Object[]{first, kth};
31 |
32 | }
33 | }
34 |
35 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P21.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | /**
7 | * (*) Insert an element at a given position into a list
8 | */
9 | public class P21 {
10 |
11 | public static List insertAt(List list, int pos, T t) throws IllegalArgumentException {
12 | if (pos < 1) {
13 | throw new IllegalArgumentException("pos can't be less than 1");
14 | }
15 | list.add((pos - 1), t);
16 | return list;
17 | }
18 |
19 |
20 | public static List insertAt_split(List list, int pos, T t) throws IllegalArgumentException {
21 | if (pos < 1) {
22 | throw new IllegalArgumentException("pos can't be less than 1");
23 | }
24 |
25 | Map> split = P17.split(list, pos);
26 | List first = split.get(true);
27 | List second = split.get(false);
28 | first.add(pos - 1, t);
29 |
30 | first.addAll(second);
31 | return first;
32 | }
33 |
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P49.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes;
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.Stream;
8 |
9 | import static java.util.stream.Collectors.toList;
10 |
11 | /**
12 | * (**) Gray code.
13 | * An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example,
14 | * n = 1: C(1) = ['0','1'].
15 | * n = 2: C(2) = ['00','01','11','10'].
16 | * n = 3: C(3) = ['000','001','011','010','110','111','101','100'].
17 | */
18 | public class P49 {
19 |
20 | public static List gray(int n) {
21 | if (n == 1) {
22 | return Arrays.asList("0", "1");
23 | }
24 | List original = gray(n - 1);
25 | List reversed = new ArrayList<>(original);
26 | Collections.reverse(reversed);
27 | return Stream.concat(original.stream().map(s -> "0" + s), reversed.stream().map(s -> "1" + s)).collect(toList());
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/random/RandomProblem003.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random;
2 |
3 | /**
4 | * Perform matrix multiplication of two arrays.
5 | * Matrix multiplication of array A of size nxm and array B of size mxp is an array of size nxp
6 | */
7 | public class RandomProblem003 {
8 |
9 | public static int[][] matrixMultiplication(int[][] a, int[][] b) {
10 | int rowsA = a.length;
11 | int colsA = a[0].length;
12 | int rowsB = b.length;
13 | int colsB = b[0].length;
14 |
15 | if (colsA != rowsB) {
16 | throw new IllegalArgumentException("Can't perform matrix calculation on matrix with given sizes");
17 | }
18 | int[][] result = new int[rowsA][colsB];
19 |
20 | for (int i = 0; i < rowsA; i++) {
21 | for (int j = 0; j < colsB; j++) {
22 | int fValue = 0;
23 | for (int k = 0; k < colsA; k++) {
24 | fValue += a[i][k] * b[k][j];
25 | }
26 | result[i][j] = fValue;
27 | }
28 | }
29 | return result;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P04Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P04Test extends FunSpec with Matchers {
6 |
7 | describe("size of a list (built-in)") {
8 | it("should be zero when list is empty") {
9 | P04.length(List()) should be(0)
10 | }
11 |
12 | it("should be 5 when list has five elements") {
13 | P04.length(List(1, 2, 3, 4, 5)) should be(5)
14 | }
15 | }
16 |
17 | describe("size of a list (built-in another)") {
18 | it("should be zero when list is empty") {
19 | P04.length1(List()) should be(0)
20 | }
21 |
22 | it("should be 5 when list has five elements") {
23 | P04.length1(List(1, 2, 3, 4, 5)) should be(5)
24 | }
25 | }
26 |
27 | describe("size of a list (recursive)") {
28 | it("should be zero when list is empty") {
29 | P04.lengthRecursive(List()) should be(0)
30 | }
31 |
32 | it("should be 5 when list has five elements") {
33 | P04.lengthRecursive(List(1, 2, 3, 4, 5)) should be(5)
34 | }
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P35Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 |
7 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
8 | import static org.hamcrest.core.IsCollectionContaining.hasItems;
9 | import static org.junit.Assert.assertThat;
10 |
11 | public class P35Test {
12 |
13 | @Test
14 | public void _8_isthesumof_3_and_5() throws Exception {
15 | List numbers = P35.goldbach(8);
16 | assertThat(numbers, hasSize(2));
17 | assertThat(numbers, hasItems(3, 5));
18 | }
19 |
20 | @Test
21 | public void _4_isthesumof_2_and_2() throws Exception {
22 | List numbers = P35.goldbach(4);
23 | assertThat(numbers, hasSize(2));
24 | assertThat(numbers, hasItems(2, 2));
25 | }
26 |
27 | @Test
28 | public void _28_isthesumof_5_and_23() throws Exception {
29 | List numbers = P35.goldbach(28);
30 | assertThat(numbers, hasSize(2));
31 | assertThat(numbers, hasItems(5, 23));
32 | }
33 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 Shekhar Gulati
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P06Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 |
7 | import static com.shekhargulati.ninetynine_problems._01_lists.P06.isPalindrome;
8 | import static org.junit.Assert.assertFalse;
9 | import static org.junit.Assert.assertTrue;
10 |
11 | public class P06Test {
12 |
13 | @Test
14 | public void shouldReturnTrueWhenListIsPalindrome() throws Exception {
15 | assertTrue(isPalindrome(Arrays.asList("x", "a", "m", "a", "x")));
16 | }
17 |
18 | @Test
19 | public void shouldReturnFalseWhenListIsNotPalindrome() throws Exception {
20 | assertFalse(isPalindrome(Arrays.asList(1, 2, 3, 4, 5)));
21 | }
22 |
23 | @Test
24 | public void shouldReturnTrueWhenListIsPalindrome_IntStream() throws Exception {
25 | assertTrue(isPalindrome(Arrays.asList("x", "a", "m", "a", "x")));
26 | }
27 |
28 | @Test
29 | public void shouldReturnFalseWhenListIsNotPalindrome_IntStream() throws Exception {
30 | assertFalse(isPalindrome(Arrays.asList(1, 2, 3, 4, 5)));
31 | }
32 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P31.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | /**
4 | * A prime number is a natural number greater than 1 that is only divisible by 1 and itself. All other numbers are Composite.
5 | * (**) Determine whether a given integer number is prime.
6 | */
7 | object P31 {
8 |
9 | def isPrime(number: Int): Boolean =
10 | if (number < 2)
11 | false
12 | else
13 | !((2 to Math.sqrt(number).toInt) exists (f => number % f == 0))
14 |
15 |
16 | /**
17 | * One of the ways to find a number is prime by finding out all factors of a number below its square root.
18 | * Give n = a*b, if 1 < a <= b < n, then a <= √n
19 | *
20 | * Complexity of this algorithm is O(√n)
21 | */
22 | def isPrime_trialDivision(number: Int): Boolean = {
23 | if (number < 2) {
24 | throw new IllegalArgumentException("Prime numbers can only be greater than equal to 2")
25 | } else {
26 | val factors = for (f <- 2 to Math.sqrt(number).toInt if number % f == 0) yield f
27 | if (factors.nonEmpty) false else true
28 | }
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P28.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | /**
4 | * (**) Sorting a list of lists according to length of sublists
5 | */
6 | object P28 {
7 |
8 | /*
9 | We suppose that a list (InList) contains elements that are lists themselves.
10 | The objective is to sort the elements of InList according to their length.
11 | E.g. short lists first, longer lists later, or vice versa
12 | */
13 | def lsort[T](list: List[List[T]]): List[List[T]] = list.sortWith((l1, l2) => l1.length - l2.length < 0)
14 |
15 | /*
16 | Again, we suppose that a list (InList) contains elements that are lists themselves.
17 | But this time the objective is to sort the elements of InList according to their length frequency;
18 | i.e. in the default, where sorting is done ascending order, lists with rare lengths are placed first, others with a more frequent length come later.
19 | */
20 | def lfsort[T](list: List[List[T]]): List[List[T]] =
21 | lsort(list)
22 | .groupBy(l => l.length).values.toList
23 | .sortWith((l1, l2) => l1.length - l2.length < 0)
24 | .flatten
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P49.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes
2 |
3 | /**
4 | * (**) Gray code.
5 | * An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example,
6 | * n = 1: C(1) = ['0','1'].
7 | * n = 2: C(2) = ['00','01','11','10'].
8 | * n = 3: C(3) = ['000','001','011','010','110','111','101','100'].
9 | */
10 | object P49 {
11 |
12 |
13 | def gray(n: Int): List[String] = {
14 | /*
15 | Algorithm:
16 | 1. Start with a gray code sequence of n-1
17 | 2. Reverse the list
18 | 3. Concatenate original and reverse lists
19 | 4. Prepend original list with 0 and reverse list with 1
20 | */
21 | if (n == 1) {
22 | List("0", "1")
23 | } else {
24 | val original = gray(n - 1)
25 | val reversed = original.reverse
26 | original.map("0" + _) ++ reversed.map("1" + _)
27 | }
28 | }
29 |
30 |
31 | def binarySeries(n: Int): List[String] = n match {
32 | case 1 => List("0", "1")
33 | case _ => List("0", "1").flatMap(x => binarySeries(n - 1).map(x + _))
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P01Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.LinkedList;
6 |
7 | import static com.shekhargulati.ninetynine_problems._01_lists.CollectionUtils.linkedList;
8 | import static java.util.Arrays.asList;
9 | import static org.hamcrest.CoreMatchers.equalTo;
10 | import static org.hamcrest.CoreMatchers.is;
11 | import static org.junit.Assert.assertThat;
12 |
13 | public class P01Test {
14 |
15 | @Test
16 | public void shouldFindLastElementFromAListOfAlphabets() throws Exception {
17 | assertThat(P01.last(asList("a", "b", "c", "d")), is(equalTo("d")));
18 | }
19 |
20 | @Test
21 | public void shouldFindLastElementFromALinkedListOfAlphabets() throws Exception {
22 | LinkedList alphabets = linkedList("a", "b", "c", "d");
23 | assertThat(P01.last(alphabets), is(equalTo("d")));
24 | }
25 |
26 | @Test
27 | public void shouldFindLastElementFromAListOfAlphabetsUsingRecursion() throws Exception {
28 | assertThat(P01.lastRecursive(asList("a", "b", "c", "d")), is(equalTo("d")));
29 | }
30 |
31 |
32 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P08Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 |
7 | import static java.util.Arrays.asList;
8 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
9 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P08Test {
13 |
14 | @Test
15 | public void shouldRemoveConsecutiveDuplicatesInAList() throws Exception {
16 | List compressedList = P08.compress(asList("a", "a", "a", "a", "b", "c", "c", "d", "e", "e", "e", "e"));
17 | assertThat(compressedList, hasSize(5));
18 | assertThat(compressedList, contains("a", "b", "c", "d", "e"));
19 | }
20 |
21 | @Test
22 | public void shouldNotRemoveNonConsecutiveSimilarElementsFromAList() throws Exception {
23 | List compressedList = P08.compress(asList("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"));
24 | assertThat(compressedList, hasSize(6));
25 | assertThat(compressedList, contains("a", "b", "c", "a", "d", "e"));
26 | }
27 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P04Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.Collections;
7 |
8 | import static org.hamcrest.CoreMatchers.equalTo;
9 | import static org.hamcrest.CoreMatchers.is;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P04Test {
13 |
14 | @Test
15 | public void listOfEmptyListShouldBe0() throws Exception {
16 | int length = P04.length(Collections.emptyList());
17 | assertThat(length, is(equalTo(0)));
18 | }
19 |
20 | @Test
21 | public void shouldFindListOfNonEmptyList() throws Exception {
22 | assertThat(P04.length(Arrays.asList(1, 2, 3, 4, 5)), is(equalTo(5)));
23 | }
24 |
25 | @Test
26 | public void listOfEmptyListShouldBe0_Recursive() throws Exception {
27 | int length = P04.lengthRecursive(Collections.emptyList());
28 | assertThat(length, is(equalTo(0)));
29 | }
30 |
31 | @Test
32 | public void shouldFindListOfNonEmptyList_Recursive() throws Exception {
33 | assertThat(P04.lengthRecursive(Arrays.asList(1, 2, 3, 4, 5)), is(equalTo(5)));
34 | }
35 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P34.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
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 list of prime numbers.
11 | */
12 | public class P34 {
13 |
14 | public static List primeNumbers(IntStream range) {
15 | return range.filter(P31::isPrime).boxed().collect(Collectors.toList());
16 | }
17 |
18 | public static List primeNumbers_sieve(final int start, final int end) {
19 | boolean[] primes = new boolean[end + 1];
20 | Arrays.fill(primes, true);
21 | for (int i = 2; i < primes.length; i++) {
22 | for (int j = i + 1; j < primes.length; j++) {
23 | primes[j] = !primes[j] || j % i == 0 ? false : true;
24 | }
25 | }
26 |
27 | List primeNumbers = new ArrayList<>();
28 | for (int i = start; i < primes.length; i++) {
29 | if (primes[i]) {
30 | primeNumbers.add(i);
31 | }
32 | }
33 | return primeNumbers;
34 | }
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P03Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.LinkedList;
7 | import java.util.List;
8 |
9 | import static com.shekhargulati.ninetynine_problems._01_lists.CollectionUtils.linkedList;
10 | import static org.hamcrest.CoreMatchers.equalTo;
11 | import static org.hamcrest.CoreMatchers.is;
12 | import static org.junit.Assert.assertThat;
13 |
14 | public class P03Test {
15 |
16 | @Test
17 | public void shouldFindKthElementFromAList() throws Exception {
18 | List numbers = Arrays.asList(1, 2, 3, 4, 5);
19 | assertThat(P03.kth(numbers, 2), is(equalTo(3)));
20 | }
21 |
22 | @Test
23 | public void shouldFindKthElementFromAListRecursive() throws Exception {
24 | LinkedList numbers = linkedList(1, 2, 3, 4, 5);
25 | assertThat(P03.kthRecursive(numbers, 2), is(equalTo(3)));
26 | }
27 |
28 | @Test
29 | public void shouldFindKthElementFromAList_LinkedListAndStream() throws Exception {
30 | List numbers = Arrays.asList(1, 2, 3, 4, 5);
31 | assertThat(P03.kthStream(numbers, 2), is(equalTo(3)));
32 | }
33 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P11Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.AbstractMap.SimpleEntry;
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import static org.hamcrest.CoreMatchers.equalTo;
10 | import static org.hamcrest.CoreMatchers.is;
11 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
12 | import static org.junit.Assert.assertThat;
13 |
14 | public class P11Test {
15 |
16 | @Test
17 | public void shouldEncodeAList() throws Exception {
18 | List encodedList = P11.encode_modified(Arrays.asList("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"));
19 | assertThat(encodedList, hasSize(6));
20 | assertThat(encodedList.get(0), is(equalTo(new SimpleEntry<>(4, "a"))));
21 | assertThat(encodedList.get(1), is(equalTo("b")));
22 | assertThat(encodedList.get(2), is(equalTo(new SimpleEntry<>(2, "c"))));
23 | assertThat(encodedList.get(3), is(equalTo(new SimpleEntry<>(2, "a"))));
24 | assertThat(encodedList.get(4), is(equalTo("d")));
25 | assertThat(encodedList.get(5), is(equalTo(new SimpleEntry<>(4, "e"))));
26 | }
27 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P31Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P31Test extends FunSpec with Matchers {
6 |
7 | describe("Problem 31 Spec") {
8 |
9 | it("7 is a prime number") {
10 | val prime = P31.isPrime(7)
11 | prime should be(true)
12 | }
13 |
14 | it("10 is not prime number") {
15 | val prime = P31.isPrime(10)
16 | prime should be(false)
17 | }
18 | }
19 |
20 | describe("Problem 31 Spec (trial division)") {
21 | it("7 is a prime number") {
22 | val prime = P31.isPrime_trialDivision(7)
23 | prime should be(true)
24 | }
25 |
26 | it("10 is not prime number") {
27 | val prime = P31.isPrime_trialDivision(10)
28 | prime should be(false)
29 | }
30 |
31 | it("15,485,863 is last prime below one million") {
32 | val prime = P31.isPrime_trialDivision(15485863)
33 | prime should be(true)
34 | }
35 |
36 | it("86,028,121 is the last prime below five million") {
37 | val i: Int = 86028121
38 | val prime = P31.isPrime_trialDivision(86028121)
39 | prime should be(true)
40 | }
41 |
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P09.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Objects;
6 |
7 | /**
8 | * (**) Pack consecutive duplicates of list elements into sublists
9 | * If a list contains repeated elements they should be placed in separate sublists.
10 | *
11 | *
12 | * pack(Arrays.asList("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"))
13 | * [["a","a","a","a"],["b"],["c","c"],["a","a"],["d"],["e","e","e","e"]]
14 | *
15 | */
16 | public class P09 {
17 |
18 | /*
19 | Simple approach using for-each loop
20 | */
21 | public static List> pack(List list) {
22 | T lastElement = null;
23 | List> packedList = new ArrayList<>();
24 | List elements = new ArrayList<>();
25 | for (T el : list) {
26 | if (!Objects.equals(lastElement, el)) {
27 | elements = new ArrayList<>();
28 | packedList.add(elements);
29 | }
30 | elements.add(el);
31 | lastElement = el;
32 | }
33 | return packedList;
34 | }
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P02Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import java.util.NoSuchElementException
4 |
5 | import org.scalatest.{FunSpec, Matchers}
6 |
7 | class P02Test extends FunSpec with Matchers {
8 |
9 | describe("SecondLast Element in a List Spec") {
10 | it("should give first element when list has only two elements") {
11 | val numbers = List(10, 6)
12 | P02.secondLast(numbers) should be(10)
13 | }
14 |
15 | it("should give second last element when list has more than two elements") {
16 | val numbers = List(1, 2, 11, 4, 5, 8, 10, 6)
17 | P02.secondLast(numbers) should be(10)
18 | }
19 |
20 | it("should throw exception when list is empty") {
21 | val thrown = the[NoSuchElementException] thrownBy P02.secondLast(List())
22 | thrown.getMessage should equal("Can't find secondLast element from a list with less than 2 elements")
23 | }
24 |
25 | it("should throw exception when list has one element") {
26 | val thrown = the[NoSuchElementException] thrownBy P02.secondLast(List(1))
27 | thrown.getMessage should equal("Can't find secondLast element from a list with less than 2 elements")
28 | }
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P19Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.CoreMatchers.equalTo;
9 | import static org.junit.Assert.assertThat;
10 |
11 | public class P19Test {
12 |
13 | @Test
14 | public void shouldRotateAListByThreeElementsWhenNIs3() throws Exception {
15 | List rotated = P19.rotate(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h"), 3);
16 | assertThat(rotated, equalTo(Arrays.asList("d", "e", "f", "g", "h", "a", "b", "c")));
17 | }
18 |
19 | @Test
20 | public void shouldReturnSameListWhenNIs0() throws Exception {
21 | List rotated = P19.rotate(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h"), 0);
22 | assertThat(rotated, equalTo(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h")));
23 | }
24 |
25 | @Test
26 | public void shouldRotateWhenNIsNegative() throws Exception {
27 | List rotated = P19.rotate(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h"), -2);
28 | assertThat(rotated, equalTo(Arrays.asList("g", "h", "a", "b", "c", "d", "e", "f")));
29 | }
30 |
31 |
32 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P05Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.ArrayDeque;
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import static com.shekhargulati.ninetynine_problems._01_lists.CollectionUtils.arrayDeque;
10 | import static org.hamcrest.CoreMatchers.equalTo;
11 | import static org.hamcrest.CoreMatchers.is;
12 | import static org.junit.Assert.assertThat;
13 |
14 | public class P05Test {
15 |
16 | @Test
17 | public void shouldReverseAList() throws Exception {
18 | List numbers = Arrays.asList(1, 2, 3, 4, 5);
19 | assertThat(P05.reverse(numbers), is(equalTo(Arrays.asList(5, 4, 3, 2, 1))));
20 | }
21 |
22 | @Test
23 | public void shouldReverseAList_IntStream() throws Exception {
24 | List numbers = Arrays.asList(1, 2, 3, 4, 5);
25 | assertThat(P05.reverse_IntStream(numbers), is(equalTo(Arrays.asList(5, 4, 3, 2, 1))));
26 | }
27 |
28 | @Test
29 | public void shouldReverseAList_Stream() throws Exception {
30 | ArrayDeque numbers = arrayDeque(1, 2, 3, 4, 5);
31 | assertThat(P05.reverse_customStream(numbers), is(equalTo(Arrays.asList(5, 4, 3, 2, 1))));
32 | }
33 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P13.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.annotation.tailrec
4 |
5 | /**
6 | * (**) Run-length encoding of a list (direct solution).
7 | *
8 | * {{{
9 | * encode_direct([a,a,a,a,b,c,c,a,a,d,e,e,e,e]).
10 | * }}}
11 | */
12 | object P13 {
13 |
14 | /**
15 | * Using dropWhile method and tail recursion
16 | */
17 | def encode_direct[T](list: List[T]): List[Any] = {
18 | @tailrec
19 | def encode(list: List[T], result: List[Any]): List[Any] = list match {
20 | case x :: xs =>
21 | val remaining = xs.dropWhile(_ == x)
22 | val duplicateCount: Int = list.length - remaining.length
23 | duplicateCount match {
24 | case 1 => encode(remaining, result :+ x)
25 | case _ => encode(remaining, result :+(duplicateCount, x))
26 | }
27 | case Nil =>
28 | result
29 | }
30 | encode(list, List())
31 | }
32 |
33 | def encode_direct_span[T](list: List[T]): List[Any] = list match {
34 | case x :: xs =>
35 | val (consecutiveDuplicates, remaining) = xs.span(_ == x)
36 | (consecutiveDuplicates.length + 1, x) +: encode_direct_span(remaining)
37 | case Nil => Nil
38 | }
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P21.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.annotation.tailrec
4 | import scala.collection.mutable
5 |
6 | /**
7 | * (*) Insert an element at a given position into a list
8 | */
9 | object P21 {
10 |
11 | def insertAt[T](list: List[T], pos: Int, t: T): List[T] = {
12 | if (pos < 1) {
13 | throw new IllegalArgumentException("position should be greater than 0")
14 | }
15 | val (first, second) = list.splitAt(pos - 1)
16 | (first :+ t) ++ second
17 | }
18 |
19 | def insertAt_inbuilt[T](list: List[T], pos: Int, t: T): List[T] = {
20 | if (pos < 1) {
21 | throw new IllegalArgumentException("position should be greater than 0")
22 | }
23 | val listBuffer: mutable.Buffer[T] = list.toBuffer
24 | listBuffer.insert(pos - 1, t)
25 | listBuffer.toList
26 | }
27 |
28 | def insertAt_recursion[T](list: List[T], pos: Int, t: T): List[T] = {
29 | @tailrec
30 | def insertAt(remaining: List[T], first: List[T], cur: Int): List[T] = remaining match {
31 | case xs if cur == pos => (first :+ t) ++ remaining
32 | case x :: xs => insertAt(xs, first :+ x, cur + 1)
33 | case _ => Nil
34 | }
35 | insertAt(list, List(), 1)
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P07.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.stream.Stream;
6 |
7 | import static java.util.stream.Collectors.toList;
8 |
9 | /**
10 | * (**) Flatten a nested list structure
11 | *
12 | * Transform a list, possibly holding lists as elements into a 'flat' list by replacing each list with its elements (recursively).
13 | *
14 | */
15 | public class P07 {
16 |
17 | public static List flatten(List> list, Class elementType) {
18 | List flatten = new ArrayList<>();
19 | list.forEach(e -> {
20 | if (e instanceof List) {
21 | flatten.addAll(flatten((List>) e, elementType));
22 | } else {
23 | flatten.add((T) e);
24 | }
25 | });
26 | return flatten;
27 | }
28 |
29 | public static List flatten_stream(List> list, Class elementType) {
30 | return list
31 | .stream()
32 | .flatMap(e -> e instanceof List ? flatten_stream(((List>) e), elementType).stream() : Stream.of(e))
33 | .map(e -> (T) e)
34 | .collect(toList());
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P10Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.AbstractMap.SimpleEntry;
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | import static org.hamcrest.CoreMatchers.equalTo;
10 | import static org.hamcrest.CoreMatchers.is;
11 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
12 | import static org.junit.Assert.assertThat;
13 |
14 | public class P10Test {
15 |
16 | @Test
17 | public void shouldEncodeAList() throws Exception {
18 | List> encodedList = P10.encode(Arrays.asList("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"));
19 | assertThat(encodedList, hasSize(6));
20 | assertThat(encodedList.get(0), is(equalTo(new SimpleEntry<>(4, "a"))));
21 | assertThat(encodedList.get(1), is(equalTo(new SimpleEntry<>(1, "b"))));
22 | assertThat(encodedList.get(2), is(equalTo(new SimpleEntry<>(2, "c"))));
23 | assertThat(encodedList.get(3), is(equalTo(new SimpleEntry<>(2, "a"))));
24 | assertThat(encodedList.get(4), is(equalTo(new SimpleEntry<>(1, "d"))));
25 | assertThat(encodedList.get(5), is(equalTo(new SimpleEntry<>(4, "e"))));
26 | }
27 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P13Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 |
4 | import org.junit.Test;
5 |
6 | import java.util.AbstractMap.SimpleEntry;
7 | import java.util.Arrays;
8 | import java.util.List;
9 |
10 | import static org.hamcrest.CoreMatchers.equalTo;
11 | import static org.hamcrest.CoreMatchers.is;
12 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
13 | import static org.junit.Assert.assertThat;
14 |
15 | public class P13Test {
16 |
17 | @Test
18 | public void shouldEncodeAList() throws Exception {
19 | List> encodedList = P13.encode_direct(Arrays.asList("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"));
20 | assertThat(encodedList, hasSize(6));
21 | assertThat(encodedList.get(0), is(equalTo(new SimpleEntry<>(4, "a"))));
22 | assertThat(encodedList.get(1), is(equalTo(new SimpleEntry<>(1, "b"))));
23 | assertThat(encodedList.get(2), is(equalTo(new SimpleEntry<>(2, "c"))));
24 | assertThat(encodedList.get(3), is(equalTo(new SimpleEntry<>(2, "a"))));
25 | assertThat(encodedList.get(4), is(equalTo(new SimpleEntry<>(1, "d"))));
26 | assertThat(encodedList.get(5), is(equalTo(new SimpleEntry<>(4, "e"))));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P23Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
9 | import static org.junit.Assert.assertThat;
10 |
11 | public class P23Test {
12 |
13 | @Test
14 | public void shouldReturnAListOfThreeRandomSelectedElements() throws Exception {
15 | List result = P23.randomSelect(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h"), 3);
16 | System.out.println(result);
17 | assertThat(result, hasSize(3));
18 | }
19 |
20 | @Test
21 | public void shouldReturnAListOfThreeRandomSelectedElements_recursive() throws Exception {
22 | List result = P23.randomSelectR(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h"), 3);
23 | System.out.println(result);
24 | assertThat(result, hasSize(3));
25 | }
26 |
27 |
28 | @Test
29 | public void shouldReturnAListOfThreeRandomSelectedElements_imperative() throws Exception {
30 | List result = P23.randomSelect_imperative(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h"), 3);
31 | System.out.println(result);
32 | assertThat(result, hasSize(3));
33 | }
34 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P26Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P26Test extends FunSpec with Matchers {
6 |
7 | describe("P26 Spec") {
8 | it("should generate all combinations of size K from N elements of a list") {
9 | val combinations = P26.combinations(List("a", "b", "c", "d", "e", "f"), 3)
10 | println(combinations)
11 | combinations should have length 20
12 | }
13 | }
14 |
15 |
16 | describe("P26 Spec recursive") {
17 | it("should generate all combinations of size K from N elements of a list") {
18 | val combinations = P26.combinations1(List("a", "b", "c", "d", "e", "f"), 3)
19 | println(combinations)
20 | combinations should have length 20
21 | }
22 |
23 | it("should generate all combinations of size 2 from 3 elements of a list") {
24 | val combinations = P26.combinations1(List("a", "b", "c"), 2)
25 | println(combinations)
26 | combinations should have length 3
27 | }
28 |
29 | it("should generate all combinations of size 3 from 3 elements of a list") {
30 | val combinations = P26.combinations1(List("a", "b", "c"), 3)
31 | println(combinations)
32 | combinations should have length 1
33 | }
34 | }
35 |
36 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/fortytwo_problems/Problem01.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.fortytwo_problems;
2 |
3 | import java.util.AbstractMap.SimpleEntry;
4 | import java.util.ArrayList;
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | /**
9 | * Taken an input a sequence of 2n real numbers.
10 | * Design an O(nlogn) algorithm that partitions the numbers into n pairs,
11 | * with the property that the partition minimizes the sum of maximum sum of a pair.
12 | */
13 | public class Problem01 {
14 |
15 | public static List> pairs(int[] numbers) {
16 | /*
17 | Algorithm:
18 | 1. Sort the numbers
19 | 2. Iterate over half the list and put first number and last in a pair
20 |
21 | Other algorithm feasible
22 | 1. Sort numbers
23 | 2. Create reverse numbers
24 | 3. Take first half of zip of numbers and reverse
25 | let l = sort [1,9,5,3]
26 | let r = reverse l
27 | take (length l `div` 2) (zip l r)
28 | */
29 | Arrays.sort(numbers);
30 | List> pairs = new ArrayList<>();
31 | for (int i = 0; i < numbers.length / 2; i++) {
32 | pairs.add(new SimpleEntry<>(numbers[i], numbers[(numbers.length - i) - 1]));
33 | }
34 | return pairs;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P13Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P13Test extends FunSpec with Matchers {
6 |
7 | describe("P13 Spec") {
8 | it("should perform run-length encoding") {
9 | val encodedList: List[Any] = P13.encode_direct(List("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"))
10 | encodedList should have size 6
11 | encodedList(0) should equal((4, "a"))
12 | encodedList(1) should equal("b")
13 | encodedList(2) should equal((2, "c"))
14 | encodedList(3) should equal((2, "a"))
15 | encodedList(4) should equal("d")
16 | encodedList(5) should equal((4, "e"))
17 | }
18 | }
19 |
20 | describe("P13 Spec(span)") {
21 | it("should perform run-length encoding") {
22 | val encodedList: List[Any] = P13.encode_direct_span(List("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"))
23 | encodedList should have size 6
24 | encodedList(0) should equal((4, "a"))
25 | encodedList(1) should equal(1, "b")
26 | encodedList(2) should equal((2, "c"))
27 | encodedList(3) should equal((2, "a"))
28 | encodedList(4) should equal(1, "d")
29 | encodedList(5) should equal((4, "e"))
30 | }
31 | }
32 |
33 |
34 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_02_arithmetic/P34Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P34Test extends FunSpec with Matchers {
6 |
7 | describe("P34 Spec") {
8 | it("should list 2,3,5,7 as prime numbers between 0 and 10") {
9 | val primeNumbers = P34.primeNumbers(0 to 10)
10 | primeNumbers should have length 4
11 | primeNumbers should be(List(2, 3, 5, 7))
12 | }
13 |
14 | it("should list 7, 11, 13, 17, 19, 23, 29, 31 as prime numbers between 7 and 31") {
15 | val primeNumbers = P34.primeNumbers(7 to 31)
16 | primeNumbers should have length 8
17 | primeNumbers should be(List(7, 11, 13, 17, 19, 23, 29, 31))
18 | }
19 |
20 | }
21 |
22 | describe("P34 Spec sieve") {
23 | it("should list 2,3,5,7 as prime numbers between 0 and 10") {
24 | val primeNumbers = P34.primeNumbers_sieve(0 to 10)
25 | primeNumbers should have length 4
26 | primeNumbers should be(List(2, 3, 5, 7))
27 | }
28 |
29 | it("should list 7, 11, 13, 17, 19, 23, 29, 31 as prime numbers between 7 and 31") {
30 | val primeNumbers = P34.primeNumbers_sieve(7 to 31)
31 | primeNumbers should have length 8
32 | primeNumbers should be(List(7, 11, 13, 17, 19, 23, 29, 31))
33 | }
34 |
35 | }
36 |
37 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/tadm/ch04/excercises/Problem4_2.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.excercises;
2 |
3 | import com.shekhargulati.IntPair;
4 |
5 | import java.util.OptionalInt;
6 | import java.util.stream.IntStream;
7 |
8 | public class Problem4_2 {
9 |
10 | public static IntPair maximize_unsorted(int[] numbers) {
11 | OptionalInt min = IntStream.of(numbers).min();
12 | OptionalInt max = IntStream.of(numbers).max();
13 | return new IntPair(min.getAsInt(), max.getAsInt());
14 | }
15 |
16 | public static IntPair maximize_sorted(int[] numbers) {
17 | return new IntPair(numbers[0], numbers[numbers.length - 1]);
18 | }
19 |
20 | public static IntPair minimize_unsorted(int[] numbers) {
21 | int[] sorted = IntStream.of(numbers).sorted().toArray();
22 | return minimize_sorted(sorted);
23 | }
24 |
25 | public static IntPair minimize_sorted(int[] sorted) {
26 | int diff = sorted[1] - sorted[0];
27 | IntPair pair = null;
28 | for (int i = 1; i < sorted.length - 1; i++) {
29 | int first = sorted[i];
30 | int second = sorted[i + 1];
31 | if (diff > (second - first)) {
32 | diff = second - first;
33 | pair = new IntPair(first, second);
34 | }
35 | }
36 | return pair;
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/tadm/ch04/examples/MergeSort.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.examples;
2 |
3 | import java.util.Arrays;
4 |
5 | public class MergeSort {
6 |
7 | public static void main(String[] args) {
8 | System.out.println(Arrays.toString(mergeSort(new int[]{3, 2, 1, 4})));
9 | }
10 |
11 | public static int[] mergeSort(int[] arr) {
12 | if (arr.length == 1) {
13 | return arr;
14 | }
15 | int middle = arr.length / 2;
16 | int[] left = mergeSort(Arrays.copyOfRange(arr, 0, middle));
17 | int[] right = mergeSort(Arrays.copyOfRange(arr, middle, arr.length));
18 | return merge(left, right, arr.length);
19 | }
20 |
21 | private static int[] merge(int[] left, int[] right, int length) {
22 | int[] sorted = new int[length];
23 | int[] smaller = ((left.length < right.length) ? left : right);
24 | for (int i = 0; i < smaller.length; i++) {
25 | if (left[i] <= right[i]) {
26 | sorted[i] = left[i];
27 | } else {
28 | sorted[i] = right[i];
29 | }
30 | }
31 | int[] greater = ((left.length > right.length) ? left : right);
32 | for (int i = smaller.length; i < greater.length; i++) {
33 | sorted[i] = greater[i];
34 | }
35 | return sorted;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/random/MovieScheduler.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.random
2 |
3 | import java.time.LocalDate
4 |
5 | object MovieScheduler {
6 |
7 |
8 | /**
9 | * Find non-overlapping movies that actor can do within a duration
10 | */
11 | def schedule(movies: List[Movie], duration: (LocalDate, LocalDate)): List[Movie] = {
12 | /*
13 | 1. Find the movie which completes first within the duration
14 | 2. Add that to the result list
15 | 3. Call the method recursively by remove movie found in step 2. Also, set start of duration to the completion date of that movie
16 | */
17 | val selectedOpt = movies
18 | .filter(m => m.start.isAfter(duration._1.minusDays(1)) && m.completion.isBefore(duration._2.plusDays(1)))
19 | .sortWith({
20 | case (m1, m2) => m1.completion.isBefore(m2.completion)
21 | })
22 | .headOption
23 |
24 | selectedOpt.map(selected => {
25 | movies.splitAt(movies.indexOf(selected) + 1) match {
26 | case (Nil, second) => List(selected) ++ schedule(second, (selected.completion, duration._2))
27 | case (first, second) => List(selected) ++ schedule(first.init ++ second, (selected.completion, duration._2))
28 | case _ => Nil
29 | }
30 | }).getOrElse(Nil)
31 | }
32 |
33 | }
34 |
35 | case class Movie(title: String, start: LocalDate, completion: LocalDate)
36 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P26.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
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.Collectors;
8 | import java.util.stream.Stream;
9 |
10 | import static java.util.stream.Collectors.toList;
11 |
12 | /**
13 | * (**) Generate the combinations of K distinct objects chosen from the N elements of a list
14 | */
15 | public class P26 {
16 |
17 | public static List> combinations(List list, int k) {
18 | if (k == 0 || list.isEmpty()) {
19 | return Collections.emptyList();
20 | }
21 | if (k == 1) {
22 | return list.stream().map(e -> Stream.of(e).collect(toList())).collect(toList());
23 | }
24 | Map> headAndTail = P17.split(list, 1);
25 | List head = headAndTail.get(true);
26 | List tail = headAndTail.get(false);
27 | List> c1 = combinations(tail, (k - 1)).stream().map(e -> {
28 | List l = new ArrayList<>();
29 | l.addAll(head);
30 | l.addAll(e);
31 | return l;
32 | }).collect(Collectors.toList());
33 | List> c2 = combinations(tail, k);
34 | c1.addAll(c2);
35 | return c1;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_03_logic_and_codes/P46.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._03_logic_and_codes
2 |
3 | /**
4 | * 3.01 (**) Truth tables for logical expressions.
5 | *
6 | * Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goals (not only the constants true and fail).
7 | *
8 | * A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B)).
9 | * Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables.
10 | */
11 | object P46 {
12 |
13 | def table(f: (Boolean, Boolean) => Boolean): String = {
14 | val tableBuilder = StringBuilder.newBuilder
15 | tableBuilder.append("A B result\n")
16 | for {a <- List(true, false)
17 | b <- List(true, false)
18 | } {
19 | tableBuilder.append(f"$a%-10s $b%-10s ${f(a, b)}%s\n")
20 | }
21 | tableBuilder.mkString("")
22 | }
23 |
24 | def or(a: Boolean, b: Boolean): Boolean = a || b
25 |
26 | def and(a: Boolean, b: Boolean): Boolean = a && b
27 |
28 | def nand(a: Boolean, b: Boolean) = !and(a, b)
29 | }
30 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P02Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.*;
6 |
7 | import static com.shekhargulati.ninetynine_problems._01_lists.CollectionUtils.linkedList;
8 | import static java.util.Arrays.asList;
9 | import static org.hamcrest.CoreMatchers.equalTo;
10 | import static org.hamcrest.CoreMatchers.is;
11 | import static org.junit.Assert.assertThat;
12 |
13 | public class P02Test {
14 |
15 | @Test
16 | public void shouldFindSecondLastElementFromAList() throws Exception {
17 | List numbers = asList(1, 2, 11, 4, 5, 8, 10, 6);
18 | assertThat(P02.secondLast(numbers), is(equalTo(10)));
19 | }
20 |
21 | @Test(expected = NoSuchElementException.class)
22 | public void shouldThrowExceptionWhenListEmpty() throws Exception {
23 | P02.secondLast(Collections.emptyList());
24 | }
25 |
26 | @Test(expected = NoSuchElementException.class)
27 | public void shouldThrowExceptionWhenListHasSingleElement() throws Exception {
28 | P02.secondLast(Arrays.asList(1));
29 | }
30 |
31 | @Test
32 | public void shouldFindSecondLastElementFromALinkedList() throws Exception {
33 | LinkedList numbers = linkedList(1, 2, 11, 4, 5, 8, 10, 6);
34 | assertThat(P02.secondLastRecursion(numbers), is(equalTo(10)));
35 | }
36 | }
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P35.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import java.util.Arrays;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.stream.IntStream;
7 |
8 | /**
9 | * (**) Goldbach's conjecture
10 | *
11 | * Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers.
12 | * Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct
13 | * in the general case. It has been numerically confirmed up to very large numbers.
14 | * Write a predicate to find the two prime numbers that sum up to a given even integer.
15 | */
16 | public class P35 {
17 |
18 | public static List goldbach(int number) {
19 | if (number == 2) {
20 | return Collections.emptyList();
21 | } else if (number % 2 != 0) {
22 | return Collections.emptyList();
23 | }
24 |
25 | List primeNumbers = P34.primeNumbers(IntStream.rangeClosed(2, number));
26 | for (Integer primeNumber : primeNumbers) {
27 | if (primeNumbers.contains(number - primeNumber)) {
28 | return Arrays.asList(primeNumber, number - primeNumber);
29 | }
30 | }
31 | throw new RuntimeException("Should not have happened!!");
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ninety-Nine Problems in Java 8, Scala, and Haskell
2 |
3 | This is an adaptation of the [Ninety-Nine Prolog Problems](https://sites.google.com/site/prologsite/prolog-problems) written by Werner Hett at the Berne University of Applied Sciences in Berne, Switzerland.
4 |
5 | From the original source:
6 |
7 | > The purpose of this problem collection is to give you the opportunity to practice your skills in logic programming. Your goal should be to find the most elegant solution of the given problems. Efficiency is important, but logical clarity is even more crucial. Some of the (easy) problems can be trivially solved using built-in predicates. However, in these cases, you learn more if you try to find your own solution.
8 |
9 | > The problems have different levels of difficulty. Those marked with a single asterisk (\*) are easy. If you have successfully solved the preceding problems you should be able to solve them within a few (say 15) minutes. Problems marked with two asterisks (\*\*) are of intermediate difficulty. If you are a skilled programmer it shouldn't take you more than 30-90 minutes to solve them. Problems marked with three asterisks (\*\*\*) are more difficult. You may need more time (i.e. a few hours or more) to find a good solution.
10 |
11 | ***Please refer to language specific README.md for more details.***
12 |
13 | ## Programming Languages
14 |
15 | * [Java 8](./java8)
16 | * [Scala](./scala)
17 | * [Haskell](./haskell)
18 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P26Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 | import java.util.stream.Stream;
7 |
8 | import static java.util.stream.Collectors.toList;
9 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P26Test {
13 |
14 | @Test
15 | public void shouldFindAllCombinationsOfSize2FromAListWithSize3() throws Exception {
16 | List input = Stream.of("a", "b", "c").collect(toList());
17 | List> combinations = P26.combinations(input, 2);
18 | assertThat(combinations, hasSize(3));
19 | }
20 |
21 |
22 | @Test
23 | public void shouldFindAllCombinationsOfSize3FromAListWithSize6() throws Exception {
24 | List input = Stream.of("a", "b", "c", "d", "e", "f").collect(toList());
25 | List> combinations = P26.combinations(input, 3);
26 | assertThat(combinations, hasSize(20));
27 | }
28 |
29 | @Test
30 | public void shouldFindAllCombinationsOfSize4FromAListWithSize6() throws Exception {
31 | List input = Stream.of("a", "b", "c", "d", "e", "f").collect(toList());
32 | List> combinations = P26.combinations(input, 4);
33 | assertThat(combinations, hasSize(15));
34 | }
35 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/codegolf/AcronymMakerTest.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.codegolf;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.CoreMatchers.equalTo;
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class AcronymMakerTest {
9 |
10 | @Test
11 | public void acronymOfUnitedStatesOfAmericaIsUSA() throws Exception {
12 | final String input = "United States of America";
13 | final String acronym = AcronymMaker.acronym(input);
14 | assertThat(acronym, equalTo("USA"));
15 | }
16 |
17 | @Test
18 | public void acronymOfUnitedStatesOfAmericaIsUSA_lowercase() throws Exception {
19 | final String input = "united states of america";
20 | final String acronym = AcronymMaker.acronym(input);
21 | assertThat(acronym, equalTo("USA"));
22 | }
23 |
24 | @Test
25 | public void acronymOfLightAmplificationByStimulationOfEmittedRadiationIsLASER() throws Exception {
26 | final String input = "Light Amplification by Stimulation of Emitted Radiation";
27 | final String acronym = AcronymMaker.acronym(input);
28 | assertThat(acronym, equalTo("LASER"));
29 | }
30 |
31 | @Test
32 | public void acronymOfJordanOfTheWorldIsJTW() throws Exception {
33 | final String input = "Jordan Of the World";
34 | final String acronym = AcronymMaker.acronym(input);
35 | assertThat(acronym, equalTo("JTW"));
36 | }
37 |
38 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P16Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
9 | import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P16Test {
13 |
14 | @Test
15 | public void shouldDropEveryNthElement() throws Exception {
16 | List result = P16.dropEveryNth(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), 3);
17 | assertThat(result, hasSize(8));
18 | assertThat(result, contains("a", "b", "d", "e", "g", "h", "j", "k"));
19 | }
20 |
21 | @Test
22 | public void shouldReturnSameListWhenNIsLessThanListSize() throws Exception {
23 | List result = P16.dropEveryNth(Arrays.asList("a", "b"), 3);
24 | assertThat(result, hasSize(2));
25 | assertThat(result, contains("a", "b"));
26 | }
27 |
28 | @Test
29 | public void shouldReturnSameListWhenNIsZero() throws Exception {
30 | List result = P16.dropEveryNth(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"), 0);
31 | assertThat(result, hasSize(11));
32 | assertThat(result, contains("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"));
33 | }
34 |
35 |
36 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/tadm/ch04/excercises/Problem4_2Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.excercises;
2 |
3 | import com.shekhargulati.IntPair;
4 | import org.junit.Test;
5 |
6 | import static org.hamcrest.CoreMatchers.equalTo;
7 | import static org.junit.Assert.assertThat;
8 |
9 | public class Problem4_2Test {
10 |
11 | @Test
12 | public void shouldFindPairThatMaximizeWithinUnsortedArray() throws Exception {
13 | int[] numbers = {6, 13, 19, 3, 8};
14 |
15 | IntPair p = Problem4_2.maximize_unsorted(numbers);
16 | assertThat(p, equalTo(new IntPair(3, 19)));
17 | }
18 |
19 | @Test
20 | public void shouldFindPairThatMaximizeWithinSortedArray() throws Exception {
21 | int[] numbers = {3, 6, 8, 13, 19};
22 |
23 | IntPair p = Problem4_2.maximize_sorted(numbers);
24 | assertThat(p, equalTo(new IntPair(3, 19)));
25 | }
26 |
27 | @Test
28 | public void shouldFindPairThatMinimizeWithinUnsortedArray() throws Exception {
29 | int[] numbers = {6, 13, 19, 3, 8, 14};
30 |
31 | IntPair p = Problem4_2.minimize_unsorted(numbers);
32 | assertThat(p, equalTo(new IntPair(13, 14)));
33 | }
34 |
35 | @Test
36 | public void shouldFindPairThatMinimiseWithinSortedArray() throws Exception {
37 | int[] numbers = {3, 6, 8, 13, 19};
38 |
39 | IntPair p = Problem4_2.minimize_sorted(numbers);
40 | assertThat(p, equalTo(new IntPair(6, 8)));
41 | }
42 | }
--------------------------------------------------------------------------------
/scala/src/main/scala/com/shekhargulati/ninetynine_problems/_01_lists/P08.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import scala.annotation.tailrec
4 |
5 | /**
6 | * (**) Eliminate consecutive duplicates of list elements
7 | * If a list contains repeated elements they should be replaced with a single copy of the element.
8 | * The order of the elements should not be changed.
9 | *
10 | *
11 | * compress(List(a,a,a,a,b,c,c,a,a,d,e,e,e,e))
12 | * [a,b,c,d,e]
13 | *
14 | */
15 | object P08 {
16 |
17 | def compress[T >: Null <: Any](list: List[T]): List[T] = {
18 | @tailrec
19 | def compress_rec(input: List[T], result: List[T], lastElem: T): List[T] = {
20 | input match {
21 | case x :: xs if lastElem != x => compress_rec(xs, result :+ x, x)
22 | case x :: xs => compress_rec(xs, result, x)
23 | case Nil => result
24 | }
25 | }
26 | compress_rec(list, List(), null)
27 | }
28 |
29 | def compress_dropWhile[T](list: List[T]): List[T] = list match {
30 | case Nil => Nil
31 | case x :: xs => x :: compress_dropWhile(xs.dropWhile(e => e == x))
32 | }
33 |
34 | def compress_dropWhile_tailrec[T](list: List[T]): List[T] = {
35 | @tailrec
36 | def compressR(input: List[T], result: List[T]): List[T] = input match {
37 | case Nil => result
38 | case x :: xs => compressR(xs.dropWhile(e => e == x), result :+ x)
39 | }
40 | compressR(list, List())
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/tadm/ch04/excercises/Problem4_1.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.tadm.ch04.excercises;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.Objects;
6 | import java.util.stream.Collectors;
7 |
8 | public class Problem4_1 {
9 |
10 | public static List> teams(List players) {
11 | List sorted = players.stream().sorted((p1, p2) -> p1.rating - p2.rating).collect(Collectors.toList());
12 | int totalPlayers = players.size();
13 | return Arrays.asList(sorted.subList(0, totalPlayers / 2), sorted.subList(totalPlayers / 2, totalPlayers));
14 | }
15 |
16 | }
17 |
18 | class Player {
19 | String name;
20 | int rating;
21 |
22 | public Player(String name, int rating) {
23 | this.name = name;
24 | this.rating = rating;
25 | }
26 |
27 | @Override
28 | public String toString() {
29 | return "Player{" +
30 | "name='" + name + '\'' +
31 | ", rating=" + rating +
32 | '}';
33 | }
34 |
35 | @Override
36 | public boolean equals(Object o) {
37 | if (this == o) return true;
38 | if (o == null || getClass() != o.getClass()) return false;
39 | Player player = (Player) o;
40 | return rating == player.rating &&
41 | Objects.equals(name, player.name);
42 | }
43 |
44 | @Override
45 | public int hashCode() {
46 | return Objects.hash(name, rating);
47 | }
48 | }
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P28Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P28Test extends FunSpec with Matchers {
6 |
7 | describe("P28Spec") {
8 |
9 | it("should sort list elements by length") {
10 | val input = List(List("a", "b", "c"), List("d", "e"), List("f", "g", "h"), List("d", "e"), List("i", "j", "k"), List("m", "n"), List("o"))
11 | val result = P28.lsort(input)
12 | result should be(List(List("o"), List("d", "e"), List("d", "e"), List("m", "n"), List("a", "b", "c"), List("f", "g", "h"), List("i", "j", "k")))
13 | }
14 |
15 | it("should sort list by length frequency") {
16 | val input = List(List("a", "b", "c"), List("d", "e"), List("f", "g", "h"), List("d", "e"), List("i", "j", "k", "l"), List("m", "n"), List("o"))
17 | val result = P28.lfsort(input)
18 | result should be(List(List("i", "j", "k", "l"), List("o"), List("a", "b", "c"), List("f", "g", "h"), List("d", "e"), List("d", "e"), List("m", "n")))
19 | }
20 |
21 | it("should sort list by element list length frequency") {
22 | val input = List(List("a", "b", "c", "d"), List("d", "e"), List("f", "g", "h"), List("d", "e"), List("i", "j", "k", "l"), List("m", "n"), List("o"))
23 | val result = P28.lfsort(input)
24 | result should be(List(List("o"), List("f", "g", "h"), List("a", "b", "c", "d"), List("i", "j", "k", "l"), List("d", "e"), List("d", "e"), List("m", "n")))
25 | }
26 |
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/java8/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Gradle template
3 | .gradle
4 | build/
5 |
6 | # Ignore Gradle GUI config
7 | gradle-app.setting
8 |
9 |
10 | ### JetBrains template
11 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
12 |
13 | *.iml
14 |
15 | ## Directory-based project format:
16 | .idea/
17 | # if you remove the above rule, at least ignore the following:
18 |
19 | # User-specific stuff:
20 | # .idea/workspace.xml
21 | # .idea/tasks.xml
22 | # .idea/dictionaries
23 |
24 | # Sensitive or high-churn files:
25 | # .idea/dataSources.ids
26 | # .idea/dataSources.xml
27 | # .idea/sqlDataSources.xml
28 | # .idea/dynamic.xml
29 | # .idea/uiDesigner.xml
30 |
31 | # Gradle:
32 | # .idea/gradle.xml
33 | # .idea/libraries
34 |
35 | # Mongo Explorer plugin:
36 | # .idea/mongoSettings.xml
37 |
38 | ## File-based project format:
39 | *.ipr
40 | *.iws
41 |
42 | ## Plugin-specific files:
43 |
44 | # IntelliJ
45 | out/
46 |
47 | # mpeltonen/sbt-idea plugin
48 | .idea_modules/
49 |
50 | # JIRA plugin
51 | atlassian-ide-plugin.xml
52 |
53 | # Crashlytics plugin (for Android Studio and IntelliJ)
54 | com_crashlytics_export_strings.xml
55 | crashlytics.properties
56 | crashlytics-build.properties
57 |
58 |
59 | ### Java template
60 | *.class
61 |
62 | # Mobile Tools for Java (J2ME)
63 | .mtj.tmp/
64 |
65 | # Package Files #
66 | *.jar
67 | *.war
68 | *.ear
69 |
70 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
71 | hs_err_pid*
72 |
73 | rx-docker-client.iml
74 |
75 | !gradle/wrapper/gradle-wrapper.jar
76 |
--------------------------------------------------------------------------------
/scala/src/test/scala/com/shekhargulati/ninetynine_problems/_01_lists/P03Test.scala:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists
2 |
3 | import org.scalatest.{FunSpec, Matchers}
4 |
5 | class P03Test extends FunSpec with Matchers {
6 |
7 | describe("kth element of a list (built-in)") {
8 | it("should be first element when k is 0") {
9 | P03.kth(List(1, 2, 3, 4, 5), 0) should be(1)
10 | }
11 |
12 | it("should be last element when k is equal to size of list minus one") {
13 | P03.kth(List(1, 2, 3, 4, 5), 4) should be(5)
14 | }
15 |
16 | it("should be (k+1)th element") {
17 | P03.kth(List(1, 2, 3, 4, 5), 2) should be(3)
18 | }
19 | }
20 |
21 | describe("kth element of a list (built-in another)") {
22 | it("should be first element when k is 0") {
23 | P03.kth1(List(1, 2, 3, 4, 5), 0) should be(1)
24 | }
25 |
26 | it("should be last element when k is equal to size of list minus one") {
27 | P03.kth1(List(1, 2, 3, 4, 5), 4) should be(5)
28 | }
29 |
30 | it("should be (k+1)th element") {
31 | P03.kth1(List(1, 2, 3, 4, 5), 2) should be(3)
32 | }
33 | }
34 |
35 | describe("kth element of a list (recursive)") {
36 | it("should be first element when k is 0") {
37 | P03.kthRecursive(List(1, 2, 3, 4, 5), 0) should be(1)
38 | }
39 |
40 | it("should be last element when k is equal to size of list minus 1") {
41 | P03.kthRecursive(List(1, 2, 3, 4, 5), 4) should be(5)
42 | }
43 |
44 | it("should be (k+1)th element") {
45 | P03.kthRecursive(List(1, 2, 3, 4, 5), 2) should be(3)
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P23.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.Random;
7 | import java.util.stream.Collectors;
8 |
9 | /**
10 | * (**) Extract a given number of randomly selected elements from a list
11 | */
12 | public class P23 {
13 |
14 | public static List randomSelect(List list, int n) {
15 | return new Random().ints(0, list.size()).limit(n).mapToObj(list::get).collect(Collectors.toList());
16 | }
17 |
18 | public static List randomSelectR(List list, int n) {
19 | if (n == 0) {
20 | return Collections.emptyList();
21 | }
22 | Object[] objects = P20.removeAt0(list, new Random().nextInt(list.size()));
23 | List remaining = (List) objects[0];
24 | T t = (T) objects[1];
25 | List result = new ArrayList<>();
26 | result.add(t);
27 | result.addAll(randomSelectR(remaining, n - 1));
28 | return result;
29 | }
30 |
31 | public static List randomSelect_imperative(List list, int n) {
32 | List result = new ArrayList<>();
33 |
34 | Random random = new Random();
35 | List remaining = list;
36 | while (result.size() < n) {
37 | Object[] objects = P20.removeAt0(remaining, random.nextInt(remaining.size()));
38 | remaining = (List) objects[0];
39 | T t = (T) objects[1];
40 | result.add(t);
41 | }
42 | return result;
43 | }
44 |
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P01.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.LinkedList;
4 | import java.util.List;
5 | import java.util.NoSuchElementException;
6 |
7 | /**
8 | * (*) Find the last element of a list.
9 | *
10 | * Check P01Test class for test cases related to this problem.
11 | */
12 | public class P01 {
13 |
14 | /*
15 | You could solve this using many different approaches.
16 | If you work with List interface then you can find the last element using List size as shown below.
17 | */
18 | public static T last(List elements) {
19 | int numberOfElements = elements.size();
20 | return elements.get(numberOfElements - 1);
21 | }
22 |
23 | /*
24 | Another way to solve this is by using LinkedList instead of a List.
25 | LinkedList provides a builtin getLast method.
26 | */
27 | public static T last(LinkedList elements) {
28 | return elements.getLast();
29 | }
30 |
31 |
32 | /*
33 | A functional approach could be to use recursion. We call the function recusively with a sub list which ignores the 0th element.
34 | When we reach the end i.e. size of the list is 1 then we return that element.
35 | */
36 | public static T lastRecursive(List elements) {
37 | if (elements == null || elements.isEmpty()) {
38 | throw new NoSuchElementException();
39 | }
40 | if (elements.size() == 1) {
41 | return elements.get(0);
42 | }
43 | return lastRecursive(elements.subList(1, elements.size()));
44 | }
45 |
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_01_lists/P28Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.hamcrest.CoreMatchers.equalTo;
9 | import static org.hamcrest.CoreMatchers.is;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P28Test {
13 |
14 | @Test
15 | public void shouldSortByElementLength() throws Exception {
16 | List> input = Arrays.asList(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e"), Arrays.asList("f", "g", "h"), Arrays.asList("d", "e"), Arrays.asList("i", "j", "k"), Arrays.asList("m", "n"), Arrays.asList("o"));
17 | List> result = P28.lsort(input);
18 | assertThat(result, is(equalTo(Arrays.asList(Arrays.asList("o"), Arrays.asList("d", "e"), Arrays.asList("d", "e"), Arrays.asList("m", "n"), Arrays.asList("a", "b", "c"), Arrays.asList("f", "g", "h"), Arrays.asList("i", "j", "k")))));
19 | }
20 |
21 | @Test
22 | public void shouldSortByLengthFrequency() throws Exception {
23 | List> input = Arrays.asList(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e"), Arrays.asList("f", "g", "h"), Arrays.asList("d", "e"), Arrays.asList("i", "j", "k", "l"), Arrays.asList("m", "n"), Arrays.asList("o"));
24 | List> result = P28.lfsort(input);
25 | assertThat(result, is(equalTo(Arrays.asList(Arrays.asList("i", "j", "k", "l"), Arrays.asList("o"), Arrays.asList("a", "b", "c"), Arrays.asList("f", "g", "h"), Arrays.asList("d", "e"), Arrays.asList("d", "e"), Arrays.asList("m", "n")))));
26 | }
27 | }
--------------------------------------------------------------------------------
/scala/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### SBT template
3 | # Simple Build Tool
4 | # http://www.scala-sbt.org/release/docs/Getting-Started/Directories.html#configuring-version-control
5 |
6 | target/
7 | lib_managed/
8 | src_managed/
9 | project/boot/
10 | .history
11 | .cache
12 | ### Scala template
13 | *.class
14 | *.log
15 |
16 | # sbt specific
17 | .cache
18 | .history
19 | .lib/
20 | dist/*
21 | target/
22 | lib_managed/
23 | src_managed/
24 | project/boot/
25 | project/plugins/project/
26 |
27 | # Scala-IDE specific
28 | .scala_dependencies
29 | .worksheet
30 | ### JetBrains template
31 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio
32 |
33 | *.iml
34 |
35 | ## Directory-based project format:
36 | .idea/
37 | # if you remove the above rule, at least ignore the following:
38 |
39 | # User-specific stuff:
40 | # .idea/workspace.xml
41 | # .idea/tasks.xml
42 | # .idea/dictionaries
43 |
44 | # Sensitive or high-churn files:
45 | # .idea/dataSources.ids
46 | # .idea/dataSources.xml
47 | # .idea/sqlDataSources.xml
48 | # .idea/dynamic.xml
49 | # .idea/uiDesigner.xml
50 |
51 | # Gradle:
52 | # .idea/gradle.xml
53 | # .idea/libraries
54 |
55 | # Mongo Explorer plugin:
56 | # .idea/mongoSettings.xml
57 |
58 | ## File-based project format:
59 | *.ipr
60 | *.iws
61 |
62 | ## Plugin-specific files:
63 |
64 | # IntelliJ
65 | /out/
66 |
67 | # mpeltonen/sbt-idea plugin
68 | .idea_modules/
69 |
70 | # JIRA plugin
71 | atlassian-ide-plugin.xml
72 |
73 | # Crashlytics plugin (for Android Studio and IntelliJ)
74 | com_crashlytics_export_strings.xml
75 | crashlytics.properties
76 | crashlytics-build.properties
77 |
78 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P28.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.Collection;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | import static java.util.stream.Collectors.groupingBy;
9 | import static java.util.stream.Collectors.toList;
10 |
11 | /**
12 | * (**) Sorting a list of lists according to length of sublists
13 | */
14 | public class P28 {
15 |
16 | public static List> lsort(List> list) {
17 | list.sort((xs1, xs2) -> xs1.size() - xs2.size());
18 | return list;
19 | }
20 |
21 | public static List> lfsort(List> list) {
22 | Map freqs = new HashMap<>();
23 | list.stream().map(List::size).forEach(l -> freqs.put(l, freqs.compute(l, (k, v) -> v == null ? 1 : v + 1)));
24 | return list
25 | .stream()
26 | .sorted((xs1, xs2) -> freqs.get(xs1.size()) - freqs.get(xs2.size()))
27 | .collect(toList());
28 | }
29 |
30 | /*
31 | Same as scala code. This code does not works correctly because elements with same length are at different position
32 | */
33 | public static List> lfsort1(List> list) {
34 | return lsort(
35 | lsort(list)
36 | .stream()
37 | .collect(groupingBy(List::size))
38 | .values().stream().collect(toList()))
39 | .stream()
40 | .flatMap(Collection::stream)
41 | .collect(toList());
42 | }
43 |
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/ninetynine_problems/_02_arithmetic/P34Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._02_arithmetic;
2 |
3 | import org.junit.Test;
4 |
5 | import java.util.List;
6 | import java.util.stream.IntStream;
7 |
8 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
9 | import static org.hamcrest.core.IsCollectionContaining.hasItems;
10 | import static org.junit.Assert.assertThat;
11 |
12 | public class P34Test {
13 |
14 | @Test
15 | public void shouldGiveAllPrimeNumbersBetween2And10() throws Exception {
16 | List primeNumbers = P34.primeNumbers(IntStream.rangeClosed(2, 10));
17 | assertThat(primeNumbers, hasSize(4));
18 | assertThat(primeNumbers, hasItems(2, 3, 5, 7));
19 | }
20 |
21 | @Test
22 | public void shouldGiveAllPrimeNumbersBetween7And31() throws Exception {
23 | List primeNumbers = P34.primeNumbers(IntStream.rangeClosed(7, 31));
24 | assertThat(primeNumbers, hasSize(8));
25 | assertThat(primeNumbers, hasItems(7, 11, 13, 17, 19, 23, 29, 31));
26 | }
27 |
28 | @Test
29 | public void shouldGiveAllPrimeNumbersBetween2And10_sieve() throws Exception {
30 | List primeNumbers = P34.primeNumbers_sieve(2, 10);
31 | assertThat(primeNumbers, hasSize(4));
32 | assertThat(primeNumbers, hasItems(2, 3, 5, 7));
33 | }
34 |
35 | @Test
36 | public void shouldGiveAllPrimeNumbersBetween7And31_sieve() throws Exception {
37 | List primeNumbers = P34.primeNumbers_sieve(7, 31);
38 | assertThat(primeNumbers, hasSize(8));
39 | assertThat(primeNumbers, hasItems(7, 11, 13, 17, 19, 23, 29, 31));
40 | }
41 | }
--------------------------------------------------------------------------------
/java8/src/test/java/com/shekhargulati/leetcode/algorithms/Problem05Test.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.leetcode.algorithms;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.hamcrest.CoreMatchers.equalTo;
6 | import static org.junit.Assert.assertThat;
7 |
8 | public class Problem05Test {
9 |
10 | @Test
11 | public void shouldDetectLongestPalindrome() throws Exception {
12 | final String input = "saasdcjkbkjnjnnknvjfknjnfjkvnjkfdnvjknfdkvjnkjfdnvkjnvjknjkgnbjkngkjvnjkgnbvkjngfreyh67ujrtyhytju789oijtnuk789oikmtul0oymmmmmmmmmmmmmmmm";
13 | String l = Problem05.longestPalindrome(input);
14 | assertThat(l, equalTo("mmmmmmmmmmmmmmmm"));
15 | }
16 |
17 | @Test
18 | public void shouldFindLongestPalindromeString() throws Exception {
19 | final String input = "racecar";
20 | String s = Problem05.longestPalindrome1(input);
21 | assertThat(s, equalTo("racecar"));
22 |
23 | }
24 |
25 | @Test
26 | public void shouldFindLongestPalindromeString_2() throws Exception {
27 | final String input = "saas";
28 | String s = Problem05.longestPalindrome1(input);
29 | assertThat(s, equalTo("saas"));
30 | }
31 |
32 | @Test
33 | public void shouldFindLongestPalindromeString_3() throws Exception {
34 | final String input = "forgeeksskeegfor";
35 | String s = Problem05.longestPalindrome1(input);
36 | assertThat(s, equalTo("geeksskeeg"));
37 | }
38 |
39 | @Test
40 | public void shouldFindLongestPalindromeString_4() throws Exception {
41 | final String input = "abaccddccefe";
42 | String s = Problem05.longestPalindrome1(input);
43 | assertThat(s, equalTo("ccddcc"));
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/java8/src/main/java/com/shekhargulati/ninetynine_problems/_01_lists/P05.java:
--------------------------------------------------------------------------------
1 | package com.shekhargulati.ninetynine_problems._01_lists;
2 |
3 | import java.util.*;
4 | import java.util.stream.IntStream;
5 | import java.util.stream.StreamSupport;
6 |
7 | import static java.util.stream.Collectors.toList;
8 |
9 | /**
10 | * Reverse a list
11 | */
12 | public class P05 {
13 |
14 | public static List reverse(List list) {
15 | if (list == null) {
16 | throw new IllegalArgumentException("list can't be null");
17 | }
18 | Collections.reverse(list);
19 | return list;
20 | }
21 |
22 | public static List reverse_foreach(List list) {
23 | if (list == null) {
24 | throw new IllegalArgumentException("list can't be null");
25 | }
26 | List reversed = new ArrayList<>();
27 | for (int i = list.size() - 1; i >= 0; i--) {
28 | reversed.add(list.get(i));
29 | }
30 | return reversed;
31 | }
32 |
33 |
34 | public static List reverse_IntStream(List