How to resolve the algorithm Numbers with equal rises and falls step by step in the Haskell programming language
Published on 7 June 2024 03:52 AM
How to resolve the algorithm Numbers with equal rises and falls step by step in the Haskell programming language
Table of Contents
Problem Statement
When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Given the decimal digits of the number are written as a series d:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Numbers with equal rises and falls step by step in the Haskell programming language
This Haskell code defines a function riseEqFall
that checks if the sum of the digits that increase is equal to the sum of the digits that decrease in a given number.
-
pairs
function: It takes a list and returns a list of pairs of consecutive elements. -
riseEqFall
function:- It takes an integer
n
and converts it to a string usingshow n
. - It then maps each character in the string to an integer using
map digitToInt
. - It computes the pairs of digits using
pairs
. - It defines
rel
as a function that takes a comparator (e.g.,>
or<
) and applies it to each pair of digits. - It calculates the sum of the results of applying
rel
to each pair usingsum
. - Finally, it checks if the sum of increasing digits is equal to the sum of decreasing digits.
- It takes an integer
-
a296712
list:- It is a list comprehension that generates a list of all integers
n
from 1 to infinity that satisfy theriseEqFall
condition.
- It is a list comprehension that generates a list of all integers
-
main
function:- It prints the first 200 numbers in the
a296712
list. - It prints the 10,000,000th number in the
a296712
list.
- It prints the first 200 numbers in the
Source code in the haskell programming language
import Data.Char
pairs :: [a] -> [(a,a)]
pairs (a:b:as) = (a,b):pairs (b:as)
pairs _ = []
riseEqFall :: Int -> Bool
riseEqFall n = rel (>) digitPairs == rel (<) digitPairs
where rel r = sum . map (fromEnum . uncurry r)
digitPairs = pairs $ map digitToInt $ show n
a296712 :: [Int]
a296712 = [n | n <- [1..], riseEqFall n]
main :: IO ()
main = do
putStrLn "The first 200 numbers are: "
putStrLn $ unwords $ map show $ take 200 a296712
putStrLn ""
putStr "The 10,000,000th number is: "
putStrLn $ show $ a296712 !! 9999999
You may also check:How to resolve the algorithm Verify distribution uniformity/Naive step by step in the R programming language
You may also check:How to resolve the algorithm Flatten a list step by step in the Crystal programming language
You may also check:How to resolve the algorithm Loops/Foreach step by step in the Halon programming language
You may also check:How to resolve the algorithm Search a list step by step in the Acornsoft Lisp programming language
You may also check:How to resolve the algorithm Cheryl's birthday step by step in the Visual Basic .NET programming language