Skip to content

Commit 82e97af

Browse files
authored
Merge pull request TheAlgorithms#29 from shashank152k/BasicMaths
Basic Maths - Fibonacci, Factorial, Maximum Sub Array Sum (Kadane)
2 parents 172453b + 36dc59a commit 82e97af

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

src/Maths/Factorial.hs

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module Maths.Factorial where
2+
3+
fac :: Integer -> Integer
4+
fac 0 = 1
5+
fac n = n * fac (n - 1)
6+
7+
main :: IO ()
8+
main = do
9+
print (fac 4)

src/Maths/Fibonacci.hs

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module Maths.Fibonacci where
2+
3+
fib :: Integer -> Integer
4+
fib 0 = 0
5+
fib 1 = 1
6+
fib n = fib (n-1) + fib (n-2)
7+
8+
main :: IO ()
9+
main = do
10+
print (fib 10)

src/Maths/KadaneAlgorithm.hs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
module Maths.KadaneAlgorithm where
2+
3+
-- Sample Input List
4+
inputList :: [Integer]
5+
inputList = [1, -2, 3, 4, -5, 6, -7, 8, 9, 10]
6+
7+
8+
-- Helper function that updates values of maxSoFar and maxEndingHere
9+
-- and call itself recursively over the values of the list
10+
-- and when the list is empty, return the maxSoFar value
11+
-- with the start and end indices.
12+
maxSubArrayHelper :: Integer -> Integer -> Integer -> Integer -> Integer -> [Integer] -> (Integer, Integer, Integer)
13+
maxSubArrayHelper maxSoFar _ _ start end [] = (maxSoFar, start, end)
14+
maxSubArrayHelper maxSoFar maxEndingHere i start end (x:xs) =
15+
let i' = i + 1
16+
maxEndingHere' = maxEndingHere + x
17+
in
18+
if maxSoFar < maxEndingHere' then
19+
maxSubArrayHelper maxEndingHere' maxEndingHere' i' start i xs
20+
else if maxEndingHere' < 0 then
21+
maxSubArrayHelper maxSoFar 0 i' i' i' xs
22+
else
23+
maxSubArrayHelper maxSoFar maxEndingHere' i' start end xs
24+
25+
-- Initially maxSoFar (maximum sum till the previous iteration),
26+
-- maxEndingHere (maximum sum till end index of the current iteration),
27+
-- start (start index) and end (end index) are sent as 0
28+
maxSubArray :: [Integer] -> (Integer, Integer, Integer)
29+
maxSubArray = maxSubArrayHelper 0 0 0 0 0
30+
31+
-- Outputs (sum, start, end)
32+
-- sum - sum from start to end indices of the input array
33+
-- start:end - the subarray with max sum
34+
main :: IO ()
35+
main = do
36+
print (maxSubArray inputList)

0 commit comments

Comments
 (0)