restructure: arrays and slices
This commit is contained in:
38
16-slices/exercises/06-compare-the-slices/main.go
Normal file
38
16-slices/exercises/06-compare-the-slices/main.go
Normal file
@ -0,0 +1,38 @@
|
||||
// For more tutorials: https://blog.learngoprogramming.com
|
||||
//
|
||||
// Copyright © 2018 Inanc Gumus
|
||||
// Learn Go Programming Course
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
//
|
||||
|
||||
package main
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// EXERCISE: Compare the slices
|
||||
//
|
||||
// 1. Split the namesA string and get a slice
|
||||
//
|
||||
// 2. Sort all the slices
|
||||
//
|
||||
// 3. Compare whether the slices are equal or not
|
||||
//
|
||||
//
|
||||
// EXPECTED OUTPUT
|
||||
//
|
||||
// They are equal.
|
||||
//
|
||||
//
|
||||
// HINTS
|
||||
//
|
||||
// 1. strings.Split function splits a string and
|
||||
// returns a string slice
|
||||
//
|
||||
// 2. Comparing slices: First check whether their length
|
||||
// are the same or not; only then compare them.
|
||||
//
|
||||
// ---------------------------------------------------------
|
||||
|
||||
func main() {
|
||||
// namesA := "Da Vinci, Wozniak, Carmack"
|
||||
// namesB := []string{"Wozniak", "Da Vinci", "Carmack"}
|
||||
}
|
33
16-slices/exercises/06-compare-the-slices/solution/main.go
Normal file
33
16-slices/exercises/06-compare-the-slices/solution/main.go
Normal file
@ -0,0 +1,33 @@
|
||||
// For more tutorials: https://blog.learngoprogramming.com
|
||||
//
|
||||
// Copyright © 2018 Inanc Gumus
|
||||
// Learn Go Programming Course
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
//
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
namesA := "Da Vinci, Wozniak, Carmack"
|
||||
namesB := []string{"Wozniak", "Da Vinci", "Carmack"}
|
||||
|
||||
namesC := strings.Split(namesA, ", ")
|
||||
|
||||
sort.Strings(namesC)
|
||||
sort.Strings(namesB)
|
||||
|
||||
if len(namesC) == len(namesB) {
|
||||
for i := range namesC {
|
||||
if namesC[i] != namesB[i] {
|
||||
return
|
||||
}
|
||||
}
|
||||
fmt.Println("They are equal.")
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user