Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "sort"
- )
- type RuneSlice []rune
- func (p RuneSlice) Len() int { return len(p) }
- func (p RuneSlice) Less(i, j int) bool { return p[i] < p[j] }
- func (p RuneSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
- func isPermutation(str1, str2 string) bool {
- // if lengths are not equal - false
- if len(str1) == len(str2) {
- return false
- }
- // sort both strings/runes
- var rune1 RuneSlice = []rune(str1)
- var rune2 RuneSlice = []rune(str2)
- sort.Sort(rune1)
- sort.Sort(rune2)
- //fmt.Println(string(rune1[:]))
- //fmt.Println(string(rune2[:]))
- // compare rune1 and rune 2 by indexes
- for i := 0; i < len(rune1); i++ {
- if rune1[i] != rune2[i] {
- return false
- }
- }
- return true
- }
- func main() {
- fmt.Println("18,19,20,21 and 21,20,18,20,19,18,20 is permutation of each other : ", isPermutation("18,19,20,21", "21,20,18,20,19,18,20"))
- fmt.Println("18,19,20,21 and 21,20,18,20,18,20 is permutation of each other : ", isPermutation("18,19,20,21", "21,20,18,20,18,20"))
- }
- // A pumpung is a permutation of consecutive integers, possibly with repeated items.
- // For example, [21, 20, 18, 20, 19, 18, 20] is pumpung
- // since it is a permutation of [18, …, 21] with 18 and 20 repeated.
- // However, [21, 20, 18, 20, 18, 20] is not.
- package main
- import "fmt"
- const (
- maxInt = int(^uint(0) >> 1)
- minInt = -maxInt - 1
- )
- func isPumpung(a []int) (min, max int, pumpung bool) {
- min, max = maxInt, minInt
- p := make(map[int]bool)
- for _, e := range a {
- p[e] = true
- if min > e {
- min = e
- }
- if max < e {
- max = e
- }
- }
- pumpung = max-min+1 == len(p)
- if !pumpung {
- min, max = 0, 0
- }
- return min, max, pumpung
- }
- func isPumpungEqual(a1, a2 []int) bool {
- min1, max1, pumpung1 := isPumpung(a1)
- if !pumpung1 {
- return false
- }
- min2, max2, pumpung2 := isPumpung(a2)
- if !pumpung2 {
- return false
- }
- return min1 == min2 && max1 == max2
- }
- func main() {
- a1 := []int{18, 19, 20, 21}
- fmt.Print(a1, " ")
- fmt.Println(isPumpung(a1))
- a2 := []int{21, 20, 18, 20, 18, 20}
- fmt.Print(a2, " ")
- fmt.Println(isPumpung(a2))
- a3 := []int{21, 20, 18, 20, 19, 18, 20}
- fmt.Print(a3, " ")
- fmt.Println(isPumpung(a3))
- fmt.Println()
- fmt.Println(a1, a2, isPumpungEqual(a1, a2))
- fmt.Println(a1, a3, isPumpungEqual(a1, a3))
- }
- [18 19 20 21] 18 21 true
- [21 20 18 20 18 20] 0 0 false
- [21 20 18 20 19 18 20] 18 21 true
- [18 19 20 21] [21 20 18 20 18 20] false
- [18 19 20 21] [21 20 18 20 19 18 20] true
Add Comment
Please, Sign In to add comment