RabbitFarm
2024-12-01
Contiguous and Semi-Ordered
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1: Contiguous Array
You are given an array of binary numbers, @binary.
Write a script to return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Let’s not concern ourselves with any particular efficiencies and just analyze all the subsets of the given numbers!
The main loop for iterating over all the contiguous sub-arrays.
We really just need one subroutine to co-ordinate the inputs and run the main loop that’s required.
Putting it all together...
The rest of the code just runs some simple tests.
-
MAIN:{
say contiguous_array 1, 0;
say contiguous_array 0, 1, 0;
say contiguous_array 0, 0, 0, 0, 0;
say contiguous_array 0, 1, 0, 0, 1, 0;
}
◇
-
Fragment referenced in 3.
Sample Run
$ perl perl/ch-1.pl 2 2 0 4
Part 2: Semi-Ordered Permutation
You are given permutation of $n integers, @ints. Write a script to find the minimum number of swaps needed to make the @ints a semi-ordered permutation.
A permutation is called semi-ordered if the first number is 1 and the last number equals n. That means we need to count the number of swaps needed to move 1 to the beginning and $n to the end.
At first thought, I wonder if there’s a catch? Does the swapping end up moving 1 or $n further from its destination? That doesn’t seem to be the case even if they were adjacent to each other. That is because they are moving in opposite directions. 1 is always moving left and $n is always moving right. Although they may swap with each other it will always be of benefit to them both.
Let’s start with the code for swapping left and and right to move 1 and $n in their respective directions.
We’ll put everything together in a subroutine.
The rest of the code drives some tests.
-
MAIN:{
say semi_ordered 2, 1, 4, 3;
say semi_ordered 2, 4, 1, 3;
say semi_ordered 1, 3, 2, 4, 5;
}
◇
-
Fragment referenced in 9.
Sample Run
$ perl perl/ch-2.pl 2 3 0
References
posted at: 23:34 by: Adam Russell | path: /perl | permanent link to this entry