aboutsummaryrefslogtreecommitdiff
path: root/challenge-149/alexander-pankoff/perl/ch-2.pl
blob: d140f7e92acd35f1c02115b009cb02973390032d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw'say state signatures';
use bignum;
no warnings qw'experimental::signatures';

# TASK #2 › Largest Square
# Submitted by: Roger Bell_West
#
# Given a number base, derive the largest perfect square with no repeated digits and return it as a string. (For base>10, use ‘A’..‘Z’.)
# Example:
#
#     f(2)="1"
#     f(4)="3201"
#     f(10)="9814072356"
#     f(12)="B8750A649321"

use List::Util qw(uniq);

run() unless caller();

sub run() {

    my ($N) = @ARGV;

    if ( !$N || $N !~ m/^\d+$/ || $N < 2 || $N > 36 ) {
        die <<EOF;
  Usage:

    $0 N

  Options:

    N - a number base (between 2 and 36)
EOF
    }

    say "f($N) = " . largest_perfet_square_without_repeated_digits_in_base($N);

}

sub largest_perfet_square_without_repeated_digits_in_base($base) {
    my @digits = ( 0 .. 9, 'A' .. 'Z' )[ 0 .. $base - 1 ];

    for (
        my $i =
        int( sqrt( base_to_dec( $base, join( '', reverse @digits ) ) ) ) ;
        $i > 0 ;
        $i--
      )
    {
        my $perfect_square = dec_to_base( $base, $i**2 );

        my @digits = split( '', $perfect_square );

        return $perfect_square if scalar uniq(@digits) == scalar @digits;

    }
}

sub dec_to_base ( $base, $n ) {
    my @digits = ( 0 .. 9, 'A' .. 'Z' );

    return $digits[$n] if $n <= $base - 1;

    my $rem  = $n % $base;
    my $next = int( $n / $base );

    dec_to_base( $base, $next ) . $digits[$rem];
}

sub base_to_dec ( $base, $n ) {
    my $power = 1;
    my $num   = 0;

    my @digits = split( '', $n );

    for my $i ( reverse( 0 .. $#digits ) ) {

        $num += value( $digits[$i] ) * $power;
        $power = $power * $base;

    }

    return $num;

}

sub value($c) {

    if ( $c ge '0' && $c le '9' ) {
        return ord($c) - ord('0');

    }

    return ord($c) - ord('A') + 10;
}