Discussion
· Oct 20, 2023

Code Golf: Chinese zodiac cycle

Let's do a round of code golf! Last one was very popular!

The Chinese zodiac is a repeating cycle of 12 years, with each year being represented by an animal and an element that changes every 2 years.
The animals are: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog and Pig.
The elements are: Wood, Fire, Earth, Metal and Water.
Your task is to write a function that receives a year, and returns the element and the animal that year represent.
Let's use the year 1924 as start point, in the Chinese zodiac the element was Wood and the animal was Rat.

Input

2023

Output

"Water Rabbit"

Note

Rules

  1. The signature of the contest entry MUST be:
    Class codeGolf.ChineseZodiac
    {
    
        ClassMethod Calendar(y As %Integer) As %String
        {
            q " "// Your solution here
        }
    
    }
    
  2. It is forbidden to modify class/signature, including but not limited to:
    • Adding inheritance
    • Setting default argument values
    • Adding class elements (Parameters, Methods, Includes, etc).
  3. It is forbidden to refer to non-system code from your entry. For example, this is not a valid entry:
    ClassMethod Build(f As %Integer)
    {
      W ##class(myPackage.myClass).test(a)
    }
    
  4. The use of $ZWPACK and $ZWBPACK is also discouraged.
  5. You can use this test case:
    Class codeGolf.unittests.ChineseZodiac Extends %UnitTest.TestCase
    {
    
        Method TestSolutions()
        {
            Do $$$AssertEquals(##class(codeGolf.ChineseZodiac).Calendar(1972), "Water Rat")
            Do $$$AssertEquals(##class(codeGolf.ChineseZodiac).Calendar(1934), "Wood Dog")
            Do $$$AssertEquals(##class(codeGolf.ChineseZodiac).Calendar(2023), "Water Rabbit")
            Do $$$AssertEquals(##class(codeGolf.ChineseZodiac).Calendar(2043), "Water Pig")
            Do $$$AssertEquals(##class(codeGolf.ChineseZodiac).Calendar(1961), "Metal Ox")
            Do $$$AssertEquals(##class(codeGolf.ChineseZodiac).Calendar(2002), "Water Horse")
            Do $$$AssertEquals(##class(codeGolf.ChineseZodiac).Calendar(2016), "Fire Monkey")
        }
    
    }
 
Not a valid solution
Discussion (7)2
Log in or sign up to continue
Class codeGolf.ChineseZodiac
{
    ClassMethod Calendar(y As %Integer) As %String
    {
        Set startYear = 1924
        Set animals = "Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig"
        Set elements = "Wood,Fire,Earth,Metal,Water"
        Set diff = y - startYear
        
        If diff < 0 Quit "Invalid Year"
        Set animalIndex = (diff + 12) % 12
        Set elementIndex = (diff / 2) % 5
        Set animal = $List(animals, animalIndex + 1)
        Set element = $List(elements, elementIndex + 1)
        
        Quit element_" "_animal    
    }
}