rajeev@udhar.com
BAN USER#!/usr/bin/perl
# Print usage and exit if two numbers are not passed.
die "Usage: $0 number1 number2\n" if @ARGV != 2;
my $num1 = $ARGV[0];
my $num2 = $ARGV[1];
# We are going to compare the digits of each number, so split them.
my(@arr_num2) = split //, $num2;
my(@asc_arr_num1) = sort split //, $num1;
my(@desc_arr_num1) = sort {$b <=> $a} split //, $num1;
#print "@desc_arr_num1\n@asc_arr_num1\n";
#
# Of all the numbers, that can be formed from the digits of the first number, which are higher than
# second number, we will out of the lowest of them all.
#
# We'll make two arrays from the digits of first numner.
# We'll compare the digits from the array of digits from first numner in descending order with
# the digits of second number. When the digit from first number exceeds the corresponding digit
# from second number, we'll find the lowest combination of the remaining digits of first number
# and append them. For that we'll use the second array that we created from digits of first number
# in ascending order.
#
# If the resulting number at the end of the loop is lower/equal than the second number, that means
# no number can be formed from digits of first number which is bigger than second number.
#
for (my $i=0; $i<@desc_arr_num1; $i++)
{
$result .= sprintf "%d", $desc_arr_num1[$i];
if ($desc_arr_num1[$i] > $arr_num2[$i] )
{
for (my $k=0; $k<@asc_arr_num1-$i-1; $k++)
{
$result .= sprintf "%d", $asc_arr_num1[$k];
}
last;
}
}
if ($result > $num2)
{
print "$result\n";
}
else
{
print "Sorry, but no number can be formed from digits of $num1 which is bigger than $num2.\n";
}
$ careercup_5165229530939392.pl 5281 7443
8125
$ careercup_5165229530939392.pl 7442 7443
Sorry, but no number can be formed from digits of 7442 which is bigger than 7443.
$ careercup_5165229530939392.pl 123 7443
Sorry, but no number can be formed from digits of 123 which is bigger than 7443.
$ cat output_file | grep -v '/$'
- rajeev@udhar.com August 22, 2015
# I started writing a Perl script and in the middle of it, realized it's fairly easy to do it in bash.
# Not fancy but gets the job done. If I'm in hurry and not looking for votes :-), I would do the
# bash version any day. Yes, it can be improved and no it's not flawless. Here is the quick
# version. BTW this method can be used for numbers and strings both.
$ careercup_5158359730749440.sh
- rajeev@udhar.com August 22, 2015Intersection of (0 1 1 2 2 5) and (0 1 2 2 2 6) is: (0 1 2 2)
Intersection of (0 1 1) and (0 1 2 3 4 5 6) is: (0 1)