DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 098

Weekly Challenge 098

Tasks

TASK #1 › Read N-characters

Task

You are given file $FILE.

Create subroutine readN($FILE, $number) returns the first n-characters and moves the pointer to the (n+1)th character

Solution

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.

Example

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
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Search Insert Position

Task

You are given a sorted array of distinct integers @N and a target $N.

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.

My solution

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 $index and $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.

Examples

» ./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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)