DEV Community

Simon Green
Simon Green

Posted on

Jumping Groups

Weekly Challenge 212

Challenge, My solutions

Task 1: Jumping Letters

Task

You are given a word having alphabetic characters only, and a list of positive integers of the same length

Write a script to print the new word generated after jumping forward each letter in the given word by the integer in the list. The given list would have exactly the number as the total alphabets in the given word.

My solution

This seems relatively straight forward. I have a list called lower_alphabet that contains the twenty six letters of the English alphabet, and upper_alphabet for the capital letters.

I then loop through each letter in the original word, choose the right alphabet to use, take the position of that letter (a = 0, z = 25), and the appropriate number from the input, and take the modulus of 26 from it to chose the new letter. For each step, I add to the new_word array.

Examples

$ ./ch-1.py Perl 2 22 19 9
Raku

$ ./ch-1.py Raku 24 4 7 17
Perl
Enter fullscreen mode Exit fullscreen mode

Task 2: Rearrange Groups

Task

You are given a list of integers and group size greater than zero.

Write a script to split the list into equal groups of the given size where integers are in sequential order. If it can’t be done then print -1.

My solution

Mea culpa from me. I misunderstood the task, and asked Mohammad for help for something that I really should have figured out myself. Sorry about that.

My solution needs a little of explanation. So here goes. Firstly I take the last number from the array and call it n. This is number of elements I need in each set. I then sort the remainder of the array list (array in Perl) numerically. While there are items in the list I do the following:

  1. Set the expected variable. This is from the first (lowest) value in the array, incrementing by 1 continuing for n times.
  2. Set the not_matched set (hash in Perl) with the values from the expected array.
  3. Loop through the values in array. The first occurrence of an expected integer will remove the value from the not_matched set. Anything else will add to a new list called new_array
  4. If there are any values in the not_matched set means that I haven't found a solution, so I print -1 and exit.
  5. Otherwise I add a nicely formatted output of the expected list, set array to be the values of new_array, and continue on.

If I have exhausted the array list, then I know we have a solution, and print it to the user.

Examples

$ ./ch-2.py 1 2 3 5 1 2 7 6 3 3
(1,2,3), (1,2,3), (5,6,7)

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

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

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

Top comments (0)