Skip to content

Instantly share code, notes, and snippets.

@r17x
Last active August 5, 2023 14:59
Show Gist options
  • Save r17x/939509c126c68faf1be2c58ab4c52372 to your computer and use it in GitHub Desktop.
Save r17x/939509c126c68faf1be2c58ab4c52372 to your computer and use it in GitHub Desktop.
Hackerrank Functional Programming Challenge w/ OCaml
(* returns an array of n elements *)
let make_array n =
let rec f xs = function
| 0 -> xs
| n -> [n] @ f xs (n - 1)
in f [] n
let () =
let n = int_of_string (read_line ()) in
let arr = make_array n in
List.iter ( Printf.printf "%d " ) arr
(* Enter your code here. Read input from STDIN. Print output to STDOUT *)
let rec read_lines () =
try let line = read_line () in
int_of_string (line) :: read_lines()
with
End_of_file -> []
let f n arr =
let rec f n = function
| [] -> []
| [x] when x < n -> [x]
| x::xs -> (if x < n then [x] else []) @ f n xs
in f n arr
let () =
let n::arr = read_lines() in
arr
|> f n
|> List.iter (fun x -> print_int x; print_newline ());;
let rec read_lines () =
try let line = read_line () in
int_of_string (line) :: read_lines()
with
End_of_file -> []
let f arr =
let rec f n = function
| [] -> []
| x::xs -> if n mod 2 == 0
then f (n+1) xs
else [x] @ f (n+1) xs
in f 0 arr
let () =
let arr = read_lines() in
arr
|> f
|>List.iter (fun x -> print_int x; print_newline ()) ;;
let rec read_lines () =
try let line = read_line () in
int_of_string (line) :: read_lines()
with
End_of_file -> []
let compare a b = if a < b then -1 else 1
let f n arr =
let rec f l = function
| 0 -> l
| n -> f (arr @ l) (n-1)
in
(f [] n)
|> List.sort compare
let () =
let n::arr = read_lines() in
let ans = f n arr in
List.iter (fun x -> print_int x; print_newline ()) ans;;
let rec read_lines () =
try let line = read_line () in
int_of_string (line) :: read_lines()
with
End_of_file -> []
let rev arr =
let rec rev = function
| [] -> []
| [x] -> [x]
| x::xs -> (rev xs) @ [x]
in
rev arr
let () =
let arr = read_lines() in
arr
|> rev
|> List.iter (fun x -> print_int x; print_newline ());;
let f arr =
let rec f = function
| [] -> []
| x::xs -> [ if x < 0 then x * -1 else x ] @ f xs
in f arr
let rec read_lines () =
try let line = read_line () in
line :: read_lines()
with
End_of_file -> []
let () =
let inp = read_lines () in
let arr = List.map int_of_string inp in
let result = f arr in
let output = List.map string_of_int result in
print_string (String.concat "\n" output) ;;
@efi-sre
Copy link

efi-sre commented Nov 29, 2022

bisa bisanya pake ocaml

@r17x
Copy link
Author

r17x commented Nov 29, 2022

gak ada pilihan lain pak @efi-sre

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment