From b1c9c32b460cfba36b971adce5451235de351b9a Mon Sep 17 00:00:00 2001 From: dcw Date: Sun, 7 May 2023 21:45:50 +0100 Subject: imported my solutions to this week's tasks (while on holiday), in Perl and C --- challenge-215/duncan-c-white/C/.cbuild | 2 +- challenge-215/duncan-c-white/C/Makefile | 18 +++ challenge-215/duncan-c-white/C/README | 9 ++ challenge-215/duncan-c-white/C/args.c | 234 ++++++++++++++++++++++++++++ challenge-215/duncan-c-white/C/args.h | 12 ++ challenge-215/duncan-c-white/C/ch-1.c | 84 ++++++++++ challenge-215/duncan-c-white/C/ch-2.c | 111 +++++++++++++ challenge-215/duncan-c-white/C/parseints.c | 114 ++++++++++++++ challenge-215/duncan-c-white/C/parseints.h | 1 + challenge-215/duncan-c-white/C/printarray.c | 39 +++++ challenge-215/duncan-c-white/C/printarray.h | 1 + challenge-215/duncan-c-white/README | 122 +++++---------- challenge-215/duncan-c-white/perl/ch-1.pl | 78 ++++++++++ challenge-215/duncan-c-white/perl/ch-2.pl | 105 +++++++++++++ 14 files changed, 850 insertions(+), 80 deletions(-) create mode 100644 challenge-215/duncan-c-white/C/Makefile create mode 100644 challenge-215/duncan-c-white/C/README create mode 100644 challenge-215/duncan-c-white/C/args.c create mode 100644 challenge-215/duncan-c-white/C/args.h create mode 100644 challenge-215/duncan-c-white/C/ch-1.c create mode 100644 challenge-215/duncan-c-white/C/ch-2.c create mode 100644 challenge-215/duncan-c-white/C/parseints.c create mode 100644 challenge-215/duncan-c-white/C/parseints.h create mode 100644 challenge-215/duncan-c-white/C/printarray.c create mode 100644 challenge-215/duncan-c-white/C/printarray.h create mode 100755 challenge-215/duncan-c-white/perl/ch-1.pl create mode 100755 challenge-215/duncan-c-white/perl/ch-2.pl diff --git a/challenge-215/duncan-c-white/C/.cbuild b/challenge-215/duncan-c-white/C/.cbuild index 835981f6f1..c168e34403 100644 --- a/challenge-215/duncan-c-white/C/.cbuild +++ b/challenge-215/duncan-c-white/C/.cbuild @@ -1,5 +1,5 @@ BUILD = ch-1 ch-2 -BUILD = ch-1 +#BUILD = ch-1 CFLAGS = -Wall -g #LDFLAGS = -lm #CFLAGS = -g diff --git a/challenge-215/duncan-c-white/C/Makefile b/challenge-215/duncan-c-white/C/Makefile new file mode 100644 index 0000000000..1b34ccd3b2 --- /dev/null +++ b/challenge-215/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-215/duncan-c-white/C/README b/challenge-215/duncan-c-white/C/README new file mode 100644 index 0000000000..78c5c3608e --- /dev/null +++ b/challenge-215/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 very similar (non-debugging and debugging) +output to the Perl originals. + +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-215/duncan-c-white/C/args.c b/challenge-215/duncan-c-white/C/args.c new file mode 100644 index 0000000000..20c21e6c30 --- /dev/null +++ b/challenge-215/duncan-c-white/C/args.c @@ -0,0 +1,234 @@ +#include +#include +#include +#include +#include +#include + + +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 +#include +#include +#include +#include +#include + +#include "args.h" +#include "parseints.h" +#include "printarray.h" + + +// +// bool issorted = sortedletters( word ); +// Return true iff the letters of word are sorted. +// +bool sortedletters( char *word ) +{ + int len = strlen(word); + for( int pos=0; pos word[pos+1] ) return false; + } + return true; +} + + +int main( int argc, char **argv ) +{ + int argno = process_flag_n_m_args( "odd-one-out", argc, argv, + 1, 1000, "wordlist" ); + + if( debug ) + { + printf( "debug: list: " ); + for( int i=argno; iargno ) putchar( ',' ); + printf( "%s", argv[i] ); + } + putchar( '\n' ); + } + + char *sorted[argc]; + int nsorted = 0; + char *nonsorted[argc]; + int nnonsorted = 0; + for( int i=argno; i0 ) putchar(','); + printf( "%s", sorted[i] ); + } + putchar( '\n' ); + printf( "unsorted words removed are: " ); + for( int i=0; i0 ) putchar(','); + printf( "%s", nonsorted[i] ); + } + putchar( '\n' ); + } + + return 0; +} diff --git a/challenge-215/duncan-c-white/C/ch-2.c b/challenge-215/duncan-c-white/C/ch-2.c new file mode 100644 index 0000000000..0d997a2ece --- /dev/null +++ b/challenge-215/duncan-c-white/C/ch-2.c @@ -0,0 +1,111 @@ +// Task 2: Number Placement +// +// C translation + +#include +#include +#include +#include +#include +#include + +#include "args.h" +#include "parseints.h" +#include "printarray.h" + + +// bool non01 = contains_non_01( string ); +// returns true iff the given string contains any char EXCEPT for 0 or 1. +// +bool contains_non_01( char *string ) +{ + for( char *s = string; *s; s++ ) + { + if( *s != '0' && *s != '1' ) return true; + } + return false; +} + + +// bool canfind = find_pat( startpos, count, bitstring, len ); +// Return true iff we can find the desired pattern (count zeros +// neither preceded nor followed by a one) in bitstring. +// +bool find_pat( int startpos, int count, char *bitstring, int len ) +{ + for( int i=startpos; i 0 ) + { + char p = bitstring[startpos-1]; + if( p == '1' ) return false; + if( debug ) + { + printf( "debug: preceding (%c) is not 1\n", p ); + } + } + int followpos = startpos + count; + if( followpos < len ) + { + char f = bitstring[followpos]; + if( f == '1' ) return false; + if( debug ) + { + printf( "debug: following (%c) is not 1\n", f ); + } + } + if( debug ) + { + printf( "found pattern at startpos %d\n", startpos ); + } + + return 1; +} + + +int main( int argc, char **argv ) +{ + int argno = process_flag_n_args( "number-replacement", argc, argv, + 2, "count bitstring" ); + int count = atoi( argv[argno++] ); + char *bitstring = argv[argno]; + + if( debug ) + { + printf( "debug: count=%d, bitstring: %s\n", count, bitstring ); + } + + if( contains_non_01( bitstring ) ) + { + fprintf( stderr, "number-replacement: bitstring %s must " + "only contain 0 and 1\n", bitstring ); + exit(1); + } + + int len = strlen( bitstring ); + for( int startpos=0; startpos<=len-count; startpos++ ) + { + if( debug ) + { + printf( "trying find_pat starting at %d\n", startpos ); + } + if( find_pat( startpos, count, bitstring, len ) ) + { + if( debug ) + { + printf( "succeeded at %d\n", startpos ); + } + for( int i=0; i +#include +#include +#include +#include +#include + +#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 +#include + + +// print_int_array( maxw, nelements, results[], sep, outfile ); +// format results[0..nelements-1] as a 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 maxw ) + { + fputc( '\n', out ); + linelen = 0; + } else if( i>0 ) + { + fputc( ' ', out ); + linelen++; + } + + linelen += len; + fprintf( out, "%s", buf ); + if( i0 ) + //{ + // fputc( '\n', out ); + //} +} diff --git a/challenge-215/duncan-c-white/C/printarray.h b/challenge-215/duncan-c-white/C/printarray.h new file mode 100644 index 0000000000..40efb83277 --- /dev/null +++ b/challenge-215/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-215/duncan-c-white/README b/challenge-215/duncan-c-white/README index 17df43b304..b035eae705 100644 --- a/challenge-215/duncan-c-white/README +++ b/challenge-215/duncan-c-white/README @@ -1,112 +1,76 @@ -Task 1: Rank Score +Task 1: Odd one Out -You are given a list of scores (>=1). - -Write a script to rank each score in descending order. First three will -get medals i.e. G (Gold), S (Silver) and B (Bronze). Rest will just get -the ranking number. - -Use the standard model of giving equal scores equal rank, then advancing -that number of ranks. +You are given a list of words (alphabetic characters only) of same size. +Write a script to remove all words not sorted alphabetically and print +the number of words in the list that are not alphabetically sorted. Example 1 - Input: @scores = (1,2,4,3,5) - Output: (5,4,S,B,G) + Input: @words = ('abc', 'xyz', 'tsu') + Output: 1 - Score 1 is the 5th rank. - Score 2 is the 4th rank. - Score 4 is the 2nd rank i.e. Silver (S). - Score 3 is the 3rd rank i.e. Bronze (B). - Score 5 is the 1st rank i.e. Gold (G). + The words 'abc' and 'xyz' are sorted and can't be removed. + The word 'tsu' is not sorted and hence can be removed. Example 2 - Input: @scores = (8,5,6,7,4) - Output: (G,4,B,S,5) + Input: @words = ('rat', 'cab', 'dad') + Output: 3 - Score 8 is the 1st rank i.e. Gold (G). - Score 4 is the 4th rank. - Score 6 is the 3rd rank i.e. Bronze (B). - Score 7 is the 2nd rank i.e. Silver (S). - Score 4 is the 5th rank. + None of the words in the given list are sorted. + Therefore all three needs to be removed. Example 3 - Input: @list = (3,5,4,2) - Output: (B,G,S,4) + Input: @words = ('x', 'y', 'z') + Output: 0 -Example 4 - - Input: @scores = (2,5,2,1,7,5,1) - Output: (4,S,4,6,G,S,6) - -MY NOTES: sounds pretty easy, although scores (high is best) and ranks (low -is best) are a little confusing. Even worse is joint ranks for equal scores. -Start from the end: Gold is a label for rank 1, Single is a label for rank 2, -Bronze is a label for rank 3. So work out the ranks (including the nasty -joint ranks thing) and then apply the G/S/B stuff at the end. +MY NOTES: strangely worded, all the stuff about removing words you don't want +and then counting what's left (but not displaying what's left) can be +simplified to: count what you want (the non-sorted words), and that's easy. +But on second thought, let's remove the words anyway, even if we only print +them out in debug mode. GUEST LANGUAGE: As a bonus, I've had a go at translating ch-1.pl into C, look in the C/ directory for that. -Task 2: Collect Points +Task 2: Number Placement + +You are given a list of numbers having just 0 and 1. You are also given +placement count (>=1). -You are given a list of numbers. -You will perform a series of removal operations. For each operation, -you remove from the list N (N >= 1) equal and consecutive numbers, -and add to your score N x N. -Determine the maximum possible score. +Write a script to find out if it is possible to replace 0 with 1 in the +given list. The only condition is that you can only replace when there +is no 1 on either side. Print 1 if it is possible otherwise 0. Example 1: - Input: @numbers = (2,4,3,3,3,4,5,4,2) - Output: 23 + Input: @numbers = (1,0,0,0,1), $count = 1 + Output: 1 - We see three 3's next to each other so let us remove that first and - collect 3 x 3 points. - So now the list is (2,4,4,5,4,2). - Let us now remove 5 so that all 4's can be next to each other and - collect 1 x 1 point. - So now the list is (2,4,4,4,2). - Time to remove three 4's and collect 3 x 3 points. - Now the list is (2,2). - Finally remove both 2's and collect 2 x 2 points. - So the total points collected is 9 + 1 + 9 + 4 => 23. + You are asked to replace only one 0 as given count is 1. + We can easily replace middle 0 in the list i.e. (1,0,1,0,1). Example 2: - Input: @numbers = (1,2,2,2,2,1) - Output: 20 + Input: @numbers = (1,0,0,0,1), $count = 2 + Output: 0 - Remove four 2's first and collect 4 x 4 points. - Now the list is (1,1). - Finally remove the two 1's and collect 2 x 2 points. - So the total points collected is 16 + 4 => 20. + You are asked to replace two 0's as given count is 2. + It is impossible to replace two 0's. Example 3: - Input: @numbers = (1) + Input: @numbers = (1,0,0,0,0,0,0,0,1), $count = 3 Output: 1 -Example 4: - - Input: @numbers = (2,2,2,1,1,2,2,2) - Output: 40 - - Remove two 1's = 2 x 2 points. - Now the list is (2,2,2,2,2,2). - Then remove six 2's = 6 x 6 points. +MY NOTES: ok, so it means "can you replace COUNT consecutive +zeros with ones, where neither the preceding or following number is 1". +i.e. where there is either NO preceding or following number (the COUNT +consecutive zeros start or end of the sequence), or a 0 precedes and +follows our COUNT consecutive zeros. +So I guess we just run a start-point along the sequence and check. -MY NOTES: hmmm.. that seems a bit tricky, in particular I can't immediately -see whether we have do try all possible first moves (etc), or just the first -move (or nth move more generally) with the greatest score contribution.. -Actually, eg 4 shows that we CAN'T just take the individual move with the -greatest score contribution, cos otherwise we'd take one of the "length 3" -sequences and pass up the "length 6" sequence that becomes available later.. -So, yes, it's a brute force "find all" type problem.. - -GUEST LANGUAGE: As a bonus, I will soon have a go at translating ch-2.pl -into C, but I run out of time today.. when it's done, look in the C/ -directory for that. +GUEST LANGUAGE: As a bonus, I had a go at translating ch-2.pl into C, +look in the C/ directory for that. diff --git a/challenge-215/duncan-c-white/perl/ch-1.pl b/challenge-215/duncan-c-white/perl/ch-1.pl new file mode 100755 index 0000000000..dc0e73b010 --- /dev/null +++ b/challenge-215/duncan-c-white/perl/ch-1.pl @@ -0,0 +1,78 @@ +#!/usr/bin/perl +# +# Task 1: Odd one Out +# +# You are given a list of words (alphabetic characters only) of same size. +# Write a script to remove all words not sorted alphabetically and print +# the number of words in the list that are not alphabetically sorted. +# +# Example 1 +# +# Input: @words = ('abc', 'xyz', 'tsu') +# Output: 1 +# +# The words 'abc' and 'xyz' are sorted and can't be removed. +# The word 'tsu' is not sorted and hence can be removed. +# +# Example 2 +# +# Input: @words = ('rat', 'cab', 'dad') +# Output: 3 +# +# None of the words in the given list are sorted. +# Therefore all three needs to be removed. +# +# Example 3 +# +# Input: @words = ('x', 'y', 'z') +# Output: 0 +# +# MY NOTES: strangely worded, all the stuff about removing words you don't want +# and then counting what's left (but not displaying what's left) can be +# simplified to: count what you want (the non-sorted words), and that's easy. +# But on second thought, let's remove the words anyway, even if we only print +# them out in debug mode. +# +# GUEST LANGUAGE: As a bonus, I've 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 Data::Dumper; + +my $debug=0; +die "Usage: odd-one-out [--debug] wordlist\n" + unless GetOptions( "debug"=>\$debug ) && @ARGV>0; + +my @list = split( /,/, join(',',@ARGV) ); + +say "debug: list: ", join(',',@list) if $debug; + +# +# my $issorted = sortedletters( $word ); +# Return true iff the letters of $word are sorted. +# +sub sortedletters +{ + my( $word ) = @_; + my @let = split( //, $word ); + foreach my $pos (0..$#let-1) + { + return 0 if $let[$pos] gt $let[$pos+1]; + } + return 1; +} + + +my @sorted = grep { sortedletters($_) } @list; +my $removed = @list - @sorted; +say $removed; +if( $debug ) +{ + say "list (of sorted) words is: ", join(',',@sorted); + my @notsorted = grep { ! sortedletters($_) } @list; + say "unsorted words removed are: ", join(',',@notsorted); +} diff --git a/challenge-215/duncan-c-white/perl/ch-2.pl b/challenge-215/duncan-c-white/perl/ch-2.pl new file mode 100755 index 0000000000..6693478c01 --- /dev/null +++ b/challenge-215/duncan-c-white/perl/ch-2.pl @@ -0,0 +1,105 @@ +#!/usr/bin/perl +# +# Task 2: Number Placement +# +# You are given a list of numbers having just 0 and 1. You are also given +# placement count (>=1). +# +# Write a script to find out if it is possible to replace 0 with 1 in the +# given list. The only condition is that you can only replace when there +# is no 1 on either side. Print 1 if it is possible otherwise 0. +# +# Example 1: +# +# Input: @numbers = (1,0,0,0,1), $count = 1 +# Output: 1 +# +# You are asked to replace only one 0 as given count is 1. +# We can easily replace middle 0 in the list i.e. (1,0,1,0,1). +# +# Example 2: +# +# Input: @numbers = (1,0,0,0,1), $count = 2 +# Output: 0 +# +# You are asked to replace two 0's as given count is 2. +# It is impossible to replace two 0's. +# +# Example 3: +# +# Input: @numbers = (1,0,0,0,0,0,0,0,1), $count = 3 +# Output: 1 +# +# MY NOTES: ok, so it means "can you replace COUNT consecutive +# zeros with ones, where neither the preceding or following number is 1". +# i.e. where there is either NO preceding or following number (the COUNT +# consecutive zeros start or end of the sequence), or a 0 precedes and +# follows our COUNT consecutive zeros. +# So I guess we just run a start-point along the sequence and check. +# +# GUEST LANGUAGE: As a bonus, I 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 Function::Parameters; + +my $debug=0; +die "Usage: number-replacement [--debug] count bitstring\n" + unless GetOptions( "debug"=>\$debug ) && @ARGV == 2; +my( $count, $bitstring ) = @ARGV; + +if( $debug ) +{ + say "debug: count=$count, bitstring=$bitstring"; +} + +die "number-replacement: bitstring $bitstring must only contain 0 and 1\n" + if $bitstring =~ /[^01]/; + +# +# my $canfind = find_pat( $startpos, $count, $bitstring, $len ); +# Return true iff we can find the desired pattern ($count zeros +# neither preceded nor followed by a one) in $bitstring. +# +fun find_pat( $startpos, $count, $bitstring, $len ) +{ + my $zeroes = '0' x $count; + return 0 unless substr($bitstring,$startpos,$count) eq $zeroes; + say "debug: found $zeroes starting at $startpos" if $debug; + if( $startpos > 0 ) + { + my $p = substr($bitstring,$startpos-1,1); + return 0 if $p eq '1'; + say "debug: preceding ($p) is not 1" if $debug; + } + my $followpos = $startpos + $count; + if( $followpos < $len ) + { + my $f = substr($bitstring,$followpos,1); + #say "debug: following=$f" if $debug; + say "debug: following ($f) is not 1" if $debug; + } + say "found pattern at startpos $startpos" if $debug; + + return 1; +} + + +my $len = length( $bitstring ); +foreach my $startpos (0..$len-$count) +{ + #say "trying find_pat starting at $startpos" if $debug; + if( find_pat( $startpos, $count, $bitstring, $len ) ) + { + #say "debug: succeeded at startpos=$startpos" if $debug; + substr( $bitstring, $startpos, $count, '1' x $count ); + say "1 (changed bitstring to $bitstring)"; + exit 0; + } +} +say 0; -- cgit