Skip to content

Commit

Permalink
c1-m3-slice sorting with user input data
Browse files Browse the repository at this point in the history
  • Loading branch information
hoangbits committed May 21, 2020
1 parent bef0426 commit 8706857
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions c1-m3-activity/slice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"fmt"
"sort"
"unicode"
)

func main() {
sli := make([]int, 0, 3)
for {
var inputValue rune
fmt.Println("Please enter an integer: ")
// duplicated line: https://stackoverflow.com/questions/57734634/why-i-get-a-duplicate-output-when-the-loop-if-there-is-a-scanf
num, err := fmt.Scanf("%c\n", &inputValue)
if err != nil {
fmt.Print(err.Error() + "\n")
continue
}

if unicode.IsNumber(inputValue) {
// get integer out of ASCII: https://stackoverflow.com/questions/21322173/convert-rune-to-int
number := int(inputValue - '0')
sli = append(sli, number)
sort.SliceStable(sli, func(i, j int) bool { return sli[i] < sli[j] })

fmt.Printf("Scanned: %d len=%d cap=%d %v \n\n", num, len(sli), cap(sli), sli)

} else if unicode.IsLetter(inputValue) && inputValue == rune('w') {
fmt.Print("bye!\n")
break
}

}
}

0 comments on commit 8706857

Please sign in to comment.