Weekly Challenge 098
TASK #1 › Read N-characters
You are given file
readN($FILE, $number) returns the first n-characters and moves the pointer to the
I have to say I'm surprised that this is the first task given it is more complex (IMO) than the second task. Perl - like most modern languages - is UTF-8 aware. This makes it easier to read characters rather than bytes. But then maybe I'm over thinking this task and it is expected that only English is used.
This task is also complicated as the
readN function takes a file name, and not a file handle. To get around this, I use the state function to contain a mapping of file names to file handles, and open a new file handle if it doesn't already exist.
For the reading of the characters, the read function allows us to read the next
$n characters (not bytes) into a scalar, which I then print.
For these examples, input.txt contains
1324567890, and hello.txt contains
tēnā koe i tēnei ata.
» ./ch-1.pl input.txt 4 4 4 1234 5678 90 » ./ch-1.pl hello.txt 5 5 5 tēnā koe i tēne
TASK #2 › Search Insert Position
You are given a sorted array of distinct integers
@N and a target
Write a script to return the index of the given target if found otherwise place the target in the sorted array and return the index.
If this was something I was going to use at work, I'd use firstidx from the List::MoreUtils module. However, I have a policy of not using non-core modules when it comes to Team PWC challenges.
For this task I loop over the array in while / each loop. This gives me both of
$value while iterating over an array, and saves me having to manually doing this. Using each on arrays was introduced in Perl 5.12.
If a value is greater or equal to the target, I print the index of that value. If no value is found (i.e. the target is greater than the last value), I print the number of input values. This would be the index position of the next value.
» ./ch-2.pl "(1, 2, 3, 4)" 3 2 » ./ch-2.pl "(1, 3, 5, 7)" 6 3 » ./ch-2.pl "(12, 14, 16, 18)" 10 0 » ./ch-2.pl "(11, 13, 15, 17)" 19 4
Top comments (0)