DEV Community

Simon Green
Simon Green

Posted on

The magical number game

Weekly Challenge 268

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: Magic Number

Task

You are given two arrays of integers of same size, @x and @y.

Write a script to find the magic number that when added to each elements of one of the array gives the second array. Elements order is not important.

My solution

For input via the command line, I take a list of integers and then split the list in two. Calling the Python function directly takes two list.

For this task I numerically sort the two lists x and y. I then calculate the different between the first values in each list, and store this as diff.

I then loop through each position in the list to ensure the difference between the integers in that position in each list is diff. If it isn't, I exit early.

def magic_number(x: list, y: list) -> int | None:
    x = sorted(x)
    y = sorted(y)

    diff = y[0] - x[0]

    for i in range(len(x)):
        if y[i] - x[i] != diff:
            return None

    return diff
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 3 7 5 9 5 7
2

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

$ ./ch-1.py 2 5
3
Enter fullscreen mode Exit fullscreen mode

Task 2: Number Game

Task

You are given an array of integers, @ints, with even number of elements.

Write a script to create a new array made up of elements of the given array. Pick the two smallest integers and add it to new array in decreasing order i.e. high to low. Keep doing until the given array is empty.

My solution

This is relatively straight forward, so doesn't need much explanation. For this task, I sort the list and then swap each pairs of numbers (1st and 2nd, 3rd and 4th, etc).

Both Python and Perl support the x, y = y, x syntax to swap numbers without using a temporary value.

def numbers_game(ints: list) -> list:
    ints = sorted(ints)

    for i in range(0, len(ints), 2):
        ints[i], ints[i+1], = ints[i+1], ints[i]

    return ints
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py 2 5 3 4
(3, 2, 5, 4)

$ ./ch-2.py 9 4 1 3 6 4 6 1
(1, 1, 4, 3, 6, 4, 9, 6)

$ ./ch-2.py 1 2 2 3
(2, 1, 3, 2)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)