Last active
August 29, 2015 14:01
-
-
Save Denommus/0e80d0ea488898c38442 to your computer and use it in GitHub Desktop.
Check if a number is happy or not
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| digs :: Int -> [Int] | |
| digs = map (read . return) . show | |
| process :: Int -> Int | |
| process = sum . map (^2) . digs | |
| isHappy :: Int -> Bool | |
| isHappy x = isHappyHelper x [] | |
| where isHappyHelper 1 _ = True | |
| isHappyHelper bag list | |
| | bag `elem` list = False | |
| | otherwise = isHappyHelper (process bag) (bag : list) | |
| main :: IO () | |
| main = readLn >>= print . isHappy |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (defun char-to-int (char) | |
| (parse-integer (make-string 1 :initial-element char))) | |
| (defun digits (number) | |
| (map 'list #'char-to-int (write-to-string number))) | |
| (defun process (number) | |
| (reduce #'+ (mapcar (lambda (x) (expt x 2)) (digits number)))) | |
| (defun happyp (number) | |
| (labels ((happy-helper (x list) | |
| (cond | |
| ((= x 1) t) | |
| ((member x list) nil) | |
| (t (happy-helper (process x) (cons x list)))))) | |
| (happy-helper number '()))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fn digits(number: uint) -> Vec<uint> { | |
| number.to_string() | |
| .as_slice() | |
| .chars() | |
| .map(|x| x.to_digit(10).unwrap()) | |
| .collect() | |
| } | |
| fn process(number: uint) -> uint { | |
| digits(number).iter().map(|&x| x*x).fold(0, |x, y| x+y) | |
| } | |
| pub fn is_happy(number: uint) -> bool { | |
| let mut list: Vec<uint> = Vec::new(); | |
| let mut bag = number; | |
| loop { | |
| if bag==1 { | |
| return true | |
| } else if list.contains(&bag) { | |
| return false | |
| } else { | |
| list.push(bag); | |
| bag = process(bag); | |
| } | |
| } | |
| } | |
| #[test] | |
| fn numbers_1_and_7_are_happy() { | |
| assert!(is_happy(1)); | |
| assert!(is_happy(7)); | |
| } | |
| #[test] | |
| fn numbers_2_and_3_arent_happy() { | |
| assert!(!is_happy(2)); | |
| assert!(!is_happy(3)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment