ataias
https://ataias.com.br/index.xml
Recent content on ataias
Hugo  gohugo.io
enus
POWERED BY [HUGO](//gohugo.io)  THEME: [HIKARI](//github.com/digitalcraftsman/hugohikaritheme)  © Ataias Pereira Reis
Tue, 28 Mar 2017 09:45:11 0300

Get number of common divisors in OCaml
https://ataias.com.br/2017/03/28/getnumberofcommondivisorsinocaml
Tue, 28 Mar 2017 09:45:11 0300
https://ataias.com.br/2017/03/28/getnumberofcommondivisorsinocaml
<p>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:</p>
<pre><code class="languageocaml">(* Need to check divisors just up to sqrt x *)
let max x = Int.of_float (sqrt x) > (+) 1;;
</code></pre>
<p>After that, I wrote a function to get the number of common divisors of a single number <code>n</code>. Inside it I wrote another function, <code>divs</code> responsible to get all the divisors up to the limit define in the <code>max</code> function. This is just half of the divisors. The other half is obtained by dividing <code>n</code> by its divisors and adding each result in the set. For instance, if <code>n</code> has divisors, up to <code>max n</code> in the set <code>set</code>, then I add the rest using:</p>
<pre><code class="languageocaml">let f s x = Set.add s (n / x) in
Set.fold set ~init:set ~f:f
</code></pre>
<p>In the end, the whole function to get the divisors is</p>
<pre><code class="languageocaml">let get_divisors n =
let c = Int.comparator in
(* Cap is the limit for the iterations *)
(* This is sqrt(n) *)
let cap = max (Float.of_int n) in
let set = Set.empty ~comparator:c in
let rec divs set i =
if n mod i = 0 then
let set = Set.add set i in
divs set (i+1)
else
if i > cap then set else divs set (i+1)
(* This set does not have all divisors
As the pairs are missing*)
in let set = divs set 1 in
(* Add the missing pairs *)
let f s x = Set.add s (n / x) in
Set.fold set ~init:set ~f:f;;
</code></pre>
<p>After that, I could just get the divisors of each input, intersect the sets and then get the length of this set, which would be the number of common divisors:</p>
<pre><code class="languageocaml">let get_number_common_divisors n m =
let divs_n = get_divisors n in
let divs_m = get_divisors m in
let common = Set.inter divs_n divs_m in
Set.length common;;
</code></pre>
<p>Finally, I needed some IO:</p>
<pre><code class="languageocaml">(* IO Code *)
(* When parsing with String.split,
some elements may be empty,
so we remove them *)
let remove_empty l =
let not_empty x = x <> "" in
List.filter ~f:not_empty l
(* Magic happens, returns list of numbers*)
let parse line =
let l = String.split line ~on:' ' in
let number_str = remove_empty l in
List.map number_str ~f:Int.of_string
let n_tests = read_int ();;
let () = for i = 1 to n_tests do
let line = read_line () in
let l = parse line in
let a, b = match l with
 x::y::tl > x, y
 _ > 0, 0 in
print_int (get_number_common_divisors a b);
print_newline ();
done
</code></pre>
<p>You can check the whole code on <a href="https://github.com/ataias/OCamlProblems/blob/master/get_divisors.ml">GitHub</a>. If you want to compile this code, you could use:</p>
<pre><code class="languagesh">$ corebuild get_divisors.native
</code></pre>
<p>An example of input/output:</p>
<pre><code># input
2
2 4
144 288
# output
2
15
</code></pre>
<p>Thanks for reading!</p>

Dedup chars in a string using OCaml
https://ataias.com.br/2017/03/27/dedupcharsinastringusingocaml
Mon, 27 Mar 2017 17:59:53 0300
https://ataias.com.br/2017/03/27/dedupcharsinastringusingocaml
<p>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:</p>
<pre><code># input
abcabczabczabc
# output
abcz
</code></pre>
<p>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 <a href="(http://caml.inria.fr/pub/old_caml_site/Examples/oc/basics/explode.ml)">here</a>. Those were auxiliary functions to help me to write <code>remove_all_dups</code>.</p>
<pre><code class="languageocaml">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);;
</code></pre>
<p>If you take a look at the function <code>remove_all_dups</code>, 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.</p>
<p>Thanks for reading!</p>
<p><em>Note</em>: After reading some more, I could write a much simpler code to dedup the string, with no need to write <code>implode</code> or <code>explode</code> by hand, they are already available at <code>Core.Std</code>:</p>
<pre><code class="languageocaml">(* This would be the whole code for the
program above, with the exception of IO *)
let dedup_string str =
String.to_list str
> List.dedup
> String.of_char_list;;
</code></pre>
<p>Nevertheless, this doesn’t guarantee the order. Anyway, if order is important, like in this problem, I could change <code>implode</code> by <code>String.of_char_list</code> and <code>explode</code> by <code>String.to_list</code> in the program shown before, avoiding to use <code>List.dedup</code>.</p>

Mingle strings in OCaml
https://ataias.com.br/2017/03/26/minglestringsinocaml
Sun, 26 Mar 2017 18:04:14 0300
https://ataias.com.br/2017/03/26/minglestringsinocaml
<p>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 <a href="http://caml.inria.fr/pub/old_caml_site/Examples/oc/basics/explode.ml">explode and implode strings </a>. 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.</p>
<pre><code># input
abc
xyz
# output
axbycz
</code></pre>
<pre><code class="languageocaml">(* OCaml Code now! *)
open Core.Std;;
(* Read the two input strings *)
let a = read_line();;
let b = read_line();;
let mingle a b =
let la = String.length a in
let lb = String.length b in
let total = la + lb in
let s = String.create total in
let rec m i =
(* j = index for inputs *)
let j = i / 2 in
if i > (total  1) then s
else let () =
(* i = index for output *)
s.[i] < a.[j];
s.[i+1] < b.[j];
in m (i + 2); in
m 0;;
print_string (mingle a b)
</code></pre>
<p>In OCaml, it is important for the <code>then</code> and <code>else</code> parts of the <code>if</code> to return the same type. Part of the problem was a side effect, setting indices, and had no return type. The <code>let () =</code> part lets me ignore it and just consider where it is returning the actual string.</p>

List Replication
https://ataias.com.br/2017/03/24/listreplication
Fri, 24 Mar 2017 19:57:15 0300
https://ataias.com.br/2017/03/24/listreplication
<p>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:</p>
<pre><code>3 // # of repetitions
1 // first number ...
2
3
4 // end of input, last number
</code></pre>
<p>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.</p>
<pre><code class="languageOCaml">(* This function was given by HackerRank *)
let rec read_lines () =
try let line = read_line () in
int_of_string (line) :: read_lines()
with
End_of_file > []
(* I filled this function *)
let f n arr =
let rec repeat value n =
if n > 0 then
value::(repeat value (n1))
else [] in
let rec r n arr =
match arr with
 [] > []
 hd::tl > (repeat hd n) @ (r n tl) in
r n arr
(* This function was given by HackerRank *)
let () =
let n::arr = read_lines() in
let ans = f n arr in
List.iter (
fun x > print_int x;
print_newline ()) ans;;
</code></pre>
<p>This was not hard. Nevertheless, when I write code like this, I think that solutions with arrays would be much more efficient. There are multiple cases of memory allocations in that code, but it could have been done only once in the function <code>$f(n, arr)$</code>. Why? If you have a list of <code>$m$</code> elements and you want to repeat each <code>$n$</code> times, you just allocate memory for an array of size <code>$m\cdot n$</code> and then fill the repeated elements, using a simple loop.</p>
<p>The way function <code>$f$</code> is written does not use loops, being basically functional, avoiding imperative patterns. This has a positive side: it is easier to reason about the code. The downside I already mentioned. Which pattern to use depends on what is the main concern and how big the inputs will be.</p>
<p>Thanks for reading!</p>

Hello World printing in OCaml
https://ataias.com.br/2017/03/24/helloworldprintinginocaml
Fri, 24 Mar 2017 16:56:00 0300
https://ataias.com.br/2017/03/24/helloworldprintinginocaml
<p>Another simple problem from HackerRank is to print <em>Hello World</em> 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:</p>
<pre><code class="languageOCaml">open Core.Std
let n = read_int ();;
let rec print_hello n =
if n > 0 then begin
printf "Hello World\n";
print_hello (n1);
end else ();;
print_hello n
</code></pre>
<p>Problems I had: I lost some some time to discover the <em>;;</em> was required to make it compile properly. I am not sure exactly why yet. For instance, if I use <em>else ();</em> (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.</p>
<p>Thanks for reading!</p>

Compare Triplets in OCaml
https://ataias.com.br/2017/03/24/comparetripletsinocaml
Fri, 24 Mar 2017 12:20:55 0300
https://ataias.com.br/2017/03/24/comparetripletsinocaml
<p>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 <em>“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”</em>.</p>
<p>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:</p>
<pre><code class="languagebash"># input
5 6 7
3 6 10
# output
1 1 # the score for Alice, then for Bob
</code></pre>
<p>The end result is the code below.</p>
<pre><code class="languageocaml">open Core.Std
type rating = {
x1 : int;
x2 : int;
x3 : int;
}
let get_line () =
In_channel.input_line In_channel.stdin
(* When parsing with String.split,
some elements may be empty,
so we remove them *)
let remove_empty l =
let not_empty x = x <> "" in
List.filter ~f:not_empty l
(* Magic happens, returns list of numbers*)
let parse line =
let l = String.split line ~on:' ' in
let number_str = remove_empty l in
List.map number_str ~f:Int.of_string
let to_record list =
match list with
 x1::x2::x3::[] > {x1; x2; x3}
(* Not having the 3 numbers is an error*)
 _ > assert false;;
let read_triplet () =
match get_line () with
 None > [0;0;0]
 Some x > parse x
let a = to_record (read_triplet ())
let b = to_record (read_triplet ())
let grade x y =
let f a b = if a > b then 1 else 0 in
(f x.x1 y.x1) +
(f x.x2 y.x2) +
(f x.x3 y.x3)
let grade_a = grade a b
let grade_b = grade b a
let () = printf "%d %d" grade_a grade_b
</code></pre>
<p>My comments: this was kind of hard. Why? It has been almost three years since I coded in OCaml and the concepts are not fresh on my mind of how I coded at the time. For instance, initially I was pattern matching on two elements of a list using a recursive function instead of the three elements, without a recursive function. This was cumbersome and I think it is much better in the final version, matching with 3 elements and raising an error. One thing that caused me problems was trying to use variables with first letters capitalized, as this is reserved for modules.</p>
<p>Note: later I discovered there is a function called <code>read_int</code> in OCaml. This could have made my life simpler, I think.</p>
<p>Thanks for reading!</p>

30 days of code in Go: Day 24  Djikstra's algorithm
https://ataias.com.br/2016/11/06/30daysofcodeingoday24djikstrasalgorithm
Sun, 06 Nov 2016 15:39:13 0200
https://ataias.com.br/2016/11/06/30daysofcodeingoday24djikstrasalgorithm
<p>Hi there! Today I implemented <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Djikstra’s algorithm</a> to find the minimum path between one source vertex and all the other vertices in the graph. This algorithm was devised in 1956 by the Dutch computer scientist Edsger W. Djikstra. It is quite fast having a complexity of <code>$O(n\log n)$</code> when implemented with an auxiliary heap structure.</p>
<p>To implement the heap in Go, I made use of the package <a href="https://golang.org/pkg/container/heap/">heap</a>. The package website also has an example of how to use and mine is basically a copy of it. I just changed one line. The code is available below. The graph structure was made basically with maps.</p>
<pre><code class="languageGo">package main
import (
"container/heap"
"fmt"
"time"
)
// An Item is something we manage
// in a priority queue.
type Item struct {
// a node of a graph
value *Node
// The priority of the item in the queue.
priority int
// The index of the item in the heap.
index int
}
// A PriorityQueue implements
//heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
return pq[i].priority < pq[j].priority
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n1]
item.index = 1 // for safety
*pq = old[0 : n1]
return item
}
// update modifies the priority
// and value of an Item in the queue.
func (pq *PriorityQueue) update(
item *Item, value *Node, priority int) {
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
}
type Node struct {
// beginning of vertex
Id int
// map of end vertex to weight
Edges map[int]int
}
// input is a map of vertex id to node pointer
// and the source vertex
// there are outputs: distances of
// each vertex to the source and
// the previous node that a vertex needs to go
// to follow the best path
func Dijkstra(nodes map[int]*Node, source int)
(map[int]int, map[int]int) {
// will be used for heap
Q := make(PriorityQueue, len(nodes))
// maintain reference to all items
heapItems := make(PriorityQueue, len(nodes))
distances := make(map[int]int)
previous := make(map[int]int)
// distance from source to source is 0
distances[source] = 0
for k, v := range nodes {
if k != source {
// unknown distance
distances[k] = 1000000
// undefined
previous[k] = 1
}
Q[k1] = &Item{
value: v,
priority: distances[k],
index: k  1}
heapItems[k1] = Q[k1]
}
heap.Init(&Q)
for Q.Len() > 0 {
item := heap.Pop(&Q).(*Item)
node := item.value
for end, weight := range node.Edges {
alt := item.priority + weight
if alt < distances[end] {
distances[end] = alt
previous[end] = node.Id
Q.update(
heapItems[end1], nodes[end], alt)
}
}
}
return distances, previous
}
func CreateEdge(
nodes map[int]*Node, begin, end int, weight int) {
if nodes[begin] == nil {
nodes[begin] = &Node{
Id: begin,
Edges: make(map[int]int)}
}
if nodes[end] == nil {
nodes[end] = &Node{
Id: end,
Edges: make(map[int]int)}
}
nodes[begin].Edges[end] = weight
}
func main() {
start := time.Now()
nodes := make(map[int]*Node)
begin := 0
end := 0
weight := 0
lines := 0
value := 0
for {
if value == 0 {
n, _ := fmt.Scanf("%d", &begin)
if n == 0 {
break
}
} else {
begin = end
}
lines += 1
value = 0
for {
n, _ := fmt.Scanf("%d,%d", &end, &weight)
if n == 0 {
break
}
if n == 1 {
// if we read only one value, this is
// from the next line
value = end
break
}
CreateEdge(nodes, begin, end, weight)
}
}
fmt.Printf("Lines read: %d\n", lines)
elapsed := time.Since(start)
fmt.Printf("IO Took %s\n", elapsed)
start = time.Now()
distances, _ := Dijkstra(nodes, 1)
for i := 1; i <= len(nodes); i++ {
fmt.Printf("Node: %d; Distance: %d\n",
i, distances[i])
}
elapsed = time.Since(start)
fmt.Printf("Computation Took %s\n", elapsed)
}
</code></pre>
<h3 id="example">Example</h3>
<h4 id="input">Input</h4>
<pre><code>1 2,1 8,2
2 1,1 3,1
3 2,1 4,1
4 3,1 5,1
5 4,1 6,1
6 5,1 7,1
7 6,1 8,1
8 7,1 1,2
</code></pre>
<h4 id="output">Output</h4>
<pre><code>Lines read: 8
IO Took 1.007893ms
Node: 1; Distance: 0
Node: 2; Distance: 1
Node: 3; Distance: 2
Node: 4; Distance: 3
Node: 5; Distance: 4
Node: 6; Distance: 4
Node: 7; Distance: 3
Node: 8; Distance: 2
Computation Took 25.511µs
</code></pre>
<p>If you have any suggestions or comments, let me know! Thanks for reading!</p>

