diff options
| author | dcw <d.white@imperial.ac.uk> | 2023-04-04 10:15:35 +0100 |
|---|---|---|
| committer | dcw <d.white@imperial.ac.uk> | 2023-04-04 10:15:35 +0100 |
| commit | e7695a05273901cd48ec10406960cd11b923356b (patch) | |
| tree | 37714a98c58debfe292162242b1f93e5efcf7779 | |
| parent | ed17a0bef83e3276a3949814dab37a8a51871041 (diff) | |
| download | perlweeklychallenge-club-e7695a05273901cd48ec10406960cd11b923356b.tar.gz perlweeklychallenge-club-e7695a05273901cd48ec10406960cd11b923356b.tar.bz2 perlweeklychallenge-club-e7695a05273901cd48ec10406960cd11b923356b.zip | |
imported (belatedly) my solutions to challenge 210, in Perl and C as usual..
| -rw-r--r-- | challenge-210/duncan-c-white/C/.cbuild | 1 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/Makefile | 18 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/README | 9 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/args.c | 234 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/args.h | 12 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/ch-1.c | 158 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/ch-2.c | 148 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/parseints.c | 114 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/parseints.h | 1 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/printarray.c | 39 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/C/printarray.h | 1 | ||||
| -rw-r--r-- | challenge-210/duncan-c-white/README | 111 | ||||
| -rwxr-xr-x | challenge-210/duncan-c-white/perl/ch-1.pl | 93 | ||||
| -rwxr-xr-x | challenge-210/duncan-c-white/perl/ch-2.pl | 121 |
14 files changed, 1013 insertions, 47 deletions
diff --git a/challenge-210/duncan-c-white/C/.cbuild b/challenge-210/duncan-c-white/C/.cbuild index 835981f6f1..a14ec76520 100644 --- a/challenge-210/duncan-c-white/C/.cbuild +++ b/challenge-210/duncan-c-white/C/.cbuild @@ -1,5 +1,4 @@ BUILD = ch-1 ch-2 -BUILD = ch-1 CFLAGS = -Wall -g #LDFLAGS = -lm #CFLAGS = -g diff --git a/challenge-210/duncan-c-white/C/Makefile b/challenge-210/duncan-c-white/C/Makefile new file mode 100644 index 0000000000..1b34ccd3b2 --- /dev/null +++ b/challenge-210/duncan-c-white/C/Makefile @@ -0,0 +1,18 @@ +# Makefile rules generated by CB +CC = gcc +CFLAGS = -Wall -g +BUILD = ch-1 ch-2 + +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 +ch-2: ch-2.o args.o parseints.o printarray.o +ch-2.o: ch-2.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-210/duncan-c-white/C/README b/challenge-210/duncan-c-white/C/README new file mode 100644 index 0000000000..bb9a44abc0 --- /dev/null +++ b/challenge-210/duncan-c-white/C/README @@ -0,0 +1,9 @@ +Thought I'd also have a go at translating ch-1.pl and ch-2.pl into C.. + +Both C versions produce near identical (non-debugging and debugging) +output to the Perl originals. + +These C versions use some of my regular support modules: +- a tweaked version of my command-line argument processing module args.[ch], +- a tweaked version of csvlist-of-int parsing module parseints.[ch], and +- an int-array printing module printarray.[ch]. diff --git a/challenge-210/duncan-c-white/C/args.c b/challenge-210/duncan-c-white/C/args.c new file mode 100644 index 0000000000..20c21e6c30 --- /dev/null +++ b/challenge-210/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-210/duncan-c-white/C/args.h b/challenge-210/duncan-c-white/C/args.h new file mode 100644 index 0000000000..df765fa21e --- /dev/null +++ b/challenge-210/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-210/duncan-c-white/C/ch-1.c b/challenge-210/duncan-c-white/C/ch-1.c new file mode 100644 index 0000000000..9c0054d5a1 --- /dev/null +++ b/challenge-210/duncan-c-white/C/ch-1.c @@ -0,0 +1,158 @@ + +#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" + + +#define MAX(a,b) ((a)>(b)?(a):(b)) + +int max = 0; + +int intcompare( const void *a, const void *b ) +{ + return *((int *)a) - *((int *)b); +} + + +// +// int pos = posinlist( v, nel, list ); +// Return the position of v if it's in list[nel], -1 otherwise +// +int posinlist( int v, int nel, int *list ) +{ + for( int i=0; i<nel; i++ ) + { + if( list[i] == v ) return i; + } + return -1; +} + + +// +// findall( sumsofar, nel, list ); +// Given a sumsofar, and a list[nel], find all "kill-and-win" +// paths through the list, updating max with the maximum +// of all total sums of each complete path. +// +void findall( int sumsofar, int nel, int *list ) +{ + if( nel == 0 ) + { + max = MAX( max, sumsofar ); + return; + } + + // find all distinct values in list + int *distinct = malloc( nel * sizeof(int) ); + assert( distinct != NULL ); + int ndistinct = 0; + for( int i=0; i<nel; i++ ) + { + if( posinlist( list[i], ndistinct, distinct ) == -1 ) + { + distinct[ndistinct++] = list[i]; + } + } + // sort them + qsort( distinct, ndistinct, sizeof(int), &intcompare ); + + if( debug ) + { + printf( "debug: distinct values: " ); + print_int_array( 60, ndistinct, distinct, ',', stdout ); + putchar( '\n' ); + } + + for( int i=0; i<ndistinct; i++ ) + { + // ok, pick distinct[i] as our value to kill-and-win + int v = distinct[i]; + + // kaw rule: remove all v-1 and v+1 values and ONE v value + + // give ourselves two new arrays: + + // the one containing the elements we delete + int *deleted = malloc( nel * sizeof(int) ); + assert( deleted != NULL ); + int ndeleted = 0; + int delsum = 0; + + // and the one containing the elements we keep + int *newl = malloc( nel * sizeof(int) ); + assert( newl != NULL ); + int newn = 0; + + int nvseen = 0; // how many "v"s have we seen + for( int j=0; j<nel; j++ ) + { + int el = list[j]; + bool include = true; + if( el == v-1 || el == v+1 ) + { + include = false; + } else if( el == v ) + { + if( nvseen++ == 0 ) + { + include = false; // delete 1st v + } + } + if( include ) + { + newl[newn++] = el; + } else + { + deleted[ndeleted++] = el; + delsum += el; + } + } + + int newsum = sumsofar + delsum; + if( debug ) + { + printf( "debug: kaw: list=" ); + print_int_array( 60, nel, list, ',', stdout ); + printf( ", v=%d, deleted=", v ); + print_int_array( 60, ndeleted, deleted, ',', stdout ); + printf( ", newl=" ); + print_int_array( 60, newn, newl, ',', stdout ); + printf( ", newsum=%d\n", newsum ); + } + findall( newsum, newn, newl ); + + free( deleted ); + free( newl ); + } +} + + +int main( int argc, char **argv ) +{ + int argno = process_flag_n_m_args( "kill-and-win", argc, argv, + 1, 1000, "intlist" ); + int nel; + int *list = parse_int_args( argc, argv, argno, &nel ); + + if( debug ) + { + printf( "debug: initial list: " ); + print_int_array( 60, nel, list, ',', stdout ); + putchar( '\n' ); + } + + max = 0; + findall( 0, nel, list ); + printf( "%d\n", max ); + + free( list ); + + return 0; +} diff --git a/challenge-210/duncan-c-white/C/ch-2.c b/challenge-210/duncan-c-white/C/ch-2.c new file mode 100644 index 0000000000..d2ec3e5799 --- /dev/null +++ b/challenge-210/duncan-c-white/C/ch-2.c @@ -0,0 +1,148 @@ +// +// Task 2: Number Collision +// +// C version. +// + +#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" + + +// +// int pos = find_pos_neg( nel, list ); +// Search in the given list[nel] for a positive number +// immediately followed by a negative number. +// If you find such a pair return the position of +// the positive number. +// If there is no such pair, return -1. +// +int find_pos_neg( int nel, int *list ) +{ + for( int i=0; i<nel-1; i++ ) + { + if( list[i]>=0 && list[i+1]<0 ) + { + return i; + } + } + return -1; +} + + +// +// int newnel = remove_elements( nel, list, delpos, ndel ); +// Delete ndel elements starting at delpos from list[nel], +// returning the new number of elements (should be nel-ndel) +// +int remove_elements( int nel, int *list, int delpos, int ndel ) +{ + if( debug ) + { + // give ourselves a new array containing the deleted elements + int *deleted = malloc( nel * sizeof(int) ); + assert( deleted != NULL ); + int ndeleted = 0; + + for( int i=delpos; i<delpos+ndel; i++ ) + { + deleted[ndeleted++] = list[i]; + } + printf( "debug: deleting %d elements starting at pos %d: ", + ndel, delpos ); + print_int_array( 60, ndeleted, deleted, ',', stdout ); + putchar( '\n' ); + + free( deleted ); + } + + for( int i=delpos+ndel; i<nel; i++ ) + { + list[i-ndel] = list[i]; + } + + return nel-ndel; +} + + +int main( int argc, char **argv ) +{ + int argno = process_flag_n_m_args( "number-collision", argc, argv, + 1, 1000, "intlist" ); + int nel; + int *list = parse_int_args( argc, argv, argno, &nel ); + + if( debug ) + { + printf( "debug: initial list: " ); + print_int_array( 60, nel, list, ',', stdout ); + putchar( '\n' ); + } + + for( int round = 1; ; round++ ) + { + int pos = find_pos_neg( nel, list ); + if( debug ) + { + printf( "round %d: list = ", round ); + print_int_array( 60, nel, list, ',', stdout ); + printf( " pos = %d\n", pos ); + } + if( pos == -1 ) break; + + int a = list[pos]; + int b = list[pos+1]; + if( debug ) + { + printf( "debug: elements %d and %d collide\n", a, b ); + } + int ma = a; + int mb = abs(b); + int rempos = pos; // remove which starting position? + int nrem = 1; // how many to remove? + if( ma == mb ) // remove both + { + if( debug ) + { + printf( "debug: both elements %d and %d " + "explode\n", a, b ); + } + rempos = pos; + nrem = 2; + } else if( ma > mb ) + { + if( debug ) + { + printf( "debug: element %d explodes\n", b ); + } + rempos = pos+1; + } else + { + if( debug ) + { + printf( "debug: element %d explodes\n", a ); + } + } + + // Remove nrem elements starting at rempos from list[nel] + nel = remove_elements( nel, list, rempos, nrem ); + + if( debug ) + { + printf( "end of round %d: list = ", round ); + print_int_array( 60, nel, list, ',', stdout ); + putchar( '\n' ); + } + } + + print_int_array( 60, nel, list, ',', stdout ); + putchar( '\n' ); + return 0; +} diff --git a/challenge-210/duncan-c-white/C/parseints.c b/challenge-210/duncan-c-white/C/parseints.c new file mode 100644 index 0000000000..3e820eb334 --- /dev/null +++ b/challenge-210/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-210/duncan-c-white/C/parseints.h b/challenge-210/duncan-c-white/C/parseints.h new file mode 100644 index 0000000000..da5e145a86 --- /dev/null +++ b/challenge-210/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-210/duncan-c-white/C/printarray.c b/challenge-210/duncan-c-white/C/printarray.c new file mode 100644 index 0000000000..ddee597df3 --- /dev/null +++ b/challenge-210/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-210/duncan-c-white/C/printarray.h b/challenge-210/duncan-c-white/C/printarray.h new file mode 100644 index 0000000000..40efb83277 --- /dev/null +++ b/challenge-210/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-210/duncan-c-white/README b/challenge-210/duncan-c-white/README index a7d82c8b31..6013657b55 100644 --- a/challenge-210/duncan-c-white/README +++ b/challenge-210/duncan-c-white/README @@ -1,71 +1,90 @@ -Task 1: Special Bit Characters +Task 1: Task 1: Kill and Win -You are given an array of binary bits that ends with 0. - -Valid sequences in the bit string are: - -[0] -decodes-to-> "a" -[1, 0] -> "b" -[1, 1] -> "c" - -Write a script to print 1 if the last character is an 'a' otherwise -print 0. +You are given a list of integers. Write a script to get the maximum points. +You are allowed to take out (kill) any integer and remove from the list. +However if you do that then all integers exactly one-less or one-more would +also be removed. Find out the total of integers removed. Example 1 - Input: @bits = (1, 0, 0) - Output: 1 + Input: @int = (2, 3, 1) + Output: 6 - The given array bits can be decoded as 2-bits character (10) followed - by 1-bit character (0). + First we delete 2 and that would also delete 1 and 3. So the maximum + points we get is 6. Example 2 - Input: @bits = (1, 1, 1, 0) - Output: 0 - - Possible decode can be 2-bits character (11) followed by 2-bits - character (10) i.e. the last character is not 1-bit character. - -MY NOTES: very easy. decode string then check last letter of decoded version. -I wonder if there's a way of decoding-and-checking together, though. + Input: @int = (1, 1, 2, 2, 2, 3) + Output: 11 + + First we delete 2 and that would also delete both the 1's and the + 3. Now we have (2, 2). + Then we delete another 2 and followed by the third deletion of 2. So + the maximum points we get is 11. + +MY NOTES: very easy recursive "all paths" solution with accumulating points +so far, tracking the best (max) complete path found as we go. + +PS: Thinking about this AFTER writing the code, all paths necessarily lead +to the same total sum, as whenever we delete some elements we add them to +the sum, so once we've deleted all elements the total sum is necessarily +the sum of the original elements. So the "find all paths and pick the max +sum" logic is completely unnecessary. Finding any single path and it's score +would do. Hence, I don't understand the emphasis in the question above on the +"write a script to get the maximum points" wording, and why the examples above +show a particular path if any path would do.. It's possible that the question +meant "pick a path that leads to a solution in the shortest number of kaw +rounds" - that's compatible with example 1. But dammit if that's what was +meant, the question should have been clearer. So I'm leaving my code +alone as it answers the question well enough. GUEST LANGUAGE: As a bonus, I also had a go at translating ch-1.pl into C (look in the C directory for that). -Task 2: Merge Account +Task 2: Number Collision -You are given an array of accounts i.e. name with list of email addresses. +You are given an array of integers which can move in right direction if +it is positive and left direction when negative. If two numbers collide +then the smaller one will explode. And if both are same then they both +explode. We take the absolute value in consideration when comparing. -Write a script to merge the accounts where possible. The accounts can -only be merged if they have at least one email address in common. +All numbers move at the same speed, therefore any 2 numbers moving in +the same direction will never collide. + +Write a script to find out who survives the collision. Example 1: - Input: @accounts = [ ["A", "a1@a.com", "a2@a.com"], - ["B", "b1@b.com"], - ["A", "a3@a.com", "a1@a.com"] ] - ] + Input: @list = (2, 3, -1) + Output: (2, 3) - Output: [ ["A", "a1@a.com", "a2@a.com", "a3@a.com"], - ["B", "b1@b.com"] ] + The numbers 3 and -1 collide and -1 explodes in the end. So we are + left with (2, 3). Example 2: - Input: @accounts = [ ["A", "a1@a.com", "a2@a.com"], - ["B", "b1@b.com"], - ["A", "a3@a.com"], - ["B", "b2@b.com", "b1@b.com"] ] + Input: @list = (3, 2, -4) + Output: (-4) + + The numbers 2 and -4 collide and 2 explodes in the end. That gives us + (3, -4). Now the numbers 3 and -4 collide and 3 explodes. Finally we + are left with -4. + +Example 3: + + Input: @list = (1, -1) + Output: () - Output: [ ["A", "a1@a.com", "a2@a.com"], - ["A", "a3@a.com"], - ["B", "b1@b.com", "b2@b.com"] ] + The numbers 1 and -1 both collide and explode. Nothing left in the end. -MY NOTES: fiddly and rather inelegant, especially only being allowed to -merge two entries if the intersection of the email lists is non empty. -Will also need to choose an input format, how about a list of words of the -form A:a1@a.com,a2@a.com, B:b1@b.com, A:a3@a.com and B:b2@b.com,b1@b.com +MY NOTES: very unclear explanation, but stripped of all the "numbers moving +left and right" stuff this seems straightforward (I think): find pairs of +adjacent numbers Pos,Neg where Pos>0 and Neg<0 and remove Pos or Neg depending +on min(abs(Pos),abs(Neg)). Then repeat. I don't know whether one round should +find all such immediate (Pos,Neg) pairs, as all the examples show only one +explosion per round. Or perhaps that doesn't matter, as it's just more rounds. -(TODO) GUEST LANGUAGE: As a bonus, I also had a go at translating ch-2.pl into C -(TODO) (look in the C directory for that) +GUEST LANGUAGE: As a bonus, I also had a go at translating ch-2.pl into C +(look in the C directory for that) diff --git a/challenge-210/duncan-c-white/perl/ch-1.pl b/challenge-210/duncan-c-white/perl/ch-1.pl new file mode 100755 index 0000000000..8e9a1519d6 --- /dev/null +++ b/challenge-210/duncan-c-white/perl/ch-1.pl @@ -0,0 +1,93 @@ +#!/usr/bin/perl +# +# Task 1: Kill and Win +# +# You are given a list of integers. Write a script to get the maximum points. +# You are allowed to take out (kill) any integer and remove from the list. +# However if you do that then all integers exactly one-less or one-more would +# also be removed. Find out the total of integers removed. +# +# Example 1 +# +# Input: @int = (2, 3, 1) +# Output: 6 +# +# First we delete 2 and that would also delete 1 and 3. So the maximum +# points we get is 6. +# +# Example 2 +# +# Input: @int = (1, 1, 2, 2, 2, 3) +# Output: 11 +# +# First we delete 2 and that would also delete both the 1's and the +# 3. Now we have (2, 2). +# Then we delete another 2 and followed by the third deletion of 2. So +# the maximum points we get is 11. +# +# MY NOTES: very easy recursive solution with accumulating points so far. +# Reduce search space by picking each DISTINCT value at each stage, +# not EACH value. +# +# GUEST LANGUAGE: As a bonus, I also had a go at translating ch-1.pl into C +# (look in the C directory for that). +# + +use strict; +use warnings; +use feature 'say'; +use Getopt::Long; +use List::Util qw(max sum); +use Data::Dumper; + +my $debug=0; +die "Usage: kaw [--debug] list-of-ints\n" + unless GetOptions( "debug"=>\$debug ) && @ARGV>0; + +my @list = split( /,/, join(',',@ARGV) ); + +say "list: ", join(',',@list) if $debug; + +my $max = 0; + + +# +# findall( $sumsofar, @list ); +# Given a sumsofar and a list, find all "kill-and-win" +# paths through the list, updating $max with the maximum +# of all total sums of each complete path. +# +sub findall +{ + my( $sumsofar, @list ) = @_; + if( @list == 0 ) + { + $max = max( $max, $sumsofar ); + return; + } + # find all distinct values in list + my %set = map { $_ => 1 } @list; + foreach my $v (keys %set) + { + # ok, pick $v.. + + # kaw rule: remove all $v-1 and $v+1 values + my @newl = grep { $_ != $v-1 && $_ != $v+1 } @list; + + # and ONE $v value + my $nvseen = 0; + @newl = grep { $_ != $v || ( $_ == $v && $nvseen++ > 0) } @newl; + + my @deleted = grep { $_ == $v-1 || $_ == $v+1 } @list; + push @deleted, $v; + my $news = $sumsofar + sum(@deleted); + say "debug: kaw: list=", join(',',@list), + ", v=$v, deleted=", join(',',@deleted), + |
