Peter’s blog ✴ Week 103 ✴ 8 March 2021

THE WEEKLY CHALLENGE
Zodiac and music

The Perl Camel

Task 1

Chinese zodiac

You are given a year $year. Write a script to determine the Chinese Zodiac element and animal for the given year.

Please check out the Wikipedia page for more information.

Examples


Example 1
Input: 2017
Output: Fire Rooster

Example 2
Input: 1938
Output: Earth Tiger

Analysis

The animal repeats regularly every 12 years, and the element repeats every 10 years with each element serving for 2 years.

Given that, with the animals and elements in arrays it is a simple matter of modular arithmetic to retrieve the requested details.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 2000

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-03-08
use utf8;     # Week 103 - task 1 - Chinese zodiac
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

chinese_zodiac(2017);
chinese_zodiac(1938);
chinese_zodiac(1947);

my @t = localtime;
chinese_zodiac($t[5] + 1900); # this year

sub chinese_zodiac {
    
    my ($year, @animals, @elements);
    
    # initialise
    $year = $_[0];
    @animals = qw(Rat Ox Tiger Rabbit Dragon Snake Horse 
        Goat Monkey Rooster Dog Pig);
    @elements = qw(Wood Fire Earth Metal Water);

    # report
    say qq[\nInput:  $year];
    print qq[Output: Element is $elements[(($year - 1924) / 2) % 5], ];
    say qq[animal is $animals[($year - 1924) % 12]];
}

9 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


Input:  2017
Output: Element is Fire, animal is Rooster

Input:  1938
Output: Element is Earth, animal is Tiger

Input:  1947
Output: Element is Fire, animal is Pig

Input:  2026
Output: Element is Fire, animal is Horse

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain