Question 1

 avatar
unknown
haskell
6 months ago
2.3 kB
7
Indexable
import Data.List (nub)

number :: [Int] -> Int
number [] = 0
number (x:xs) = x * 10 ^ length xs + number xs 

--Answer for question 2.1 as well 
-- Get digits of a number
digits :: Int -> [Int]
digits = map (read . (:[])) . show


-- Check if the sum of the digits of a number is odd
oddSum :: Int -> Bool
oddSum n = odd $ sum $ digits n


generator1 :: [([Int], [Int], [Int])]
generator1 = [ (s1, s2, s3)
             | s1 <- combinations
             , s2 <- combinations
             , s3 <- combinations
             , validCombination s1 s2 s3
             ]

-- Generate all unique combinations of three distinct integers from 0 to 9
combinations :: [[Int]]
combinations = [[a, b, c] | a <- [0..9], b <- [0..9], c <- [0..9], a /= b, b /= c, a /= c]
-- Check if a combination of three lists has unique digits across all three lists
validCombination :: [Int] -> [Int] -> [Int] -> Bool
validCombination s1 s2 s3 = uniqueDigits (s1 ++ s2 ++ s3)

-- Check if a list has exactly 9 unique elements
uniqueDigits :: [Int] -> Bool
uniqueDigits xs = length xs == 9 && length (nub xs) == 9


isPrime :: Int -> Bool
isPrime n
	| n < 2 = False
	| otherwise = not ( factorisable n 2)
	where
	factorisable n f
		| n < f * f = False
		| otherwise = mod n f == 0
			|| factorisable n (f+1)


-- Check if a list represents a prime number
isPrimeList :: [Int] -> Bool
isPrimeList xs = isPrime (number xs)

-- Check if three numbers are equally spaced
isEquallySpaced :: Int -> Int -> Int -> Bool
isEquallySpaced a b c = (b - a) == (c - b)


-- Selector function
selector1 :: ([Int], [Int], [Int]) -> Bool
selector1 (s1, s2, s3) =
  all (oddSum . number) [s1, s2, s3] &&                      -- Each list has an odd digit sum
  all isPrimeList [s1, s2, s3] &&                 -- Each list represents a prime number
  isEquallySpaced (number s1) (number s2) (number s3) &&  -- Numbers are equally spaced
  length (nub (s1 ++ s2 ++ s3)) == 9              -- No repeated digits across all three lists

-- Assuming generator1 is already defined and generates candidate tuples
solutions :: [([Int], [Int], [Int])]
solutions = filter selector1 generator1


-- Main function to filter and print solutions
main :: IO ()
main = print $ solutions
  
Editor is loading...
Leave a Comment