DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge: Duplicate Lines

Weekly Challenge 333

Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.

Challenge, My solutions

Task 1: Straight Line

Task

You are given a list of co-ordinates.

Write a script to find out if the given points make a straight line.

My solution

This is the exact opposite of the Boomerang challenge in week #293. As such, I copied and pasted my solution from that challenge, replacing the true and false values with false and true.

You can read about how I solved the Boomerang task here. For input from the command line, I take the integers and convert them to a points list (array in Perl) before calling the function.

Examples

$ ./ch-1.py 2 1 2 3 2 5
True

$ ./ch-1.py 1 4 3 4 10 4
True

$ ./ch-1.py 0 0 1 1 2 3
False

$ ./ch-1.py 1 1 1 1 1 1
True

$ ./ch-1.py 1000000 1000000 2000000 2000000 3000000 3000000
True
Enter fullscreen mode Exit fullscreen mode

Task 2: Duplicate Zeros

Task

You are given an array of integers.

Write a script to duplicate each occurrence of zero, shifting the remaining elements to the right. The elements beyond the length of the original array are not written.

My solution

For this task, I start with an empty solution list (array in Perl). I then iterate through the list of ints. If the value is 0, I append 0 to the solutions list. I also append the original value.

Finally, I return the solution list truncated to the number of items in the original list.

def duplicate_zeros(ints: list) -> list:
    solution = []
    for i in ints:
        if i == 0:
            solution.append(0)
        solution.append(i)

    return solution[:len(ints)]
Enter fullscreen mode Exit fullscreen mode

The Perl code follows the same logic.

sub main (@ints) {
    my @solution = ();
    for my $i (@ints) {
        if ($i == 0) {
            push @solution, 0;
        }
        push @solution, $i;
    }
    say join(', ', @solution[ 0 .. $#ints ]);
}
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py 1 0 2 3 0 4 5 0
[1, 0, 0, 2, 3, 0, 0, 4]

$ ./ch-2.py 1 2 3
[1, 2, 3]

$ ./ch-2.py 1 2 3 0
[1, 2, 3, 0]

$ ./ch-2.py 0 0 1 2
[0, 0, 0, 0]

$ ./ch-2.py 1 2 0 3 4
[1, 2, 0, 0, 3]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)