aboutsummaryrefslogtreecommitdiff
path: root/challenge-082/lars-thegler/perl/ch-2.pl
blob: cd0fef4c456939a85681991946827b13215c7fc8 (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
#! /usr/bin/env perl

use Modern::Perl;
use Data::Printer;

# TASK #2 › Interleave String
# Submitted by: Mohammad S Anwar
# You are given 3 strings; $A, $B and $C.

# Write a script to check if $C is created by interleave $A and $B.

# Print 1 if check is success otherwise 0.

# Example 1:
# Input:
#     $A = "XY"
#     $B = "X"
#     $C = "XXY"

# Output: 1
# EXPLANATION
# "X" (from $B) + "XY" (from $A) = $C
# Example 2:
# Input:
#     $A = "XXY"
#     $B = "XXZ"
#     $C = "XXXXZY"

# Output: 1
# EXPLANATION
# "XX" (from $A) + "XXZ" (from $B) + "Y" (from $A) = $C
# Example 3:
# Input:
#     $A = "YX"
#     $B = "X"
#     $C = "XXY"

# Output: 0

my ($A, $B, $C) = @ARGV;


my %interleaves;
$interleaves{$_}++ for interleave($A, $B), interleave($B, $A);

say exists $interleaves{$C} ? 1 : 0;

sub interleave {
    my ($a, $b) = @_;
    my @interleaves;
    for my $i (0..length $a) {
       my $s = $a;
       $s =~ s/^(.{$i})(.*)/$1$b$2/;
       push @interleaves, $s;
    }
    return @interleaves;
}