This way I get further use of golang and look more at the concurrency that it offers. I decided to try using go routines to implement string permutations in the phone number.
I ran into problems using sync.WaitGroup to coordinate the go programs that I used. specific error:
WaitGroup is reused before previous Wait has returned
the code:
main.go
package main
import (
"fmt"
"sync"
"github.com/sbiscigl/phonenumberperm/intstack"
"github.com/sbiscigl/phonenumberperm/permutations"
)
var wg sync.WaitGroup
func main() {
num := []int{2, 7, 1, 4, 5, 5, 2}
stack := intstack.New(num)
permutationChannel := make(chan string)
wg.Add(1)
go permutations.ThreadSafeCalcWords(stack, "", permutationChannel, &wg)
wg.Wait()
}
Permutations / perm.go
package permutations
import (
"fmt"
"sync"
"github.com/sbiscigl/phonenumberperm/intstack"
)
var letterMap = map[int][]string{
2: []string{"a", "b", "c"},
3: []string{"d", "e", "f"},
4: []string{"g", "h", "i"},
5: []string{"j", "k", "l"},
6: []string{"m", "n", "o"},
7: []string{"p", "q", "r", "s"},
8: []string{"t", "u", "v"},
9: []string{"w", "x", "y", "z"},
}
func ThreadSafeCalcWords(s intstack.IntStack, word string, ch chan<- string,
wg *sync.WaitGroup) {
if s.IsEmpty() {
ch <- fmt.Sprint(word)
wg.Done()
} else {
if s.Peek() == 1 || s.Peek() == 0 {
wg.Done()
s.Pop()
wg.Add(1)
go ThreadSafeCalcWords(s, word, ch, wg)
} else {
wg.Done()
for _, letter := range letterMap[s.Pop()] {
wg.Add(1)
go ThreadSafeCalcWords(s, word+letter, ch, wg)
}
}
}
}
intstack / intstack.go
package intstack
import "fmt"
const (
maxSize = 100
)
type IntStack struct {
valueList []int
maxSize int
}
func New(nums []int) IntStack {
return IntStack{
valueList: nums,
maxSize: maxSize,
}
}
func (s *IntStack) Pop() int {
var val int
if !s.IsEmpty() {
val = s.valueList[0]
s.valueList = s.valueList[1:]
} else {
fmt.Println("stack is empty")
}
return val
}
func (s IntStack) Peek() int {
return s.valueList[0]
}
func (s IntStack) IsEmpty() bool {
if len(s.valueList) > 0 {
return false
}
return true
}
func (s IntStack) Print() {
for _, element := range s.valueList {
fmt.Print(element)
}
fmt.Print("\n")
}
, wg.Wait() rathe wait wait. , . , Wait() , go, , . , ,
repo refrence : https://github.com/sbiscigl/phonenumberperm