The Weekly Challenge 048

Survivor and Palindrome Dates

Solutions on GitHub

Task 1: Survivor

There are 50 people standing in a circle in position 1 to 50. The person standing at position 1 has a sword. He kills the next person (position 2) and passes the sword to the next (position 3). Find out the last survivor.

Example Output

Survivor: 37

Logic

This is the classic Josephus Problem. We can simulate the process using a queue/array, looping and deleting every alternate person until only one survivor remains.

Perl Solution

ch-1.pl

sub get_last_man_standing { my $count = shift; my %people = map { $_ => 1 } (1 .. $count); my $last = 0; my $switch = 0; while (%people) { for my $key ( sort { $a <=> $b } keys %people ) { delete $people{$key} if $switch; $last = $key; $switch = $switch == 0 ? 1 : 0; } } return $last; }

Python Solution

ch-1.py

from collections import deque def get_last_man_standing(count): people = deque(range(count)) killed = 0 switch = 0 while killed < count-1: if switch == 0: switch = 1 people.rotate(-1) else: switch = 0 people.popleft() killed += 1 return people.popleft()+1

Task 2: Palindrome Dates

Write a script to print all Palindrome Dates between 2000 and 2999 in the format mmddyyyy.

Example Output

10-02-2001 01-02-2010 11-02-2011 02-02-2020 12-02-2021 03-02-2030 ...

Logic

Iterate through every day between 2000-01-01 and 2999-12-31, format the date as mmddyyyy, and check if it is equal to its reversed representation.

Perl Solution

ch-2.pl

use DateTime; sub is_palindrome { my $dt = shift; return $dt->mdy('') eq reverse $dt->mdy(''); } my $dt = DateTime->new( year => 2000, month => 1, day => 1 ); my $dt_end = DateTime->new( year => 2999, month => 12, day => 31 ); my $epoch_test = $dt->epoch; my $epoch_end = $dt_end->epoch; while ($epoch_test < $epoch_end) { my $dt_curr = DateTime->from_epoch( epoch => $epoch_test); say $dt_curr->mdy if is_palindrome($dt_curr); $epoch_test += 60 * 60 * 24; }

Python Solution

ch-2.py

from datetime import date, timedelta dt = date(2000, 1, 1) while dt.year < 3000: dt += timedelta(days=1) if dt.strftime("%m%d%Y") == dt.strftime("%m%d%Y")[::-1]: print(dt)