30 days of code in Go: Day 23  Minimum Cut of Graph
https://ataias.com.br/2016/10/29/30daysofcodeingoday23minimumcutofgraph
Sat, 29 Oct 2016 16:32:51 0200
https://ataias.com.br/2016/10/29/30daysofcodeingoday23minimumcutofgraph
<p>Hi there! Today’s program aims to solve the <a href="https://en.wikipedia.org/wiki/Minimum_cut">minimum cut problem</a>. It is another one that I learned in <em>Algorithms: Design and Analysis, Part 1</em> course from Coursera. A cut is partition of a graph and partitioning a graph means dividing it into two disjoint subsets of vertices. The minimum cut then would be such that the number of edges going from one partition to the other is minimal. Below is a simple example of a graph with 4 nodes. There are two minimum cuts for it, namely cutting the node 1 or 4 out. Each one of these cuts has 2 edges going across the partitions. The goal of my program is to show what this number of edges is, not caring what the exact number of minimum cuts is.</p>
<p><img src="https://ataias.com.br/assets/media/2016/10/graph4nodes.jpg" alt="4 Node Graph" /></p>
<p>The algorithm implemented is called <a href="https://en.wikipedia.org/wiki/Karger%27s_algorithm">Random Contraction Algorithm</a>. It was invented by Karger in the early 1990s. As the name implies, it has some randomness in it. The basics of it are simple: given a graph, choose an edge and contract its vertices into one. Do this until there are only two nodes left. This may or may not give the minimum cut, so it has to be run multiple times to actually give the minimum cut with high probability. I implemented a loop that calls this algorithm and saves the number of crossing edges in the minimum cut so far. It is presented below.</p>
<pre><code class="languageGo">package main
import (
"bufio"
"bytes"
"encoding/gob"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
"time"
)
func randomContraction(
nodes map[int]*Node,
maxNode int) int {
for len(nodes) > 2 {
start := 0
end := 0
// get two keys at random
findingEdge:
for s, node := range nodes {
for e, _ := range node.Edges {
start = s
end = e
break findingEdge
}
}
maxNode++
nodes[maxNode] = &Node{
Id: maxNode,
Edges: make(map[int]int)}
for e, v := range nodes[start].Edges {
if e != end {
nodes[maxNode].Edges[e] += v
nodes[e].Edges[maxNode] += nodes[e].Edges[start]
delete(nodes[e].Edges, start)
}
}
for e, v := range nodes[end].Edges {
if e != start {
nodes[maxNode].Edges[e] += v
nodes[e].Edges[maxNode] += nodes[e].Edges[end]
delete(nodes[e].Edges, end)
}
}
delete(nodes, start)
delete(nodes, end)
}
smallestCut := maxNode * 100
for _, v := range nodes {
thisCut := 0
for _, weight := range v.Edges {
thisCut += weight
}
if thisCut < smallestCut {
smallestCut = thisCut
}
}
return smallestCut
}
type Node struct {
Id int // beginning of vertex
Edges map[int]int // end > weight
}
func main() {
start := time.Now()
N := 0
fmt.Scanf("%d", &N)
nodes := make(map[int]*Node)
fmt.Printf("N = %d\n", N)
maxNode := 0
in := bufio.NewReaderSize(os.Stdin, 2000)
for i := 0; i <= N; i++ {
aux := 0
input, err := in.ReadString('\n')
if err != nil {
break
}
numbers := strings.Fields(input)
if len(numbers) <= 0 {
continue
}
aux, _ = strconv.Atoi(numbers[0])
if aux > maxNode {
maxNode = aux
}
if nodes[aux] == nil {
nodes[aux] = &Node{
Id: aux,
Edges: make(map[int]int)}
}
currentNode := nodes[aux]
for k := 1; k < len(numbers); k++ {
aux, _ = strconv.Atoi(numbers[k])
if nodes[aux] == nil {
// create end vertex if not existent
nodes[aux] = &Node{
Id: aux,
Edges: make(map[int]int)}
}
currentNode.Edges[aux] += 1
}
}
smallestCut := N
//encoding
var mod bytes.Buffer
enc := gob.NewEncoder(&mod)
dec := gob.NewDecoder(&mod)
iterations := int(
float64(N*N) * math.Log(float64(N)))
for i := 1; i <= iterations; i++ {
err := enc.Encode(nodes)
if err != nil {
log.Fatal("encode error:", err)
}
nodesToContract := make(map[int]*Node)
err = dec.Decode(&nodesToContract)
if err != nil {
log.Fatal("decode error:", err)
}
cut := randomContraction(
nodesToContract, maxNode)
if cut < smallestCut {
smallestCut = cut
fmt.Printf("New smallest cut: %d\n",
smallestCut)
}
if i%200 == 0 {
fmt.Printf("Current iteration: %d\n", i)
}
}
fmt.Printf("Smallest Cut after contraction: %d\n",
smallestCut)
elapsed := time.Since(start)
fmt.Printf("Total iterations: %d\n",
iterations)
fmt.Printf("Random contractions took %s\n",
elapsed)
}
</code></pre>
<p>The biggest challenge was reading the input file correctly. This happened because I was not used at reading this in Go. Firstly, I tried to read the input file and use sprintf to analyse each line, but I couldn’t find a solution to read an unknown number of variables in the strings.</p>
<p>The file has the total number of nodes in the first line and then the other lines have information about the connections for each node. The input file below is the same as the picture presented in the beginning of this post.</p>
<pre><code class="languagebash">4
1 2 3 # indicates node 1 is connected to nodes 2 and 3
2 1 3 4
3 1 2 4
4 2 3
</code></pre>
<p>The output for this case is</p>
<pre><code class="languagebash">N = 4
New smallest cut: 3
New smallest cut: 2
Smallest Cut after contraction: 2
Total iterations: 22
Random contractions took 883.278µs
</code></pre>
<p>With a little tweaking, it can also show what are the edges in each partition. <a href="https://ataias.com.br/assets/media/2016/10/reduct_with_sets.go">Here</a> is an implementation that adds sets of vertices to it. In the end, it is just needed to print the numbers in the sets of the two nodes remaining. At this time, I couldn’t find a native implementation of sets in Go. The one in the example was based on <a href="http://softwareengineering.stackexchange.com/questions/177428/setsdatastructureingolang">this</a> with my own additions.</p>
<p>That’s all for this post! Thanks for reading!</p>

