A solution to find the self-descriptive number in base 10.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
964 B

  1. package self_descriptive_number
  2. import (
  3. "strconv"
  4. "strings"
  5. "sync"
  6. )
  7. //Base10 finds all 10-digit self descriptive numbers.
  8. func Base10() ([]uint64, error) {
  9. var numbers []uint64
  10. var wg sync.WaitGroup
  11. wg.Add(9)
  12. //Create workers.
  13. for i := 1; i < 10; i++ {
  14. go func(mult int) {
  15. for j := uint64(1_000_000_000 * mult); j < uint64(1_000_000_000*(mult+1)); j++ {
  16. exists, number := Calculate(j)
  17. if exists {
  18. numbers = append(numbers, number)
  19. }
  20. }
  21. wg.Done()
  22. }(i)
  23. }
  24. //Wait for workers to finish.
  25. wg.Wait()
  26. return numbers, nil
  27. }
  28. //Calculate takes in an integer and checks
  29. //if it is a valid self descriptive number.
  30. func Calculate(num uint64) (bool, uint64) {
  31. number := strconv.FormatUint(num, 10)
  32. exploded := strings.Split(number, "")
  33. for i := 0; i < 10; i++ {
  34. digit, _ := strconv.Atoi(exploded[i])
  35. count := strings.Count(number, strconv.Itoa(i))
  36. if count != digit {
  37. return false, 0
  38. }
  39. }
  40. return true, num
  41. }