The code challenging platforms like HackerRank or CodeEval tests the logical ability and programming ability of a coder. Dynamic languages gives us the edge in developing programs faster. The algorithms which require huge computation may lead to timeouts with interpreters. Go is a compiled and disciplined language which can do very well in the competitive programming world. Beginners always feel hard to start Go because it is so strict. At the same time it is so sweet with type inferences and out of box built-in library.
These are the most essential things you need to know before jumpstart coding in Golang.
Input and Output
Even though many tutorials describes many ways to read input and print output, still beginners of Golang finds it hard to start. So I will cover the basic input/output pattern in Golang.
Taking a line of input and displaying it
Input ends with return key
$ go run input.go Gopher Hello Gopher
Above code just creates a Reader which is attached to STDIN. In order to accept input ReadString method is used. A new line (\n) is used here to identify the end of input.
Now let us see the variations in printing to STDOUT
fmt.Println("Something......") // prints a new line after output fmt.Printf("%d + %d = %d", x, y, z) // formats the output string as per adjustments str := fmt.Sprintf("%d + %d = %d", x, y, z) // used for interpolating values into a string
In any programming language type conversion is the most common thing. Let us see how we do type conversions in Go.
$ go run conversions.go 34 12.34 false
We can also convert an Integer, Float value to a string using Iota method of strconv
i := 10 strVal, _ = strconv.Iota(i)
If we observe carefully, all methods of strconv are returning two values not one. The first value is the actual result, whereas "_" contains the error message if the operation fails. If we plan to handle the error wisely then we can use it. If the operation is successful, it stores nil into err.
i := 10 // Now you can use err if something goes wrong strVal, err = strconv.Iota(i)
Make Array Slices Your Great Friend
In other programming languages, Arrays and Lists are main storing data structures of data. But in Go, you must use slices. Here frequent usage of slices is essential in competitive programming.
$ go run slices_test.go [Naren Saikiran manoj Harish] [Naren Saikiran manoj] [Naren manoj]
Practice playing with slices more and more to get familiar with. One word of caution. The indexing of slice is immutable. You need to reassign new slice to existing one after an operation.
String Processing & Cleaning
In any coding competition, we need to process strings a lot. String processing includes
- Trimming the spaces
- Splitting using separators
Now we are going to see the most straightforward way of doing that. In coding challenges we usually input no of test cases and values for each test case.
$ go run string_process.go 2 12 23 34 [12 23 34] 54 67 78 [54 67 78]
So we have two methods for splitting and stripping of strings.
These are equivalent to Python's trim() and split() builtin methods
Using Math library
While using math library of Golang, you should be careful about types of arguments passed and type the operation results. For example for finding Absolute value of a number, You need to pass a float64 number to the math.Abs funtion.
import "math" num := -10 absNum := math.Abs(num) // Throws error since Abs function only accept float64 absNum := math.Abs(float64(num)) // fine!
So you should always refer language manual to see type casting.
Using wild card format option in Printf
We all know that using format options we can customize the width and precision of output while using Printf.
n := 10.666 fmt.Printf("%12.4f", n)
This actually tells Go to print a float value with 12 spaces width and round it to 4 floating points. But what if that 12 width should be supplied programatically. Here is a wildcard trick for that.
n,s := 10.666, 12 fmt.Printf("%*.4f",s, n)
This produce the same output as above but has advantage of changing width dynamically. Here is an example called "printing staircase" where this trick will be useful.
Output is a beautiful staircase.
$ go run staircase.go 5 # ## ### #### #####
This article is an output of effort I went through while solving HackerRank. Send your comments to narenarya@live . If you really like this article share it and spread word.
Thank You :)