30 days of code in Go: Day 22  QuickSort
https://ataias.com.br/2016/10/15/30daysofcodeingoday22quicksort
Sat, 15 Oct 2016 07:47:31 0300
https://ataias.com.br/2016/10/15/30daysofcodeingoday22quicksort
<p>Hi there! Today’s challenge is another algorithm that I learned more in detail in the <em>Algorithms: Design and Analysis, Part 1</em> course from Coursera: <em>QuickSort</em>. This algorithm chooses a pivot and does a partial sort around that pivot, having all elements less than the pivot to its left and all greater to its right, considering we want the number in increasing order. The main function is <code>qsort</code> which calls the function to choose a pivot and another to partition around the pivot.</p>
<p>The way I learned in class considered the pivot to be the first element of the array and then I had indexes <code>i</code> and <code>j</code> to separate the portions of the array. All elements to the left of position <code>i</code> were smaller than the pivot, excluding the pivot itself in position 0. This left all elements greater than the pivot to the right of position <code>i</code>. Something I took some time to understand was that this is actually generic. I can choose any pivot as long as I swap it with the first element.</p>
<p>There were three ways of choosing a pivot that I considered when doing the assignment, but here I present just the last one, namely the median of three method. I consider the elements in the first, middle and last positions in the array and then I take the median of these three elements to be the pivot. The <code>getPivot</code> function returns the index of the pivot so that the <code>qsort</code> function can use it. In the end of a <code>qsort</code> call, the element is sorted in place and the number of comparisons is returned. For each recursive call of an array of size <code>m</code>, I count <code>m1</code> comparisons.</p>
<p>The solution is presented below. Notice I expect the number of elements <code>n</code> in the array as the first input and then <code>n</code> elements separated by <code>\n</code>.</p>
<pre><code class="languageGo">package main
import (
"fmt"
)
// returns the index of the median here
func argmedian(index, values []int) int {
swaps := 1
// simple bubble sort to sort three values
// and then we return the middle value
for swaps > 0 {
swaps = 0
for i := 0; i < len(index)1; i++ {
if values[i+1] < values[i] {
swap(values, i, i+1)
swap(index, i, i+1)
swaps++
}
}
}
return index[1]
}
func getPivot(a []int) int {
index := make([]int, 3)
values := make([]int, 3)
index[0] = 0
values[0] = a[0]
if len(a)%2 == 0 {
index[1] = len(a)/2  1
values[1] = a[len(a)/21]
} else {
index[1] = len(a) / 2
values[1] = a[len(a)/2]
}
index[2] = len(a)  1
values[2] = a[len(a)1]
return argmedian(index, values)
}
func swap(a []int, i, j int) {
a[i], a[j] = a[j], a[i]
}
func partition(a []int, pivot_i int) (int, int) {
swap(a, pivot_i, 0)
p := a[0] // pivot
finalPlace := 0
if len(a) > 2 {
i := 0
pivotNotInPlace := false
for j := 1; j < len(a); j++ {
if a[j] < p {
i++
swap(a, i, j)
pivotNotInPlace = true
}
}
// pivot in rightful position
// case of len(a) > 2
if pivotNotInPlace {
a[0] = a[i]
a[i] = p
finalPlace = i
}
} else if len(a) == 2 {
if a[1] < p {
a[0] = a[1]
a[1] = p
finalPlace = 1
}
}
return finalPlace, len(a)  1
}
func qsort(a []int) int {
n := 0 // number of comparisons
if len(a) <= 1 {
return n
}
pivot_index := getPivot(a)
i, n0 := partition(a, pivot_index)
n += n0
n += qsort(a[:i])
n += qsort(a[i+1:])
return n
}
func main() {
// Input file has N
// in the first line
N := 0
fmt.Scanf("%d\n", &N)
// allocate memory
X := make([]int, N)
for i := 0; i < N; i++ {
fmt.Scanf("%d\n", &X[i])
}
// n is the number of comparisons
// quicksort has done
n := qsort(X)
for i := 0; i < N; i++ {
fmt.Printf("%d\n", X[i])
}
fmt.Printf("#Comparisons: %d\n", n)
}
</code></pre>
<p>That’s all for this day of coding in Go. Thanks for readings!</p>

30 days of code in Go: Day 21  Extra Long Factorials
https://ataias.com.br/2016/10/12/30daysofcodeingoday21extralongfactorials
Wed, 12 Oct 2016 06:38:39 0300
https://ataias.com.br/2016/10/12/30daysofcodeingoday21extralongfactorials
<p>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 <code>$2^{64}1$</code>. This is a pretty huge number, but if you try to compute the factorial of a number like <code>25!</code>, 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 <a href="https://golang.org/pkg/math/big/">Big</a>. My solution is given below.</p>
<pre><code class="languageGo">package main
import (
"fmt"
"math/big"
)
/*tailrecursive factorial function*/
func factorial(
n *big.Int,
accumulate *big.Int,
one *big.Int) *big.Int {
// cmp returns 1 if n < 1
// returns 0 if n == 1
// so here I check n <= 1
if n.Cmp(one) < 0  n.Cmp(one) == 0 {
return accumulate
}
accumulate.Mul(accumulate, n)
n.Sub(n, one)
return factorial(n, accumulate, one)
}
func main() {
var n int64
fmt.Scanf("%d\n", &n)
N := big.NewInt(n)
accumulate := big.NewInt(1)
var one big.Int
one.SetInt64(1)
result := factorial(N, accumulate, &one)
fmt.Printf("%d\n", result)
}
</code></pre>
<p>As you may have seen, I have to call methods instead of using the normal mathematical operations available. This was the most annoying part basically. The factorial I wrote is tailrecursive. This means it doesn’t take as much memory as the naive solution that let the function calls stack.</p>
<p>Thanks for reading!</p>

30 days of code in Go: Day 20  Count inversions with Merge Sort
https://ataias.com.br/2016/10/09/30daysofcodeingoday20countinversionswithmergesort
Sun, 09 Oct 2016 06:09:27 0300
https://ataias.com.br/2016/10/09/30daysofcodeingoday20countinversionswithmergesort
<p>Hi there! Today’s post is not from HackerRank. This was an assignment that I solved for the <em>Algorithms: Design and Analysis, Part 1</em> course from Coursera. The goal is to implement an algorithm presented in the videos. It was explained in high level and not considering edge cases. I first tried to do it in <code>C++</code> but it was taking me more time than I wanted to spend and then I switched to <code>Go</code> and it was blazing fast to code. What really helped me to solve it fast was the idea of a <code>slice</code> in <code>Go</code>. Slices can be partitioned easily. For instance</p>
<ul>
<li><code>P := a[:m]</code>, <code>P</code> is a slice with all elements up to index <code>m</code> exclusively from <code>a</code></li>
<li><code>Q := a[m:]</code>, <code>Q</code> is a slice with all elements from index <code>m</code> inclusively to the end of <code>a</code></li>
</ul>
<p>In <code>C++</code>, the above operations would require me more lines of code. I would need to check the end of my vector <code>a</code>, declare two new <code>vector<int></code> <code>P</code> and <code>Q</code> and then add half of the elements in each newly allocated vector using a <code>for</code> loop.</p>
<p>The assignment required to me to count the inversions of a given unordered list. Below is an example.</p>
<pre><code class="languagepython">input = [6, 5, 4, 3, 2, 1]
# list after sorting
output = [1, 2, 3, 4, 5, 6]
# number of inversions found
inversions = 15
</code></pre>
<p>The number of inversions is maximum when the list is in reverse order like the example above. When we look at 6, we see there are five elements out of order after it. Then looking at 5 we see four elements out of order after it. In the end, we count 5+4+3+2+1 = 15 inversions for the example. The formula for the maximum number of inversions in a list of integers of size <code>$n$</code> is <code>$$f(n) = \left(\begin{array}{c}n\\ 2\end{array}\right) = \frac{n(n1)}{2}.$$</code></p>
<p>My solution is presented below and it requires the first input to be <code>N</code>, the number of integers that will be fed to the program, and then the <code>N</code> integers need to be separated by <code>\n</code>. I just did that because the input they gave me was a text file with all numbers separated by <code>\n</code>.</p>
<pre><code class="languageGo">package main
import (
"fmt"
"math"
)
// result is the merged list and the
// number of inversions
func merge(a []int, b []int, n0 int) ([]int, int) {
n := 0 // number of inversions
m := len(a) + len(b)
result := make([]int, m)
i := 0
j := 0
// print(b)
for k := 0; k < m; k++ {
//  edge cases 
if i == len(a) {
result[k] = b[j]
j++
continue
}
if j == len(b) {
result[k] = a[i]
i++
continue
}
//  general cases 
if a[i] < b[j] {
result[k] = a[i]
i++
} else {
result[k] = b[j]
j++
// add number of inversions
// for current merging
n += len(a)  i
}
}
return result, n + n0
}
func merge_sort(a []int) ([]int, int) {
n := 0
if len(a) > 1 {
// divide and call merge sort
m := int(math.Ceil(float64(len(a)) / 2.0))
P := a[:m]
Q := a[m:]
result1, n1 := merge_sort(P)
result2, n2 := merge_sort(Q)
return merge(result1, result2, n1+n2)
}
return a, n
}
func main() {
// Input file has N
// in the first line
// indicating how many
// lines the file has
N := 0
fmt.Scanf("%d\n", &N)
// allocate memory
X := make([]int, N)
for i := 0; i < N; i++ {
fmt.Scanf("%d\n", &X[i])
}
// Ignore sorted list,
// if needed just change _
// by a name
_, n := merge_sort(X)
fmt.Printf("#Inversions: %d\n", n)
}
</code></pre>
<p>Running</p>
<pre><code class="languagego">$ go build merge_sort.go
$ ./merge_sort < IntegerArray.txt
#Inversions: 2407905288
</code></pre>
<p>The main difficulties I had were the edge cases. They were not presented in class and I was having weird bugs saying I was trying to access an out of bounds element of the slice.</p>
<p>That’s all for this assignment, thanks for reading!</p>

