Skip to content

Instantly share code, notes, and snippets.

@Denommus
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save Denommus/0e80d0ea488898c38442 to your computer and use it in GitHub Desktop.

Select an option

Save Denommus/0e80d0ea488898c38442 to your computer and use it in GitHub Desktop.
Check if a number is happy or not
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
(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 '())))
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