new: Solved problems 21 to 28

This commit is contained in:
Sayantan Santra 2024-05-25 19:28:16 -05:00
parent 2345e43a15
commit a45b84ee9c
Signed by: SinTan1729
GPG key ID: EB3E68BFBA25C85F
8 changed files with 57 additions and 0 deletions

View file

@ -0,0 +1,4 @@
insertAt :: a -> [a] -> Int -> [a]
insertAt x ls n = left ++ [x] ++ right
where
(left, right) = splitAt (n - 1) ls

View file

@ -0,0 +1,2 @@
range :: Int -> Int -> [Int]
range m n = if m > n then [] else m : range (m + 1) n

View file

@ -0,0 +1,7 @@
import Data.List
import System.Random
rndSelect :: [a] -> Int -> IO [a]
rndSelect ls n = do
gen <- getStdGen
return $ take n [ls !! m | m <- nub $ randomRs (0, length ls - 1) gen]

View file

@ -0,0 +1,7 @@
import Data.List
import System.Random
diffSelect :: Int -> Int -> IO [Int]
diffSelect n m = do
gen <- getStdGen
return $ take n [[1 .. m] !! x | x <- nub $ randomRs (0, m - 1) gen]

View file

@ -0,0 +1,7 @@
import Data.List
import System.Random
rndPermu :: [a] -> IO [a]
rndPermu ls = do
gen <- getStdGen
return $ take (length ls) [ls !! m | m <- nub $ randomRs (0, length ls - 1) gen]

View file

@ -0,0 +1,10 @@
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = []
combinations _ [] = []
combinations n (hd : tl) = with ++ without
where
with =
if n == 1
then [[hd]]
else [(hd :)] <*> combinations (n - 1) tl
without = combinations n tl

View file

@ -0,0 +1,11 @@
import Data.List
group' :: [Int] -> [a] -> [[[a]]]
group' ln ls = map ((([([fst] <*>)] <*>) . groupBy grouper . sortBy sorter) . zip ls) (nub (permutations placers))
where
placers = concatMap (uncurry replicate) (zip ln [0 ..])
sorter (_, r1) (_, r2) = r1 `compare` r2
grouper (_, r1) (_, r2) = r1 == r2
group3 :: [a] -> [[[a]]]
group3 = group' [2, 3, 4]

View file

@ -0,0 +1,9 @@
import Data.List
lsort :: [[a]] -> [[a]]
lsort = sortBy (\x y -> length x `compare` length y)
lfsort :: [[a]] -> [[a]]
lfsort ls = sortBy (\x y -> count x `compare` count y) ls
where
count x = length . filter (length x ==) $ map length ls