30 days of code in Go: Day 19  Binomial Distribution II
https://ataias.com.br/2016/10/06/30daysofcodeingoday19binomialdistributionii
Thu, 06 Oct 2016 06:38:12 0300
https://ataias.com.br/2016/10/06/30daysofcodeingoday19binomialdistributionii
<p>Hi there! Today’s problem is very similar to the <a href="https://ataias.com.br/2016/10/05/30daysofcodeingoday18binomialdistributioni">last day</a>, again using a binomial distribution.</p>
<h3 id="question">Question</h3>
<p>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</p>
<ol>
<li>No more than two rejects?</li>
<li>At least two rejects?</li>
</ol>
<p>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 <code>$$P_{x \le 2} = \sum_{i=0}^2 b(i, 10, 0.12),$$</code> while for the case of at least two rejects it is <code>$$P_{x \ge 2} = \sum_{i=2}^{10} b(i, 10, 0.12).$$</code></p>
<h3 id="code">Code</h3>
<p>My solution is pretty similar to my last one and is presented below. Just the main function was changed.</p>
<pre><code class="languageGo">package main
import (
"fmt"
"math"
)
func factorial(n int) int {
if n <= 1 {
return 1
} else {
return n * factorial(n1)
}
}
func b(x, n int, p float64) float64 {
comb_n_x := float64(factorial(n) /
factorial(x) /
factorial(nx))
p_x := math.Pow(p, float64(x))
q_n_x := math.Pow(1.0p, float64(nx))
return comb_n_x * p_x * q_n_x
}
func main() {
percentage := 0.0
fmt.Scanf("%f", &percentage)
// probability of a defect
p := percentage / 100.0
// total number of trials
n := 0
fmt.Scanf("%d", &n)
// probability of having
// no more than 2 rejects
probability1 := 0.0
for i := 0; i <= 2; i++ {
probability1 += b(i, n, p)
}
fmt.Printf("%.3f\n", probability1)
// probability of having
// at least 2 rejects
probability2 := 0.0
for i := 2; i <= n; i++ {
probability2 += b(i, n, p)
}
fmt.Printf("%.3f\n", probability2)
}
</code></pre>
<p>Below I ran it and I commented the output.</p>
<pre><code class="languagebash">$ go build day_19.go
$ ./day_19
12 10
0.891 # P of <= 2 defects
0.342 # P of >= 2 defects
</code></pre>
<p>That’s all! Thanks for reading!</p>

