About
set3q1
def rearrangeArray(arr: Array[Int]): Array[Int] = { val sortedArr = arr.sorted val n = sortedArr.length val rearrangedArr = new ArrayInt
var left = 0 var right = n - 1 var i = 0
while (i < n) { rearrangedArr(i) = sortedArr(left) left += 1 i += 1
if (i < n) {
rearrangedArr(i) = sortedArr(right)
right -= 1
i += 1
}
}
rearrangedArr }
// Usage example val arr = Array(11, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14) val rearranged = rearrangeArray(arr)
println(rearranged.mkString(", "))
q2
applyListFun :: [a -> b] -> a -> [b] applyListFun [] _ = [] applyListFun (f:fs) x = f x : applyListFun fs x
set 2
q1 def compressA: List[A] = { list.foldRight(List.empty[A]) { (elem, acc) => if (acc.isEmpty || acc.head != elem) elem :: acc else acc } }
// Usage example val list = List('a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'c, 'e') val result = compress(list)
println(result)
q2
otherMag :: (a -> b -> c) -> (a -> b -> c) -> [a] -> [b] -> [c] otherMag _ _ [] _ = [] otherMag _ _ _ [] = [] otherMag f g (x:xs) (y:ys) = f x y : otherMag g f xs ys
main :: IO () main = do let result = otherMag (+10) (+100) [0.1, 2, 3, 4] [10, 101, 12, 103, 14] print result -- Output: [10.1, 102, 15, 107, 24]
let result2 = otherMag (+5) (\x y -> x - 10) [100, 200, 300, 400, 500] [105, 190, 305, 390, 505] print result2 -- Output: [105, 190, 305, 390, 505]