Pesquisar este blog

Livros Recomendados

Mostrando postagens com marcador paula. Mostrar todas as postagens
Mostrando postagens com marcador paula. Mostrar todas as postagens

terça-feira, 11 de abril de 2023

URI (BEECROWD) - 1192 - Paula's Mathematic Game (O jogo Matemático de Paula) - Ad-Hoc - Haskell

Boa tarde!

Trago aqui uma solução "quentinha"! Esse foi um dos últimos exercícios que resolvi em Haskell. Eu espero que uma dessas soluções ajude muita gente a entender como resolver esse exercício!

Vamos ver como são essas respostas?

Plataforma: Beecrowd (antiga URI)

Problema1192

Enunciado:

In english:
Paula loves math. Her main hobby is to invent games or activities to play with her friends. Obviously, not all of them are so passionated about mathematics and have a lot of difficulty to solve the games offered by her. Now Paula has invented a small hobby that involves three characters: a numerical digit, one letter and one numeric digit.
If the letter is uppercase, you need to subtract the first digit of the second one. If the letter is lowercase, both digts must be added. If the DIGITS are the same, the product between these two digits must be presented. She asked his friend Marcelo, who is good at programming, to create a program that prints the solution for each sequence created by Paula.


Linguagem: Haskell

Solução:

Nesta solução, transformei os valores informados como String (lidos com getLine) em inteiros através de uma função digitToInt que implementei. Essa solução apenas converte cada dígito numérico em seu respectivo número. Havia n outras maneiras de resolver, mas eu fiz manualmente indicando os números um a um.

Se os valores forem iguais, basta multiplicar, se b for maiúsculo, basta subtrair, e caso contrário basta somar.

digitToInt :: Char -> Int
digitToInt '0' = 0
digitToInt '1' = 1
digitToInt '2' = 2
digitToInt '3' = 3
digitToInt '4' = 4
digitToInt '5' = 5
digitToInt '6' = 6
digitToInt '7' = 7
digitToInt '8' = 8
digitToInt '9' = 9

main :: IO ()
main = do
   n <- readLn :: IO Int
   reading n

reading :: Int -> IO ()
reading n = do
   if n == 0
      then return ()
      else do
         [a, b, c] <- getLine
         let x = digitToInt a
         let y = digitToInt c
         if x == y
            then putStrLn (show (y*x))
            else if b >= 'A' && b <= 'Z'
               then putStrLn (show (y-x))
               else putStrLn (show (y+x))
         reading (n-1)
Nesta outra solução eu utilizei a função digitToInt disponível em Data.Char. Dessa forma não preciso definir esta função. Ela funciona exatamente como precisamos, transformando o caractere em seu respectivo valor inteiro. Além disso, o teste que verifica se b é maiúsculo foi feito com a função isUpper, definida no meu código. Também existe uma função pronta, mas preferi implementar até para testar o uso de expressões lambda. \c é o parâmetro formal e c >= 'A' && c <= 'Z' é o corpo da função. Bacana, não é mesmo?

import Data.Char(digitToInt)

isUpper :: Char -> Bool
isUpper = \c -> c >= 'A' && c <= 'Z'

main :: IO ()
main = do
   n <- readLn :: IO Int
   reading n

reading :: Int -> IO ()
reading n = do
   if n == 0
      then return ()
      else do
         line <- getLine
         let [a, b, c] = line
         let x = digitToInt a
         let y = digitToInt c
         if x == y
            then putStrLn (show (y*x))
            else if isUpper b
               then putStrLn (show (y-x))
               else putStrLn (show (y+x))
         reading (n-1)

Esse exercício já foi resolvido aqui no blog, mas agora foi a primeira vez que resolvi ele usando uma linguagem declarativa :) Procure pelo marcador "1192" se deseja encontrar uma solução para este problema em outra linguagem!

PIX para doações: 6d8bc7a8-5d74-493a-ab7a-3515baf35956
Ajude-nos a manter o blog!

Postagem em destaque

URI (BEECROWD) - 2158 - Helping Uncle Cláudio (Ajudando o Tio Cláudio) - Matemática - C, C++ e Haskell

Buenas! Estou aqui mais uma vez para resolver um problema de Matemática! Agora tenho resolvido alguns dessa categoria, pra que vocês possam ...

Postagens mais visitadas