30 days of code in Go: Day 18  Binomial Distribution I
https://ataias.com.br/2016/10/05/30daysofcodeingoday18binomialdistributioni
Wed, 05 Oct 2016 20:47:01 0300
https://ataias.com.br/2016/10/05/30daysofcodeingoday18binomialdistributioni
<p>Hi there! Today’s challenge from HackerRank was a little more involved. The challenge is <em>Given the ratio</em> <code>$1.09 : 1$</code> <em>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?</em>. Before actually solving that, it is important to understand a Bernoulli trial and also the Binomial Distribution.</p>
<h3 id="bernoullitrial">Bernoulli trial</h3>
<p>According to <a href="https://en.wikipedia.org/wiki/Bernoulli_trial">Wikipedia</a>, 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.</p>
<p>Regarding this problem, each random experiment is having a baby and the probability of “success” is the probability of having a baby boy that is <code>$p = \frac{1.09}{1.09 + 1}$</code>. If it asked for girls instead of boys in the end, success would be having a baby girl and this probability would be <code>$p = \frac{1}{1.09 + 1}$</code>.</p>
<h3 id="binomialdistribution">Binomial Distribution</h3>
<p>According to <a href="https://en.wikipedia.org/wiki/Binomial_distribution">Wikipedia</a>, the binominal distribution with parameters <code>$n$</code> and <code>$p$</code> is the discrete probability distribution of the number of successes <code>$x$</code> in a sequence of <code>$n$</code> independent Bernoulli trials, each having a probability of success <code>$p$</code>. It is given by the formula <code>$$b(x,n,p) = \left(\begin{array}{c}n\\ x\end{array}\right) p^x (1p)^{(nx)}.$$</code></p>
<p>For the case in which we want the probability of having at least three boys for a family with 6 children, we sum the values of the binomial distribution: <code>$$\mathrm{Pr} = \sum_{i=3}^{6} b(i,6,p).$$</code></p>
<h3 id="code">Code</h3>
<p>My solution is given below.</p>
<pre><code class="languageGo">package main
import (
"fmt"
"math"
)
func factorial(n int) int {
if n <= 1 {
return 1
} else {
return n * factorial(n1)
}
}
func b(x, n int, p float64) float64 {
comb_n_x := float64(factorial(n) /
factorial(x) /
factorial(nx))
p_x := math.Pow(p, float64(x))
q_n_x := math.Pow(1.0p, float64(nx))
return comb_n_x * p_x * q_n_x
}
func main() {
// reading the proportion
// of boys to girls
boys := 0.0
fmt.Scanf("%f", &boys)
girls := 0.0
fmt.Scanf("%f", &girls)
// probability of having a boy
p := boys / (girls + boys)
// total number of trials
n := 6
// probability of having
// at least 3 boys
probability := 0.0
for i := 3; i <= n; i++ {
probability += b(i, n, p)
}
fmt.Printf("%.3f\n", probability)
}
</code></pre>
<p>That’s all for today! Thanks for reading!</p>

30 days of code in Go: Day 17  Standard Deviation
https://ataias.com.br/2016/10/04/30daysofcodeingoday17standarddeviation
Tue, 04 Oct 2016 20:20:19 0300
https://ataias.com.br/2016/10/04/30daysofcodeingoday17standarddeviation
<p>Hi there! Today’s challenge was to compute standard deviation of an array of data given the formula <code>$$\sigma = \sqrt{\frac{\sum_{i=0}^{N1} (x_i  \mu)^2}{N}},$$</code> where <code>$$\mu = \frac{\sum_{i=0}^{N1} x_i}{N}.$$</code></p>
<p>The first input to the program is <code>N</code> and then <code>N</code> integers are fed to the program in sequence. My solution is given below.</p>
<pre><code class="languageGo">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)
}
</code></pre>
<p>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 <em>custom input</em>, 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.</p>
<p>That’s all for today! Thanks for reading!</p>

30 days of code in Go: Day 16  Interquartile Range
https://ataias.com.br/2016/10/03/30daysofcodeingoday16interquartilerange
Mon, 03 Oct 2016 20:57:40 0300
https://ataias.com.br/2016/10/03/30daysofcodeingoday16interquartilerange
<p>Hi there! Today’s challenge is quite similar to the <a href="https://ataias.com.br/2016/10/01/30daysofcodeingoday15quartiles">last one</a>. Again, there are quartiles, but the input is a little different and the output is the interquartile range: <code>$Q_3  Q_1$</code>. The first input is <code>$n$</code> followed by an array <code>$X$</code> of size <code>$n$</code> with our data, but the frequencies of each point are included in another array of <code>$n$</code> elements, <code>$F$</code>, that is the next input. After reading this we need to construct the actual data array <code>$S$</code>. My solution is below.</p>
<pre><code class="languageGo">package main
import (
"fmt"
"sort"
)
// assumes already sorted
func getMedian(a []int) float64 {
n := len(a)
if n%2 == 0 {
return float64(a[n/2]+a[n/21]) / 2.0
}
return float64(a[n/2])
}
func sum(a []int) int {
sum := 0
for i := 0; i < len(a); i++ {
sum += a[i]
}
return sum
}
func main() {
N := 0
fmt.Scanf("%d", &N)
// allocate memory
X := make([]int, N)
F := make([]int, N)
// read numbers from stdin
for i := 0; i < N; i++ {
fmt.Scanf("%d", &X[i])
}
for i := 0; i < N; i++ {
fmt.Scanf("%d", &F[i])
}
// construct array from numbers
// and frequencies
S := make([]int, sum(F))
k := 0
for i := 0; i < len(S); {
for j := 0; j < F[k]; j++ {
S[i+j] = X[k]
}
i += F[k]
k++
}
// sort
sort.Ints(S)
n := len(S)
var Q1, Q3 float64
// get quartiles
Q1 = getMedian(S[0 : n/2])
if n%2 == 0 {
Q3 = getMedian(S[n/2:])
} else {
Q3 = getMedian(S[n/2+1:])
}
fmt.Printf("%.1f\n", Q3Q1)
}
</code></pre>
<p>The biggest problem I had was actually constructing <code>$S$</code>. I simply forgot to construct it the first time and I was thinking the problem was in the median function, but it was fine. When I noticed I forgot it, it was quite easy to solve.</p>