diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-04-24 23:58:24 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-04-24 23:58:24 +0100 |
| commit | ecb254d67a60af87a09ef59fc1e188e4ac2892af (patch) | |
| tree | d95af3d13509b27e4561d71add5a014d00d22a22 /challenge-161 | |
| parent | 4ce40b22788b11adb3919fa00d7bfc1c707728af (diff) | |
| parent | b8594d18fb15a6b0834ee97e24ba594d3ec32421 (diff) | |
| download | perlweeklychallenge-club-ecb254d67a60af87a09ef59fc1e188e4ac2892af.tar.gz perlweeklychallenge-club-ecb254d67a60af87a09ef59fc1e188e4ac2892af.tar.bz2 perlweeklychallenge-club-ecb254d67a60af87a09ef59fc1e188e4ac2892af.zip | |
Merge pull request #5997 from dcw803/master
imported my solutions to this week's tasks - both Perl
Diffstat (limited to 'challenge-161')
| -rw-r--r-- | challenge-161/duncan-c-white/C/README | 2 | ||||
| -rw-r--r-- | challenge-161/duncan-c-white/C/ch-1.c | 154 | ||||
| -rw-r--r-- | challenge-161/duncan-c-white/README | 72 | ||||
| -rw-r--r-- | challenge-161/duncan-c-white/dictionary.txt | 39172 | ||||
| -rwxr-xr-x | challenge-161/duncan-c-white/perl/ch-1.pl | 57 | ||||
| -rwxr-xr-x | challenge-161/duncan-c-white/perl/ch-2.pl | 212 |
6 files changed, 39630 insertions, 39 deletions
diff --git a/challenge-161/duncan-c-white/C/README b/challenge-161/duncan-c-white/C/README index 8fcb95df91..61d52a58c0 100644 --- a/challenge-161/duncan-c-white/C/README +++ b/challenge-161/duncan-c-white/C/README @@ -1 +1,3 @@ Thought I'd also have a go at translating ch-1.pl into C.. + +Produces identical (non-debugging) output to my ch-1.pl:-) diff --git a/challenge-161/duncan-c-white/C/ch-1.c b/challenge-161/duncan-c-white/C/ch-1.c new file mode 100644 index 0000000000..75c8ef9965 --- /dev/null +++ b/challenge-161/duncan-c-white/C/ch-1.c @@ -0,0 +1,154 @@ +/* + * TASK #1 - Abecedarian Words + * + * An abecedarian word is a word whose letters are arranged in alphabetical + * order. For example, 'knotty' is an abecedarian word, but 'knots' + * is not. Output or return a list of all abecedarian words in the + * dictionary, sorted in decreasing order of length. + * + * Optionally, using only abecedarian words, leave a short comment in + * your code to make your reviewer smile. + * + * MY NOTES: ok. Pretty easy. Amusing phrase: + * "I am not a cellos guy" (Jealous Guy, Roxy Music) + */ + +#include <stdio.h> +#include <stdlib.h> +#include <stdbool.h> +#include <string.h> +#include <assert.h> +#include <unistd.h> +#include <ctype.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + + + + +/* + * bool isabeced = is_abeced( char *word ); + * Return true iff word is an Abecedarian-word, i.e. all + * it's letters are in sorted order. + */ +bool is_abeced( char *word ) +{ + int len = strlen(word); + for( int i=0; i<len-1; i++ ) + { + //printf( "debug: i=%d, w[i]=%c, w[i+1]=%c\n", + // i, word[i], word[i+1] ); + if( word[i] > word[i+1] ) + { + return false; + } + } + //printf( "debug: word %s is abecedarian\n", word ); + return true; +} + +bool debug=false; +#define DICTFILE "../dictionary.txt" + + +int compareword(const void *av, const void *bv) +{ + char **a = (char **)av; + char **b = (char **)bv; + //printf( "debug: cw: a=%s, b=%s\n", *a, *b ); + int x = strlen(*b) - strlen(*a); // descending order + if( x != 0 ) return x; + return strcmp(*a,*b); +} + + +int main( void ) +{ + #if 0 + bool isabeced = is_abeced( "hello" ); + printf( "debug: abeced(hello)=%d\n", (int)isabeced ); + exit(1); + isabeced = is_abeced( "xv" ); + printf( "debug: abeced(xv)=%d\n", (int)isabeced ); + exit(1); + #endif + + struct stat st; + if( stat( DICTFILE, &st ) != 0 ) + { + fprintf( stderr, "Abecedarian-words: can't stat " DICTFILE ); + exit(1); + } + int size = st.st_size; + + // Allocate a dictionary buffer for all dictionary words + char *dictbuf = malloc( size+1 ); + assert( dictbuf != NULL ); + + // allocate an equivalent buffer for abecedarian words + char *abecbuf = malloc( size+1 ); + assert( abecbuf != NULL ); + + // read the entire dictionary into dictbuf in one fell swoop + int fd = open( DICTFILE, O_RDONLY ); + assert( fd != -1 ); + int haveread = read(fd, dictbuf, size); + assert( haveread==size ); + dictbuf[size-1] = '\0'; + close(fd); + + // modify the dictbuf: lower casing it, separating words + // and counting them too + char *s = dictbuf; + int nwords = 1; + for( int i=0; i<size; i++ ) + { + *s = tolower(*s); + if( *s == '\n' ) + { + *s = '\0'; + nwords++; + } + s++; + } + + printf( "debug: Found %d words\n", nwords ); + //exit(1); + + char **abecedword = malloc( nwords * sizeof(char *) ); + assert( abecedword != NULL ); + + // Select only those words which are abeced.. + char *src = dictbuf; + char *dst = abecbuf; + int nsel = 0; + for( int w=0; w<nwords; w++ ) + { + //printf( "debug: word %d=%s\n", w, src ); + int len = strlen(src); + if( is_abeced(src) ) + { + printf( "debug: abeced word %d=%s\n", nsel, src ); + abecedword[nsel] = dst; + strcpy( dst, src ); + dst += len+1; + nsel++; + } + src += len+1; + } + + printf( "debug: Found %d Abecedarian words\n", nsel ); + //exit(1); + + // sort selected word array in descending order of length + qsort( abecedword, nsel, sizeof(char *), &compareword ); + + // display the Abecedarian words + for( int i=0; i<nsel; i++ ) + { + printf( "%s\n", abecedword[i] ); + } + + return 0; +} diff --git a/challenge-161/duncan-c-white/README b/challenge-161/duncan-c-white/README index b73af0151f..a10c12ba95 100644 --- a/challenge-161/duncan-c-white/README +++ b/challenge-161/duncan-c-white/README @@ -1,58 +1,52 @@ -TASK #1 - Four Is Magic +TASK #1 - Abecedarian Words -You are given a positive number, $n < 10. +An abecedarian word is a word whose letters are arranged in alphabetical +order. For example, 'knotty' is an abecedarian word, but 'knots' +is not. Output or return a list of all abecedarian words in the +dictionary, sorted in decreasing order of length. -Write a script to generate english text sequence starting with the English -cardinal representation of the given number, the word 'is' and then -the English cardinal representation of the count of characters that made -up the first word, followed by a comma. Continue until you reach four. +Optionally, using only abecedarian words, leave a short comment in your code to make your reviewer smile. -Example 1: - - Input: $n = 5 - Output: Five is four, four is magic. - -Example 2: - - Input: $n = 7 - Output: Seven is five, five is four, four is magic. +MY NOTES: ok. Pretty easy. -Example 3: +GUEST LANGUAGE: As a bonus, I also had a go at translating ch-1.pl into C, +look in the C directory for that. - Input: $n = 6 - Output: Six is three, three is five, five is four, four is magic. -MY NOTES: ok. Pretty easy. +TASK #2 - Pangrams -GUEST LANGUAGE: As a bonus, I'd also have a go at translating ch-1.pl into C, -look in the C directory. +A pangram is a sentence or phrase that uses every letter in the English +alphabet at least once. For example, perhaps the most well known +pangram is: +the quick brown fox jumps over the lazy dog -TASK #2 - Equilibrium Index +Using the provided dictionary, so that you don't need to include +individual copy, generate at least one pangram. -You are give an array of integers, @n. +Your pangram does not have to be a syntactically valid English sentence +(doing so would require far more work, and a dictionary of nouns, verbs, +adjectives, adverbs, and conjunctions). Also note that repeated letters, +and even repeated words, are permitted. -Write a script to find out the Equilibrium Index of the given array, if found. +BONUS: Constrain or optimize for something interesting (completely up +to you), such as: -For an array A consisting n elements, index i is an equilibrium index -if the sum of elements of subarray A[0..i-1] is equal to the sum of -elements of subarray A[i+1..n-1]. +Shortest possible pangram (difficult) -Example 1: +Pangram which contains only abecedarian words (see challenge 1) - Input: @n = (1, 3, 5, 7, 9) - Output: 3 +Pangram such that each word "solves" exactly one new letter. For example, +such a pangram might begin with (newly solved letters in bold): + a ah hi hid die ice tea ... -Example 2: + (What is the longest possible pangram generated with this method? All + solutions will contain 26 words, so focus on the letter count.) - Input: @n = (1, 2, 3, 4, 5) - Output: -1 as no Equilibrium Index found. +Pangrams that have the weirdest (PG-13) Google image search results -Example 3: +Anything interesting goes! - Input: @n = (2, 4, 2) - Output: 1 -MY NOTES: ok. Pretty easy. Rather than recomputing sums each time, -let's keep track of "the sum before i" and "the sum after i" and -adjust them each pass.. +MY NOTES: hmmm. Pretty easy to find a pangram in a brute force fashion, +but anything more constrained sounds pretty hard. diff --git a/challenge-161/duncan-c-white/dictionary.txt b/challenge-161/duncan-c-white/dictionary.txt new file mode 100644 index 0000000000..1f915f2975 --- /dev/null +++ b/challenge-161/duncan-c-white/dictionary.txt @@ -0,0 +1,39172 @@ +a +aardvark +aback +abacus +abacuses +abandon +abandoned +abandoning +abandonment +abandons +abate +abated +abates +abating +abbey +abbeys +abbot +abbots +abbreviate +abbreviated +abbreviates +abbreviating +abbreviation +abbreviations +abdicate +abdicated +abdicates +abdicating +abdication +abdications +abdomen +abdomens +abdominal +abduct +abducted +abducting +abducts +aberration +aberrations +abet +abets +abetted +abetting +abhor +abhorred +abhorrence +abhorrent +abhorring +abhors +abide +abides +abiding +abilities +ability +abject +ablaze +able +abler +ablest +ably +abnormal +abnormalities +abnormality +abnormally +aboard +abode +abodes +abolish +abolished +abolishes +abolishing +abolition +abominable +abomination +aboriginal +aborigine +aborigines +abort +aborted +aborting +abortion +abortions +abortive +aborts +abound +abounded +abounding +abounds +about +above +aboveboard +abrasive +abrasives +abreast +abridge +abridged +abridges +abridging +abroad +abrupt +abrupter +abruptest +abruptly +abscess +abscessed +abscesses +abscessing +abscond +absconded +absconding +absconds +absence +absences +absent +absented +absentee +absentees +absenting +absents +absolute +absolutely +absolutes +absolutest +absolve +absolved +absolves +absolving +absorb +absorbed +absorbent +absorbents +absorbing +absorbs +absorption +abstain +abstained +abstaining +abstains +abstention +abstentions +abstinence +abstract +abstracted +abstracting +abstraction +abstractions +abstracts +abstruse +absurd +absurder +absurdest +absurdities +absurdity +absurdly +abundance +abundances +abundant +abundantly +abuse +abused +abuser +abusers +abuses +abusing +abusive +abysmal +abyss +abysses +academic +academically +academics +academies +academy +accede +acceded +accedes +acceding +accelerate +accelerated +accelerates +accelerating +acceleration +accelerations +accelerator +accelerators +accent +accented +accenting +accents +accentuate +accentuated +accentuates +accentuating +accept +acceptability +acceptable +acceptably +acceptance +acceptances +accepted +accepting +accepts +access +accessed +accesses +accessibility +accessible +accessing +accessories +accessory +accident +accidental +accidentally +accidentals +accidents +acclaim +acclaimed +acclaiming +acclaims +acclimate +acclimated +acclimates +acclimating +acclimatize +acclimatized +acclimatizes +acclimatizing +accolade +accolades +accommodate +accommodated +accommodates +accommodating +accommodation +accommodations +accompanied +accompanies +accompaniment +accompaniments +accompanist +accompanists +accompany +accompanying +accomplice +accomplices +accomplish +accomplished +accomplishes +accomplishing +accomplishment +accomplishments +accord +accordance +accorded +according +accordingly +accordion +accordions +accords +accost +accosted +accosting +accosts +account +accountability +accountable +accountancy +accountant +accountants +accounted +accounting +accounts +accredit +accredited +accrediting +accredits +accrue +accrued +accrues +accruing +accumulate +accumulated +accumulates +accumulating +accumulation +accumulations +accuracy +accurate +accurately +accusation +accusations +accuse +accused +accuser +accusers +accuses +accusing +accustom +accustomed +accustoming +accustoms +ace +aced +aces +ache +ached +aches +achievable +achieve +achieved +achievement +achievements +achieves +achieving +aching +acid +acidity +acids +acing +acknowledge +acknowledged +acknowledges +acknowledging +acknowledgment +acknowledgments +acne +acorn +acorns +acoustic +acoustics +acquaint +acquaintance +acquaintances +acquainted +acquainting +acquaints +acquiesce +acquiesced +acquiescence +acquiesces +acquiescing +acquire +acquired +acquires +acquiring +acquisition +acquisitions +acquit +acquits +acquittal +acquittals +acquitted +acquitting +acre +acreage +acreages +acres +acrid +acrider +acridest +acrimonious +acrimony +acrobat +acrobatic +acrobatics +acrobats +acronym +acronyms +across +acrylic +acrylics +act +acted +acting +action +actions +activate +activated +activates +activating +active +actively +actives +activist +activists +activities +activity +actor +actors +actress +actresses +acts +actual +actualities +actuality +actually +actuary +acumen +acupuncture +acute +acutely +acuter +acutes +acutest +ad +adage +adages +adamant +adapt +adaptable +adaptation +adaptations +adapted +adapter +adapting +adaptive +adapts +add +added +addendum +addict +addicted +addicting +addiction +addictions +addictive +addicts +adding +addition +additional +additionally +additions +additive +additives +address +addressed +addressee +addressees +addresses +addressing +adds +adept +adepts +adequate +adequately +adhere +adhered +adherence +adherent +adherents +adheres +adhering +adhesion +adhesive +adhesives +adjacent +adjective +adjectives +adjoin +adjoined +adjoining +adjoins +adjourn +adjourned +adjourning +adjournment +adjournments +adjourns +adjunct +adjuncts +adjust +adjustable +adjusted +adjusting +adjustment +adjustments +adjusts +administer +administered +administering +administers +administration +administrations +administrative +administrator +administrators +admirable +admirably +admiral +admirals +admiration +admire +admired +admirer +admirers +admires +admiring +admissible +admission +admissions +admit +admits +admittance +admitted +admittedly +admitting +admonish +admonished +admonishes +admonishing +admonition +admonitions +ado +adobe +adobes +adolescence +adolescences +adolescent +adolescents +adopt +adopted +adopting +adoption +adoptions +adopts +adorable +adoration +adore +adored +adores +adoring +adorn +adorned +adorning +adornment +adornments +adorns +adrift +adroit +adroitly +ads +adulation +adult +adulterate +adulterated +adulterates +adulterating +adulteration +adulteries +adultery +adulthood +adults +advance +advanced +advancement +advancements +advances +advancing +advantage +advantaged +advantageous +advantages +advantaging +advent +adventure +adventured +adventurer +adventurers +adventures +adventuring +adventurous +adverb +adverbial +adverbials +adverbs +adversaries +adversary +adverse +adversely +adverser +adversest +adversities +adversity +advert +advertise +advertised +advertisement +advertisements +advertiser +advertisers +advertises +advertising +adverts +advice +advisable +advise +advised +adviser +advisers +advises +advising +advisories +advisory +advocate +advocated +advocates +advocating +aerial +aerials +aerodynamic +aerodynamics +aerosol +aerosols +aerospace +aesthetic +aesthetically +afar +affable +affably +affair +affairs +affect +affectation +affectations +affected +affecting +affection +affectionate +affectionately +affections +affects +affidavit +affidavits +affiliate +affiliated +affiliates +affiliating +affiliation +affiliations +affinities +affinity +affirm +affirmation +affirmations +affirmative +affirmatives +affirmed +affirming +affirms +affix +affixed +affixes +affixing +afflict +afflicted +afflicting +affliction +afflictions +afflicts +affluence +affluent +afford +affordable +afforded +affording +affords +affront +affronted +affronting +affronts +afield +aflame +afloat +afoot +aforementioned +aforesaid +afraid +afresh +after +aftereffect +aftereffects +afterlife +afterlives +aftermath +aftermaths +afternoon +afternoons +afterthought +afterthoughts +afterward +afterwards +again +against +age +aged +agencies +agency +agenda +agendas +agent +agents +ages +aggravate +aggravated +aggravates +aggravating +aggravation +aggravations +aggregate +aggregated +aggregates +aggregating +aggression +aggressive +aggressively +aggressiveness +aggressor +aggressors +aghast +agile +agiler +agilest +agility +aging +agitate +agitated +agitates +agitating +agitation +agitations +agitator +agitators +aglow +agnostic +agnosticism +agnostics +ago +agonies +agonize +agonized +agonizes +agonizing +agony +agree +agreeable +agreeably +agreed +agreeing +agreement +agreements +agrees +agricultural +agriculture +aground +ah +ahead +ahoy +aid +aide +aided +aides +aiding +aids +ail +ailed +ailing +ailment +ailments +ails +aim +aimed +aiming +aimless +aimlessly +aims +air +airborne +aircraft +aired +airfield +airfields +airier +airiest +airing +airline +airliner +airliners +airlines +airmail +airmailed +airmailing +airmails +airplane +airplanes +airport +airports +airs +airstrip +airstrips +airtight +airy +aisle +aisles +ajar +akin +alarm +alarmed +alarming +alarmingly +alarmist +alarmists +alarms +alas +albeit +albino +albinos +album +albums +alcohol +alcoholic +alcoholics +alcoholism +alcohols +alcove +alcoves +ale +alert +alerted +alerting +alerts +ales +alga +algae +algebra +algebraic +algorithm +algorithms +alias +aliased +aliases +aliasing +alibi +alibied +alibiing +alibis +alien +alienate +alienated +alienates +alienating +alienation +aliened +aliening +aliens +alight +alighted +alighting +alights +align +aligned +aligning +alignment +alignments +aligns +alike +alimony +alive +alkali +alkalies +alkaline +all +allay +allayed +allaying +allays +allegation +allegations +allege +alleged +allegedly +alleges +allegiance +allegiances +alleging +allegorical +allegories +allegory +allergic +allergies +allergy +alleviate +alleviated +alleviates +alleviating +alley +alleys +alliance +alliances +allied +allies +alligator +alligators +allocate +allocated +allocates +allocating +allocation +allocations +allot +allotment +allotments +allots +allotted +allotting +allow +allowable +allowance +allowances +allowed +allowing +allows +alloy +alloyed +alloying +alloys +allude +alluded +alludes +alluding +allure +allured +allures +alluring +allusion +allusions +ally +allying +almanac +almanacs +almighty +almond +almonds +almost +alms +aloft +alone +along +alongside +aloof +aloud +alpha +alphabet +alphabetic +alphabetical +alphabetically +alphabets +alphanumeric +already +also +altar +altars +alter +alterable +alteration +alterations +altered +altering +alternate +alternated +alternately +alternates +alternating +alternation +alternative +alternatively +alternatives +alternator +alters +although +altitude +altitudes +alto +altogether +altos +altruism +altruistic +aluminum +always +am +amalgamate +amalgamated +amalgamates +amalgamating +amalgamation +amalgamations +amass +amassed +amasses +amassing +amateur +amateurish +amateurs +amaze +amazed +amazement +amazes +amazing +amazingly +ambassador +ambassadors +amber +ambiance +ambiances +ambidextrous +ambient +ambiguities +ambiguity +ambiguous +ambiguously +ambition +ambitions +ambitious +ambitiously +ambivalence +ambivalent +amble +ambled +ambles +ambling +ambulance +ambulances +ambush +ambushed +ambushes +ambushing +amen +amenable +amend +amended +amending +amendment +amendments +amends +amenities +amenity +amethyst +amethysts +amiable +amiably +amicable +amicably +amid +amiss +ammonia +ammunition +amnesia +amnestied +amnesties +amnesty +amnestying +amoeba +amoebae +amoebas +amok +among +amoral +amorous +amorphous +amount +amounted +amounting +amounts +amp +ampere +amperes +ampersand +ampersands +amphetamine +amphetamines +amphibian +amphibians +amphibious +amphitheater +amphitheaters +ample +ampler +amplest +amplification +amplifications +amplified +amplifier +amplifiers +amplifies +amplify +amplifying +amplitude +amply +amps +amputate +amputated +amputates +amputating +amputation +amputations +amulet +amulets +amuse +amused +amusement +amusements +amuses +amusing +amusingly +an +anachronism +anachronisms +anagram +anal +analgesic +analgesics +analog +analogies +analogous +analogue +analogy +analyses +analysis +analyst +analysts +analytic +analyze +analyzed +analyzer +analyzes +analyzing +anarchic +anarchism +anarchist +anarchists +anarchy +anathema +anatomical +anatomies +anatomy +ancestor +ancestors +ancestral +ancestries +ancestry +anchor +anchorage +anchorages +anchored +anchoring +anchors +anchovies +anchovy +ancient +ancienter +ancientest +ancients +and +android +androids +anecdote +anecdotes +anemia +anemic +anesthesia +anesthetic +anesthetics +anew +angel +angelic +angels +anger +angered +angering +angers +angle +angled +angler +anglers +angles +angling +angrier +angriest +angrily +angry +angst +anguish +anguished +anguishes +anguishing +angular +animal +animals +animate +animated +animates +animating +animation +animations +animosities +animosity +ankle +ankles +annals +annex +annexation +annexations +annexed +annexes +annexing +annihilate +annihilated +annihilates +annihilating +annihilation +anniversaries +anniversary +annotate +annotated +annotates +annotating +annotation +annotations +announce +announced +announcement +announcements +announcer +announcers +announces +announcing +annoy +annoyance +annoyances +annoyed +annoying +annoyingly +annoys +annual +annually +annuals +annuities +annuity +annul +annulled +annulling +annulment +annulments +annuls +anoint +anointed +anointing +anoints +anomalies +anomalous +anomaly +anon +anonymity +anonymous +anonymously +anorak +anoraks +another +answer < |
