diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2023-04-24 00:16:18 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-04-24 00:16:18 +0100 |
| commit | 1955af44895eb922089844c4a84fd5bfe6fbb2f9 (patch) | |
| tree | b37e5dbd9ef2d84b1b47190f5e73447be043b319 | |
| parent | 8818e971e6c254b4b334f3d0632caf2a77e06533 (diff) | |
| parent | d0d82f02e6ea0f3b50dd1dbcdebc3fba4dcaf713 (diff) | |
| download | perlweeklychallenge-club-1955af44895eb922089844c4a84fd5bfe6fbb2f9.tar.gz perlweeklychallenge-club-1955af44895eb922089844c4a84fd5bfe6fbb2f9.tar.bz2 perlweeklychallenge-club-1955af44895eb922089844c4a84fd5bfe6fbb2f9.zip | |
Merge pull request #7959 from dcw803/master
imported my challenge 213 solutions (ch-1 and ch-2 in Perl, ch-1 in C)
| -rw-r--r-- | challenge-213/duncan-c-white/C/Makefile | 16 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/C/README | 11 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/C/args.c | 234 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/C/args.h | 12 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/C/ch-1.c | 79 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/C/parseints.c | 114 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/C/parseints.h | 1 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/C/printarray.c | 39 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/C/printarray.h | 1 | ||||
| -rw-r--r-- | challenge-213/duncan-c-white/README | 88 | ||||
| -rwxr-xr-x | challenge-213/duncan-c-white/perl/ch-1.pl | 51 | ||||
| -rwxr-xr-x | challenge-213/duncan-c-white/perl/ch-2.pl | 160 |
12 files changed, 763 insertions, 43 deletions
diff --git a/challenge-213/duncan-c-white/C/Makefile b/challenge-213/duncan-c-white/C/Makefile new file mode 100644 index 0000000000..d193658c72 --- /dev/null +++ b/challenge-213/duncan-c-white/C/Makefile @@ -0,0 +1,16 @@ +# Makefile rules generated by CB +CC = gcc +CFLAGS = -Wall -g +BUILD = ch-1 + +all: $(BUILD) + +clean: + /bin/rm -f $(BUILD) *.o core a.out + +args.o: args.c +ch-1: ch-1.o args.o parseints.o printarray.o +ch-1.o: ch-1.c args.h parseints.h printarray.h +parseints.o: parseints.c args.h parseints.h printarray.h +printarray.o: printarray.c + diff --git a/challenge-213/duncan-c-white/C/README b/challenge-213/duncan-c-white/C/README new file mode 100644 index 0000000000..fd95045bfe --- /dev/null +++ b/challenge-213/duncan-c-white/C/README @@ -0,0 +1,11 @@ +Thought I'd also have a go at translating ch-1.pl into C.. + +I'll translate ch-2.pl into C shortly. + +ch-1 produc ver similar (non-debugging and debugging) +output to the Perl original. + +These C versions use some of my regular support modules: +- my command-line argument processing module args.[ch], +- my csvlist-of-int parsing module parseints.[ch], and +- my int-array printing module printarray.[ch]. diff --git a/challenge-213/duncan-c-white/C/args.c b/challenge-213/duncan-c-white/C/args.c new file mode 100644 index 0000000000..20c21e6c30 --- /dev/null +++ b/challenge-213/duncan-c-white/C/args.c @@ -0,0 +1,234 @@ +#include <stdio.h> +#include <stdlib.h> +#include <stdbool.h> +#include <string.h> +#include <ctype.h> +#include <assert.h> + + +bool debug = false; + + +// process_flag_noarg( name, argc, argv ); +// Process the -d flag, and check that there are no +// remaining arguments. +void process_flag_noarg( char *name, int argc, char **argv ) +{ + int arg=1; + if( argc>1 && strcmp( argv[arg], "-d" ) == 0 ) + { + debug = true; + arg++; + } + + int left = argc-arg; + if( left != 0 ) + { + fprintf( stderr, "Usage: %s [-d]\n", name ); + exit(1); + } +} + + +// int argno = process_flag_n_args( name, argc, argv, n, argmsg ); +// Process the -d flag, and check that there are exactly +// n remaining arguments, return the index position of the first +// argument. If not, generate a fatal Usage error using the argmsg. +// +int process_flag_n_args( char *name, int argc, char **argv, int n, char *argmsg ) +{ + int arg=1; + if( argc>1 && strcmp( argv[arg], "-d" ) == 0 ) + { + debug = true; + arg++; + } + + int left = argc-arg; + if( left != n ) + { + fprintf( stderr, "Usage: %s [-d] %s\n Exactly %d " + "arguments needed\n", name, argmsg, n ); + exit(1); + } + return arg; +} + + +// int argno = process_flag_n_m_args( name, argc, argv, min, max, argmsg ); +// Process the -d flag, and check that there are between +// min and max remaining arguments, return the index position of the first +// argument. If not, generate a fatal Usage error using the argmsg. +// +int process_flag_n_m_args( char *name, int argc, char **argv, int min, int max, char *argmsg ) +{ + int arg=1; + if( argc>1 && strcmp( argv[arg], "-d" ) == 0 ) + { + debug = true; + arg++; + } + + int left = argc-arg; + if( left < min || left > max ) + { + fprintf( stderr, "Usage: %s [-d] %s\n Between %d and %d " + "arguments needed\n", name, argmsg, min, max ); + exit(1); + } + return arg; +} + + +// process_onenumarg_default( name, argc, argv, defvalue, &n ); +// Process the -d flag, and check that there is a single +// remaining numeric argument (or no arguments, in which case +// we use the defvalue), putting it into n +void process_onenumarg_default( char *name, int argc, char **argv, int defvalue, int *n ) +{ + char argmsg[100]; + sprintf( argmsg, "[int default %d]", defvalue ); + int arg = process_flag_n_m_args( name, argc, argv, 0, 1, argmsg ); + + *n = arg == argc ? defvalue : atoi( argv[arg] ); +} + + +// process_onenumarg( name, argc, argv, &n ); +// Process the -d flag, and check that there is a single +// remaining numeric argument, putting it into n +void process_onenumarg( char *name, int argc, char **argv, int *n ) +{ + int arg = process_flag_n_args( name, argc, argv, 1, "int" ); + + // argument is in argv[arg] + *n = atoi( argv[arg] ); +} + + +// process_twonumargs( name, argc, argv, &m, &n ); +// Process the -d flag, and check that there are 2 +// remaining numeric arguments, putting them into m and n +void process_twonumargs( char *name, int argc, char **argv, int *m, int *n ) +{ + int arg = process_flag_n_args( name, argc, argv, 2, "int" ); + + // arguments are in argv[arg] and argv[arg+1] + *m = atoi( argv[arg++] ); + *n = atoi( argv[arg] ); +} + + +// process_twostrargs() IS DEPRECATED: use process_flag_n_m_args() instead + + +// int arr[100]; +// int nel = process_listnumargs( name, argc, argv, arr, 100 ); +// Process the -d flag, and check that there are >= 2 +// remaining numeric arguments, putting them into arr[0..nel-1] +// and returning nel. +int process_listnumargs( char *name, int argc, char **argv, int *arr, int maxel ) +{ + int arg=1; + if( argc>1 && strcmp( argv[arg], "-d" ) == 0 ) + { + debug = true; + arg++; + } + + int left = argc-arg; + if( left < 2 ) + { + fprintf( stderr, "Usage: %s [-d] list_of_numeric_args\n", name ); + exit(1); + } + if( left > maxel ) + { + fprintf( stderr, "%s: more than %d args\n", name, maxel ); + exit(1); + } + + // elements are in argv[arg], argv[arg+1]... + + if( debug ) + { + printf( "debug: remaining arguments are in arg=%d, " + "firstn=%s, secondn=%s..\n", + arg, argv[arg], argv[arg+1] ); + } + + int nel = 0; + for( int i=arg; i<argc; i++ ) + { + arr[nel++] = atoi( argv[i] ); + } + arr[nel] = -1; + return nel; +} + + +// +// bool isint = check_unsigned_int( char *val, int *n ); +// Given an string val, check that there's an unsigned integer +// in it (after optional whitespace). If there is a valid +// unsigned integer value, store that integer value in *n and +// return true; otherwise return false (and don't alter *n). +bool check_unsigned_int( char *val, int *n ) +{ + // skip whitespace in val + char *p; + for( p=val; isspace(*p); p++ ) + { + /*EMPTY*/ + } + if( ! isdigit(*p) ) return false; + *n = atoi(p); + return true; +} + + +// +// bool isint = check_int( char *val, int *n ); +// Given an string val, check that there's an integer +// in it (after optional whitespace). If there is a valid +// integer value, store that integer value in *n and +// return true; otherwise return false (and don't alter *n). +bool check_int( char *val, int *n ) +{ + // skip whitespace in val + char *p; + for( p=val; isspace(*p); p++ ) + { + /*EMPTY*/ + } + int sign = 1; + if( *p == '+' ) p++; + else if( *p == '-' ) + { + sign = -1; + p++; + } + if( ! isdigit(*p) ) return false; + *n = atoi(p) * sign; + return true; +} + + +// +// bool ok = check_unsigned_real( char *val, double *n ); +// Given an string val, check that there's an unsigned real +// in it (after optional whitespace). If there is a valid +// unsigned real value, store that value in *n and +// return true; otherwise return false (and don't alter *n). +bool check_unsigned_real( char *val, double *n ) +{ + // skip whitespace in val + char *p; + for( p=val; isspace(*p); p++ ) + { + /*EMPTY*/ + } + if( ! isdigit(*p) ) return false; + *n = atof(p); + return true; +} diff --git a/challenge-213/duncan-c-white/C/args.h b/challenge-213/duncan-c-white/C/args.h new file mode 100644 index 0000000000..df765fa21e --- /dev/null +++ b/challenge-213/duncan-c-white/C/args.h @@ -0,0 +1,12 @@ +extern bool debug; + +extern void process_flag_noarg( char * name, int argc, char ** argv ); +extern int process_flag_n_args( char * name, int argc, char ** argv, int n, char * argmsg ); +extern int process_flag_n_m_args( char * name, int argc, char ** argv, int min, int max, char * argmsg ); +extern void process_onenumarg_default( char * name, int argc, char ** argv, int defvalue, int * n ); +extern void process_onenumarg( char * name, int argc, char ** argv, int * n ); +extern void process_twonumargs( char * name, int argc, char ** argv, int * m, int * n ); +extern int process_listnumargs( char * name, int argc, char ** argv, int * arr, int maxel ); +extern bool check_unsigned_int( char * val, int * n ); +extern bool check_int( char * val, int * n ); +extern bool check_unsigned_real( char * val, double * n ); diff --git a/challenge-213/duncan-c-white/C/ch-1.c b/challenge-213/duncan-c-white/C/ch-1.c new file mode 100644 index 0000000000..d6aee8264f --- /dev/null +++ b/challenge-213/duncan-c-white/C/ch-1.c @@ -0,0 +1,79 @@ +// Task 1: Fun Sort +// +// C translation + +#include <stdio.h> +#include <stdlib.h> +#include <stdbool.h> +#include <string.h> +#include <ctype.h> +#include <assert.h> + +#include "args.h" +#include "parseints.h" +#include "printarray.h" + + +static int intcmp( const void *a, const void *b ) +{ + int *ap = (int *)a; + int *bp = (int *)b; + return *ap - *bp; +} + + +int main( int argc, char **argv ) +{ + int argno = process_flag_n_m_args( "fun-sort", argc, argv, + 1, 1000, "intlist" ); + int nel; + int *list = parse_int_args( argc, argv, argno, &nel ); + + if( debug ) + { + printf( "debug: list: " ); + print_int_array( 60, nel, list, ',', stdout ); + putchar( '\n' ); + } + + int *even = malloc( nel * sizeof(int) ); + assert( even != NULL ); + + int *odd = malloc( nel * sizeof(int) ); + assert( odd != NULL ); + + int neven = 0; + int nodd = 0; + + for( int i=0; i<nel; i++ ) + { + if( list[i] % 2 == 0 ) + { + even[neven++] = list[i]; + } else + { + odd[nodd++] = list[i]; + } + } + + qsort( even, neven, sizeof(int), &intcmp ); + qsort( odd, nodd, sizeof(int), &intcmp ); + + for( int i=0; i<neven; i++ ) + { + list[i] = even[i]; + } + + for( int i=0; i<nodd; i++ ) + { + list[neven+i] = odd[i]; + } + + print_int_array( 60, nel, list, ',', stdout ); + putchar( '\n' ); + + free( even ); + free( odd ); + free( list ); + return 0; +} diff --git a/challenge-213/duncan-c-white/C/parseints.c b/challenge-213/duncan-c-white/C/parseints.c new file mode 100644 index 0000000000..3e820eb334 --- /dev/null +++ b/challenge-213/duncan-c-white/C/parseints.c @@ -0,0 +1,114 @@ +// Simple routine to parse one or more arguments, +// looking for individual ints or comma-separated +// lists of ints. +// + +#include <stdio.h> +#include <stdlib.h> +#include <stdbool.h> +#include <string.h> +#include <ctype.h> +#include <assert.h> + +#include "args.h" +#include "printarray.h" +#include "parseints.h" + +typedef struct +{ + int nel; // current number of elements + int maxel; // maximum number of elements allocated + int *list; // malloc()d list of integers +} intlist; + + +// +// intlist il.. then initialize il.. then: +// add_one( element, &il ); +// +static void add_one( int x, intlist *p ) +{ + if( p->nel > p->maxel ) + { + p->maxel += 128; + p->list = realloc( p->list, p->maxel ); + assert( p->list != NULL ); + } + #if 0 + if( debug ) + { + printf( "PIA: appending %d to result at " + "pos %d\n", x, p->nel ); + } + #endif + p->list[p->nel++] = x; +} + + +// +// intlist il.. then initialize il.. then: +// add_one_arg( argstr, &il ); +// +static void add_one_arg( char *argstr, intlist *p ) +{ + int x; + if( !check_int(argstr,&x) ) + { + fprintf( stderr, "PIA: arg %s must be int\n", argstr ); + exit(1); + } + add_one( x, p ); +} + + +// +// int nel; +// int *ilist = parse_int_args( argc, argv, argno, &nel ); +// process all arguments argv[argno..argc-1], extracting either +// single ints or comma-separated lists of ints from those arguments, +// accumulate all integers in a dynarray list, storing the total number +// of elements in nel. This list must be freed by the caller. +// Note that the list of elements used to be terminated by a -1 value, +// but I've commented this out from now on. +// +int *parse_int_args( int argc, char **argv, int argno, int *nel ) +{ + int *result = malloc( 128 * sizeof(int) ); + assert( result != NULL ); + intlist il = { 0, 128, result }; + + #if 0 + if( debug ) + { + printf( "PIA: parsing ints from args %d..%d\n", argno, argc-1 ); + } + #endif + for( int i=argno; i<argc; i++ ) + { + assert( strlen(argv[i]) < 1024 ); + char copy[1024]; + strcpy( copy, argv[i] ); + char *com; + char *s; + for( s=copy; (com = strchr(s,',')) != NULL; s=com+1 ) + { + *com = '\0'; + add_one_arg( s, &il ); + } + add_one_arg( s, &il ); + } + + //add_one( -1, &il ); + + #if 0 + if( debug ) + { + printf( "PIA: final list is " ); + print_int_array( 80, il.nel, il.list, ',', stdout ); + putchar( '\n' ); + } + #endif + + *nel = il.nel; + return il.list; +} diff --git a/challenge-213/duncan-c-white/C/parseints.h b/challenge-213/duncan-c-white/C/parseints.h new file mode 100644 index 0000000000..da5e145a86 --- /dev/null +++ b/challenge-213/duncan-c-white/C/parseints.h @@ -0,0 +1 @@ +extern int * parse_int_args( int argc, char ** argv, int argno, int * nel ); diff --git a/challenge-213/duncan-c-white/C/printarray.c b/challenge-213/duncan-c-white/C/printarray.c new file mode 100644 index 0000000000..ddee597df3 --- /dev/null +++ b/challenge-213/duncan-c-white/C/printarray.c @@ -0,0 +1,39 @@ +#include <stdio.h> +#include <string.h> + + +// print_int_array( maxw, nelements, results[], sep, outfile ); +// format results[0..nelements-1] as a <sep> separated +// list onto outfile with lines <= maxw chars long. +// produces a whole number of lines of output - without the trailing '\n' +void print_int_array( int maxw, int nel, int *results, char sep, FILE *out ) +{ + int linelen = 0; + for( int i=0; i<nel; i++ ) + { + char buf[100]; + sprintf( buf, "%d", results[i] ); + int len = strlen(buf); + if( linelen + len + 2 > maxw ) + { + fputc( '\n', out ); + linelen = 0; + } else if( i>0 ) + { + fputc( ' ', out ); + linelen++; + } + + linelen += len; + fprintf( out, "%s", buf ); + if( i<nel-1 ) + { + fputc( sep, out ); + linelen++; + } + } + //if( linelen>0 ) + //{ + // fputc( '\n', out ); + //} +} diff --git a/challenge-213/duncan-c-white/C/printarray.h b/challenge-213/duncan-c-white/C/printarray.h new file mode 100644 index 0000000000..40efb83277 --- /dev/null +++ b/challenge-213/duncan-c-white/C/printarray.h @@ -0,0 +1 @@ +extern void print_int_array( int maxw, int nel, int * results, char sep, FILE * out ); diff --git a/challenge-213/duncan-c-white/README b/challenge-213/duncan-c-white/README index 89f2c82665..bf3941e44d 100644 --- a/challenge-213/duncan-c-white/README +++ b/challenge-213/duncan-c-white/README @@ -1,69 +1,71 @@ -Task 1: Jumping Letters +Task 1: Fun Sort -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. +You are given a list of positive integers. Write a script to sort the +all even integers first then all odds in ascending order. Example 1 - Input: $word = 'Perl' and @jump = (2,22,19,9) - Output: Raku - - 'P' jumps 2 place forward and becomes 'R'. - 'e' jumps 22 place forward and becomes 'a'. (jump is cyclic i.e. after 'z' you go back to 'a') - 'r' jumps 19 place forward and becomes 'k'. - 'l' jumps 9 place forward and becomes 'u'. + Input: @list = (1,2,3,4,5,6) + Output: (2,4,6,1,3,5) Example 2 - Input: $word = 'Raku' and @jump = (24,4,7,17) - Output: 'Perl' + Input: @list = (1,2) + Output: (2,1) -MY NOTES: sounds very easy. Essentially ROT(n) for a different value of n for -each letter. +Example 3 -GUEST LANGUAGE: As a bonus, I will have a go at translating ch-1.pl into C -but I'll do that tomorrow. + Input: @list = (1) + Output: (1) +MY NOTES: sounds very easy. Select evens; sort them; select odds; sort them, +then append sorted lists together. -Task 2: Rearrange Groups +GUEST LANGUAGE: As a bonus, I've had a go at translating ch-2.pl into C, +look in the C/ directory for that. -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. +Task 2: Shortest Route + +You are given a list of bidirectional routes defining a network of nodes, +as well as source and destination node numbers. Write a script to find +the route from source to destination that passes through fewest nodes. Example 1: - Input: @list = (1,2,3,5,1,2,7,6,3) and $size = 3 - Output: (1,2,3), (1,2,3), (5,6,7) + Input: @routes = ([1,2,6], [5,6,7]) + $source = 1 + $destination = 7 + + Output: (1,2,6,7) + + Source (1) is part of route [1,2,6] so the journey looks like 1 -> 2 -> 6 + then jump to route [5,6,7] and takes the route 6 -> 7. + So the final route is (1,2,6,7) Example 2: - Input: @list = (1,2,3) and $size = 2 + Input: @routes = ([1,2,3], [4,5,6]) + $source = 2 + $destination = 5 + Output: -1 Example 3: - Input: @list = (1,2,4,3,5,3) and $size = 3 - Output: (1,2,3), (3,4,5) - -Example 4: + Input: @routes = ([1,2,3], [4,5,6], [3,8,9], [7,8]) + $source = 1 + $destination = 7 + Output: (1,2,3,8,7) -Input: @list = (1,5,2,6,4,7) and $size = 3 -Output: -1 + Source (1) is part of route [1,2,3] so the journey looks like 1 -> 2 -> 3 + then jump to route [3,8,9] and takes the route 3 -> 8 + then jump to route [7,8] and takes the route 8 -> 7 + So the final route is (1,2,3,8,7) -MY NOTES: sounds reasonably easy as a brute force search. But hang on, do we -need backtracking or not? i.e. if you find a run-of-$size-consecutive-numbers -is that run necessarily a part of the solution, allowing you to extract any -run you find whether needing to backtrack? no, not if that run is PART of a -longer run of consecutive numbers. What if we only find run-of-$size- -consecutive-numbers isolated at the start, ie. where first(run)-1 is not -present in the input? Then we should be able to: repeatedly pick any one run, -add it to solution, remove it from input, repeat until input is empty. +MY NOTES: hmmm.. weird "list of routes" data format. Easier if we can +convert the data into "normal" node -> list possible next nodes form. +Shortest route means: find all routes and min() them? -GUEST LANGUAGE: As a bonus, I will have a go at translating ch-2.pl into C -but I'll do that tomorrow. +GUEST LANGUAGE: I will translate ch-2.pl into C tomorrow. Run out of time +to do it today. diff --git a/challenge-213/duncan-c-white/perl/ch-1.pl b/challenge-213/duncan-c-white/perl/ch-1.pl new file mode 100755 index 0000000000..ef3b5563b9 --- /dev/null +++ b/challenge-213/duncan-c-white/perl/ch-1.pl @@ -0,0 +1,51 @@ +#!/usr/bin/perl +# +# Task 1: Fun Sort +# +# You are given a list of positive integers. Write a script to sort the +# all even integers first then all odds in ascending order. +# +# Example 1 +# +# Input: @list = (1,2,3,4,5,6) +# Output: (2,4,6,1,3,5) +# +# Example 2 +# +# Input: @list = (1,2) +# Output: (2,1) +# +# Example 3 +# +# Input: @list = (1) +# Output: (1) +# +# MY NOTES: sounds very easy. Select evens; sort them; select odds; sort them, +# then append sorted lists together. +# +# GUEST LANGUAGE: As a bonus, I've had a go at translating ch-2.pl into C, +# look in the C/ directory for that. +# + +use strict; +use warnings; +use feature 'say'; +use Getopt::Long; +use Data::Dumper; +use List::Util qw(any); + +my $debug=0; +die "Usage: fun-sort [--debug] intlist\n" + unless GetOptions( "debug"=>\$debug ) && @ARGV>0; + +my @list = split( /,/, join(',',@ARGV) ); + +say "debug: list: ", join(',',@list) if $debug; + +my @even = grep { $_ % 2 == 0 } @list; +my @odd = grep { $_ % 2 == 1 } @list; + +@list = sort(@even); +push @list, sort(@odd); + +say join(',',@list); diff --git a/challenge-213/duncan-c-white/perl/ch-2.pl b/challenge-213/duncan-c-white/perl/ch-2.pl new file mode 100755 index 0000000000..358f3f058a --- /dev/null +++ b/challenge-213/duncan-c-white/perl/ch-2.pl @@ -0,0 +1,160 @@ +#!/usr/bin/perl +# +# Task 2: Shortest Route +# +# You are given a list of bidirectional routes defining a network of nodes, +# as well as source and destination node numbers. Write a script to find +# the route from source to destination that passes through fewest nodes. +# +# Example 1: +# +# Input: @routes = ([1,2,6], [5,6,7]) +# $source = 1 +# $destination = 7 +# +# Output: (1,2,6,7) +# +# Source (1) is part of route [1,2,6] so the journey looks like 1 -> 2 -> 6 +# then jump to route [5,6,7] and takes the route 6 -> 7. +# So the final route is (1,2,6,7) +# +# Example 2: +# +# Input: @routes = ([1,2,3], [4,5,6]) +# $source = 2 +# $destination = 5 +# +# Output: -1 +# +# Example 3: +# +# Input: @routes = ([1,2,3], [4,5,6], [3,8,9], [7,8]) +# $source = 1 +# $destination = 7 +# Output: (1,2,3,8,7) +# +# Source (1) is part of route [1,2,3] so the journey looks like 1 -> 2 -> 3 +# then jump to route [3,8,9] and takes the route 3 -> 8 +# then jump to route [7,8] and takes the route 8 -> 7 +# So the final route is (1,2,3,8,7) +# +# MY NOTES: hmmm.. weird "list of routes" data format. Easier if we can +# convert the data into "normal" node -> list possible next nodes form. +# Shortest route means: find all routes and min() them? +# +# GUEST LANGUAGE: I will translate ch-2.pl into C tomorrow. Run out of +# time to do it today. +# + +use strict; +use warnings; +use feature 'say'; +use Getopt::Long; +use Data::Dumper; +use Function::Parameters; + +my $debug=0; +die "Usage: shortest-route [--debug] start end intlist [intlist..]\n" + unless GetOptions( "debug"=>\$debug ) && @ARGV > 3; + + +my @sr; # curr shortest route +my $srlen; # current length of shortest route + + +# +# my @shortest = shortest_route( $start, $end, \%link ); +# Find the shortest route from $start to $end using links %link, +# +fun shortest_route( $start, $end, $link ) +{ + @sr = (); + $srlen = keys(%$link) + 1; + all_routes( $start, $end, $link, [] ); + return @sr; +} + +# +# all_routes( $start, $end, $link, $done ); +# Find all routes from $start to $end using links %$link, +# where we have already visted @$done, and set @sr/$srlen +# to the shortest route found. +# +fun all_routes( $start, $end, $link, $done ) +{ + if( $start == $end ) + { + # found route @$done . $end + my @r = @$done; + push @r, $end; + say "debug: done:", join(',',@$done), " found new route ", + join(',',@r) if $debug; + if( @r < $srlen ) + { + $srlen = @r; + @sr = @r; + say "debug: done:", join(',',@$done), + " found new shortest route ", join(',',@r) + if $debug; + } + } + my %vis = map { $_ => 1 } @$done; # already visited + my @next = grep { ! $vis{$_} } @{$link->{$start}}; + say "debug: done:", join(',',@$done), " start=$start, end=$end, ", + "next=", join(',',@next) if $debug; + + my @newdone = @$done; + push @newdone, $start; + foreach my $node (@next) + { + all_routes( $node, $end, $link, \@newdone ); + } +} + + +my $start = shift; +my $end = shift; +my @route = map { [ split(/,/,$_) ] } @ARGV; + +if( $debug ) +{ + say "debug: start=$start, end=$end, routes: "; + foreach my $r (@route) + { + say "route: ", join(',',@$r); + } +} + + +my %link; # node -> list(next node) +foreach my $route (@route) +{ + my @p = @$route; + my $prev = shift @p; + foreach my $node (@p) + { + $link{$prev} //= []; + push @{$link{$prev}}, $node; + $link{$node} //= []; + push @{$link{$node}}, $prev; + $prev = $node; + } +} + +if( $debug ) +{ + foreach my $n (sort keys %link) + { + say "$n: ", join(',',@{$link{$n}}); + } +} + +my @shortest = shortest_route( $start, $end, \%link ); + +if( @shortest ) +{ + say join(',',@shortest); +} else +{ + say -1; +} |
