ScottMcMaster

Untitled

Apr 28th, 2018
84
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "bufio"
  5.     "fmt"
  6.     "math"
  7.     "os"
  8.     "strconv"
  9.     "strings"
  10. )
  11.  
  12. func main() {
  13.     reader := bufio.NewReader(os.Stdin)
  14.  
  15.     for {
  16.         fmt.Println("Enter a positive number >= 1, or negative number to quit: ")
  17.         text, _ := reader.ReadString('\n')
  18.  
  19.         i, err := strconv.Atoi(strings.TrimSpace(text))
  20.         if err != nil {
  21.             fmt.Println("Please enter a number")
  22.             continue
  23.         }
  24.  
  25.         if i <= 1 {
  26.             fmt.Println("Bye")
  27.             break
  28.         }
  29.  
  30.         typ, sequence := happyOrSad(i)
  31.         fmt.Printf("%d is %s and the sequence is %v\n", i, typ, sequence)
  32.     }
  33. }
  34.  
  35. func happyOrSad(num int) (string, []int) {
  36.     seen := make(map[int]bool)
  37.     seq := []int{num}
  38.     for num != 1 && !seen[num] {
  39.         seen[num] = true
  40.         cur := num
  41.         num = 0
  42.         for cur > 0 {
  43.             num += int(math.Pow(float64(cur%10), float64(2)))
  44.             cur /= 10
  45.         }
  46.         seq = append(seq, num)
  47.     }
  48.     var typ string
  49.     if num == 1 {
  50.         typ = "happy"
  51.     } else {
  52.         typ = "sad"
  53.     }
  54.     return typ, seq
  55. }
RAW Paste Data