Get number of common divisors in OCaml

Hi, everyone! In this challenge I used OCaml sets again. The goal was to get the number of common divisors for each pair of numbers in the test cases. The first function I wrote was to define a limit until when I would be checking if the number was divisible or not: (* Need to check divisors just up to sqrt x *) let max x = Int.of_float (sqrt x) |> (+) 1;; After that, I wrote a function to get the number of common divisors of a single number n. Inside it I wrote another function, divs responsible to get all the divisors up to the limit define in the max function. This is just half of the divisors. The other half is obtained by dividing n by its divisors and adding each result in the set. For instance, if n has divisors, up to max n in the set set, then I add the rest using: ...

March 28, 2017 · 3 min

Dedup chars in a string using OCaml

Hi there! The goal of this challenge is to remove all duplicate chars in a string. The following input/output will explain it by itself: # input abcabczabczabc # output abcz I tried to write the functions to explode and implode from what I remembered, but in the end I had to take another look at their code here. Those were auxiliary functions to help me to write remove_all_dups. open Core.Std (* string -> char list *) let explode str = let len = String.length str in let rec expl str i = if i > len - 1 then [] else str.[i]::(expl str (i+1)) in expl str 0 (* char list -> string *) let implode clist = let len = List.length clist in let str = String.create len in let rec impl i = function | [] -> str | c :: l -> str.[i] <- c; impl (i+1) l in impl 0 clist (* string -> string *) let remove_all_dups str = let char_list = explode str in let s = Set.empty ~comparator:Char.comparator in let rec remove s no_dup_l = function | [] -> no_dup_l | c :: t -> let f = fun x -> x = c in let found = Set.exists s ~f:f in if found then remove s no_dup_l t else let s = Set.add s c in remove s (c :: no_dup_l) t in remove s [] char_list |> List.rev |> implode let a = read_line();; print_string (remove_all_dups a);; If you take a look at the function remove_all_dups, there is a set that is used to keep tracks of the chars that were already seen. First I tried to use a map, but it was too much overkill and more complicated in my opinion. Sets are more specialized and ideal for that. ...

March 27, 2017 · 2 min

Mingle strings in OCaml

Hi there! The problem that I solved this time was a little cumbersome initially, cause even though I knew well how to iterate over lists, I had no idea how to iterate over strings. The solution I found was inspired in the functions to explode and implode strings . These functions use the string indices to explode the string, creating a char list, or implode a char list, creating a string. My goal was not to implode nor explode, but mingle two strings, alternating the chars in each of them. Example of input and output, together with the final result is below. ...

March 26, 2017 · 2 min

List Replication

Hi there! The idea of this problem is just to read some numbers from stdin and replicate them, but using lists. The input would be like this: 3 // # of repetitions 1 // first number ... 2 3 4 // end of input, last number Then the output would be a list with each number repeated the amount of times given. For the case above, it would show “1” three times, “2” three times and so on, each element on a different line. I was given the IO functions by HackerRank and filled the function to create the new list. The result is below. ...

March 24, 2017 · 2 min

Hello World printing in OCaml

Another simple problem from HackerRank is to print Hello World multiple times in a functional language. Well, I am using OCaml and I suppose I should avoid loops. The way I solved it is the following: open Core.Std let n = read_int ();; let rec print_hello n = if n > 0 then begin printf "Hello World\n"; print_hello (n-1); end else ();; print_hello n Problems I had: I lost some some time to discover the ;; was required to make it compile properly. I am not sure exactly why yet. For instance, if I use else (); (just one semicolon) it doesn’t print anything, even though it compiles. Usually the semicolons are required on the toplevel, but on scripts it shouldn’t be always needed. If you know something about this, let me know in the comments. ...

March 24, 2017 · 1 min

Compare Triplets in OCaml

Hi there! It has been a while since I played with OCaml, so I am solving a simple problem from HackerRank. The problem says the following “Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty”. For each category, we must check who had a greater score and give a point to that person for each category. This way, the maximum grade is 3 and the minimum is 0. An example input/output is: ...

March 24, 2017 · 3 min

30 days of code in Go: Day 21 - Extra Long Factorials

One of the big limitations of simple number data types is the maximum number they can hold. A 64 bit unsigned long can hold up to the number $2^{64}-1$. This is a pretty huge number, but if you try to compute the factorial of a number like $25!$, it is not enough. The good news is that there are software libraries that allow us to surpass this limitation. The bad is that the computations take longer. Depending on how critical something is, we may wish to avoid costly computations like these. Anyway, that’s the challenge I solved today using the package Big. My solution is given below. ...

October 12, 2016 · 2 min

30 days of code in Go: Day 19 - Binomial Distribution II

Hi there! Today’s problem is very similar to the last day, again using a binomial distribution. Question Given that 12% of the pistons of a manufacture are rejected because of incorrect sizing, what is the probability of batch of 10 pistons contain No more than two rejects? At least two rejects? Again, very similar. Now the probability of success for the Bernoulli trial is of the chance of the piston being reject, the same as being incorrectly sized. For the case of no more than two rejects, the probability is given by $$P_{x \le 2} = \sum_{i=0}^2 b(i, 10, 0.12),$$ while for the case of at least two rejects it is $$P_{x \ge 2} = \sum_{i=2}^{10} b(i, 10, 0.12).$$ ...

October 6, 2016 · 2 min

30 days of code in Go: Day 18 - Binomial Distribution I

Hi there! Today’s challenge from HackerRank was a little more involved. The challenge is Given the ratio $1.09 : 1$ of boys to girls for babies born in a certain country, what is the proportion of families with exactly 6 children that will have at least 3 boys?. Before actually solving that, it is important to understand a Bernoulli trial and also the Binomial Distribution. Bernoulli trial According to Wikipedia, a Bernoulli trial is a random experiment with exactly two possible outcomes, “success” and “failure”, in which the probability of success is the same every time the experiment is conducted. ...

October 5, 2016 · 2 min

30 days of code in Go: Day 17 - Standard Deviation

Hi there! Today’s challenge was to compute standard deviation of an array of data given the formula $$\sigma = \sqrt{\frac{\sum_{i=0}^{N-1} (x_i - \mu)^2}{N}},$$ where $$\mu = \frac{\sum_{i=0}^{N-1} x_i}{N}.$$ The first input to the program is N and then N integers are fed to the program in sequence. My solution is given below. package main import ( "fmt" "math" ) func mean(a []int) float64 { n := float64(len(a)) sum := 0.0 for i := 0; i < len(a); i++ { sum += float64(a[i]) } return sum / n } func sigma(a []int) float64 { mu := mean(a) sum := 0.0 n := float64(len(a)) for i := 0; i < len(a); i++ { x := float64(a[i]) sum += (x - mu) * (x - mu) } sigma := math.Sqrt(sum / n) return sigma } func main() { N := 0 fmt.Scanf("%d", &N) // allocate memory X := make([]int, N) // read numbers from stdin for i := 0; i < N; i++ { fmt.Scanf("%d", &X[i]) } y := sigma(X) fmt.Printf("%.1f\n", y) } The problem I had this time was with HackerRank. On my computer I had a result, but their system was saying it had a different result. After that I ran it again on HackerRank using the option custom input, but with the same input that gave me a bad answer error, but this time the answer was ok. Bugs appear everywhere, right? I will submit it with another language, still thinking about it. I wrote something to them, hopefully they will fix this bug. ...

October 4, 2016 · 2 min