Skip to content
Snippets Groups Projects
Commit b5a17dec authored by AB8057's avatar AB8057
Browse files

Upload ready assignment 3

parent 02d10ae8
No related branches found
No related tags found
No related merge requests found
#Part 1
#Implement a Elixir script that:
#Ask a number from the user.
#If given number is evenly divisible by 3, print Divisible by 3.
#If given number is evenly divisible by 5, print Divisible by 5.
#If given number is evenly divisible by 7, print Divisible by 7.
#If given number is not evenly divisible by 3, 5 or 7, find smallest value (excluding 1) that number is evenly divisible for and print that value to the output.
user_input = IO.gets("Give a number: ")
trimmed_input = String.trim(user_input) #user input trimmed version without blank spaces etc.
number = String.to_integer(trimmed_input) #number is the trimmed user input string changed into integer
case {rem(number, 3), rem(number, 5), rem(number, 7)} do # I use case - do to handle the conditions comparing against given patterns
{0, _, _} -> IO.puts("Divisible by 3")
{_, 0, _} -> IO.puts("Divisible by 5")
{_, _, 0} -> IO.puts("Divisible by 7")
_ ->
smallest_divisor = Enum.find(2..number-1, &rem(number, &1) == 0) || number #if cases above do not match, the smallest value (excluding 1) that number is evenly divisible for is searched with enum
IO.puts("Smallest divisor for #{number} is: #{smallest_divisor}") #smallest divisor value is printed
end
#Part 2
#Write an anonymous function that takes two parameters:
#Use a guard to check if both parameters are a string type. If so, return a combined string of the parameters.
#If parameters are not strings, return the addition result of the parameters.
#Test your anonymous function with string and number parameters and print the results.
string_or_number = fn #anonymous function that has guards
a, b when is_binary(a) and is_binary(b) -> a <> b #if both are string type, strings are combined
a, b -> a + b #if they are not strings, they are added
_ -> IO.puts "The given values are neither both strings or both integers."
end
#tests:
IO.puts(string_or_number.("kissa", "koira"))
IO.puts(string_or_number.(34, 2))
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment