arrays - Concise and robust way to read a line of space-separated integers in Go -


i have been giving hackerrank try problems require reading lines of integers arrays (slices).

for many of problems, parsing code ends being larger algorithmic meat of solution. instance, case in sherlock , array

any ideas on how concisely parse space-separated line of integers slice? fmt.scanf doesn't support slices , when using bufio long solutions.

some requirements:

  • you can use standard library.
  • the solution should concise, shorter better.
  • error checks shouldn't skipped. know input defined in hackerrank , should able cut corners, please don't, it's bad practice.
  • it should reasonably efficient.

note: parser should consume single line , not full input.

you can use fmt.scanf, need keep track of values you're getting.

// a.go package main  import (     "fmt"     "io" )  func main() {     var (         next int         nums []int     )      {         n, err := fmt.scanf("%d", &next)         if err == io.eof {             break         }         if err != nil {             panic(err)         }         if n == 0 {             break         }          nums = append(nums, next)     }      fmt.printf("%#v\n", nums) } 

$ echo "4 8 15 16 23 42" | go run a.go []int{4, 8, 15, 16, 23, 42} 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -