Before I started on this tonight, I ran across a video of Antônio Carlos Jobim’s One Note Samba being performed by Dean Martin & Caterina Valente, and I knew I needed to make it the musical theme tonight, but I’m going to link you to John Pizzarelli’s version.
This week’s theme is feuding in my head. On the musical side, “Number Game” made me think of Joni Mitchell, but the repeated use of the word “number” in the task titles made me think of Marketplace Radio (yes, I’m a Public Radio geek).
Element order may not be important in specifying the problem, but it feels pretty important in solving the problem. Since we’re looking for a number that, when added to each element of the first array yields an element of the second array, the obvious solution is to sort each array in either ascending or descending order, and then subtract the element in the first array from its corresponding element in the second array. As long as we get the same number each time, we’ve found the magic number. None of the examples show two input arrays that don’t yield a magic number, but nothing in the problem description precludes that.
Raku
sub magicNumber(@x, @y) {my@xS = @x.sort;my@yS = @y.sort;my$magic = @yS.shift - @xS.shift;while (@xS) {if (@yS.shift - @xS.shift != $magic) {return; # no magic number } }return$magic;}
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.
Example 1
Input: @ints = (2, 5, 3, 4)Output: (3, 2, 5, 4)Round 1: we picked (2, 3) and push it to the new array (3, 2)Round 2: we picked the remaining (4, 5) and push it to the new array (5, 4)
This feels very much like the previous task: we need to sort the elements so we can pick the two smallest integers, we pull those values off the sorted array (only one array this time, however), and we do some kind of comparison. The big difference this time is we’re adding the elements back to a list.
Raku
The big thing to note here is that Raku’s Arraypush doesn’t flatten it’s argument list, so “If you pass an array or list as the thing to push, it becomes one additional element; multiple values are added to the array only if you supply them as separate arguments or in a slip.”
defnumberGame(ints): intSorted =sorted(ints) new = []while intSorted: x = intSorted.pop(0) y = intSorted.pop(0)if x > y: new.extend([x, y])else: new.extend([y, x])return new