To do comparision, we will note the time it takes to read 10^6 numbers from StdIn, store it into slice and then print all the numbers to StdOut.
As a step to make myself stronger in Go
, I started using it for competitive programming. I was using fmt
package for IO, but soon
I started getting timeout in IO heavy questions.
In this simple approach, we will use fmt.Scanf
for reading, and we will not be using any buffered IO.
package main
import (
"fmt"
)
func testIO() {
arr := []int{}
var n, t int
fmt.Scanf("%d", &n)
for i := 0; i < n; i++ {
fmt.Scanf("%d", &t)
arr = append(arr, t)
}
for _, val := range arr {
fmt.Printf("%d ", val)
}
}
func main() {
testIO()
}
Time :
For N : 10**6
real 0m8.417s
Now we will modify our code a little bit -
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func getInt(sc *bufio.Scanner) int {
sc.Scan()
out, _ := strconv.ParseInt(sc.Text(), 10, 0)
return int(out)
}
func takeIO() {
arr := []int{}
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
wt := bufio.NewWriter(os.Stdout)
defer wt.Flush()
n := getInt(sc)
for i := 0; i < n; i++ {
t := getInt(sc)
arr = append(arr, int(t))
}
for _, val := range arr {
fmt.Fprintf(wt, "%v\n", val)
}
}
func main() {
takeIO()
}
Time :
For N : 10**6
real 0m0.270s
We gained a significant reduction in time, with minimal changes in our code.
During this long, cold, and dreary winter break, I was surfing the web, passing the time (distracting myself from the meaningless monotonous life). I stumbled upon many blogs/webs such as Anish, Codehorror by StackOverflow’s founder, and how can I forget this, the greatest of all this .
Then I thought, I too must try to write and maintain my personal blog. And as much I know myself, I am sure I will lose interest in this and quit, falsely blaming my lack of time.
The stupid computer science student in me did not want to use any from the plethora of simple online tools available like Wix, or WordPress. Foolish me!! These tools are meant to ease up your life!! Instead, I decided to make it all from scratch. It did not go as planned, and later I resorted to using tools like Jekyll (and I loved it), to make it easier.
I haven’t decided what sort of wacky useless error-prone misleading kinds of stuff, I am gonna write here. Lets See.
So here I am. Wish me luck. Special thanks to Grammarly for hiding my indecorous English from you (◠‿◕).
Built this in jekyll will update all the steps involved soon…
Target : To write atleast two blogs in a month…Let’s see!