Qualification Accredited

GCSE (9–1) AND A LEVEL

Teacher guide COMPUTER SCIENCE

For first teaching in 2020

Coding challenges booklet: Coding challenges for both GCSE and A Level Version 3

www.ocr.org.uk/computerscience Contents Palindromes Logic Gate Years inaRange Number Table Kaprekar Pangrams Events calendar Caesar Cipher Quiz Maker Query Regex Tool Number Names Happy Numbers test Arithmetic Credit Card Validator Unit Converter (temperature, currency, volume) Fruit Machine Classification Thief! Speed Tracker Factorial Finder Contents A Level andGCSE(9-1)Computer Science

8 8 8 8 7 7 7 7 7 7 7 6 6 6 6 6 6 5 5 5 2 Base ofNumbers Even more Odd Sing Along Fizz Buzz Triangulate ofChance Game What’s theday? Mor-se Coding Code itup Forwards andBackwards Year Addition Merge Item Name thatNumber Word Subtraction Truth ornot! Ordering Hack-proof Fibbing Simple Life Calculator Data Entry Code ChallengesBooklet 1 1 1 1 1 1 1 1 1 1 1 1 1 10 10 10 10

3 3 3 3 2 2 2 2 1 1 1 1 1 9 9 9 ©OCR 2020 Contents Get GIFyGet withit CSV File Utility Text basedgame Such meme, many like Page Scraper Secret Ciphers Diary Dear Calculator Mortgage Is thiscard valid? Text-speak converter Mandelbrot Set Fireworks it Reverse Happy Numbers=) Complex Numbers Find thefactorial Sudoku The meaningoflife Tilers mate Prime Factorisation A Level andGCSE(9-1)Computer Science

18 17 17 17 17 16 16 16 15 15 15 15 15 14 14 14 14 14 14 14 3 R@nd0m P@ssw0rd generator Your nameis… Happy Hopper Printer problems 2 fiddy Fib onachi That’s a lotofnumber permutation String checker Checkmate Travel club Lists 20 Goldbach miceandmen Of Beautiful soup Semaphore What have ever donefor theRomans us? Silly walks Spam filter song Galaxy PiI like Code ChallengesBooklet 27 18 18 27 26 26 22 21 21 20 20 19 19 19 19 19 19 18 18 ©OCR 2020 Introduction comment, rather than being taken as comment, ratherthanbeingtaken onlyand/or bestway to‘the solve thechallenge’. have beenidentified. Where we doprovide asolution-itshouldbeusedfor discussionand realisation thateachproblem hasmany that uniquesolutionsthatwillfulfillthesuccesscriteria Discussions regarding level to approaches encouragecandidate’s are beneficialatacohort/class We donotpublishsolutions, asthere are many ways inwhich theseproblems couldbesolved. lifetime ofthespecification. to receiveThis document andlikely isanactive regular updates withchallengesthroughout the methodologies isto beencouraged, asmany problems lendthemselves to aclasssystem. For A Level: techniques containedwithinthecurrent specification. For GCSE: their codingskills. These codingchallengesprovide real problems world for teachers andstudentsto helpdevelop Introduction A Level andGCSE(9-1)Computer Science responses only need command line interfaces, andfocus responses onlyneedcommandlineinterfaces, onusingtheprogramming any created solutionsshouldhave for agraphical useinterface it.UseofOOP 4 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 3 2 1 4 Develop yourDevelop classification system for your own area ofinterest: cars;footballers; popbands; pokemon; teachers; diseasesetc. Is there abetter way to dothisthan using 101IF...ELSE...END IFs? horse, cow, sheep, pig, dog, cat,lion,tiger, whale, dolphin,seal, sparrow, penguin,ostrich, spider, ant,bee, wasp, termite, octopus, squid the following: These systems bedrawn canoften usinga “tree” outsomesimpleresearch onclassificationtrees, structure. Carry aprogram thenwrite to helptheuserdecidebetween ithave ithaveEg Does iteatmeat?Does 4 legs?Does stripes? of A simpleclassificationsystem asksaseries Yes/No at. questionsinorder ofanimalisbeinglooked to outwhattype work Classification Submit afullydetailedShowcase for your program. combination more thanonce. Design aprogram andwrite thatdisplays allthepossiblecombinationsfor any four digits numerical entered by theuser. The program shouldavoid displaying thesame A thiefhasmanagedto findoutthefour digits for anonlinePINcode, butdoesn’t sequenceneededto hack into thecorrect theaccount. know Thief! 2. 1. Extensions: the carinmph. The camerasare onemileapart. Create aprogram themto atimefor oneandthedistancebetween calculate theaverage thattakes acargoingpastspeedcamera,thetimenext speedfor Speed Tracker and recursion. The Factorial ofapositive integer, ofzero, n,isdefinedastheproduct ofthesequencen,n-1,n-2,...1andfactorial 0,isdefinedasbeing1.Solve thisusingbothloops Factorial Finder has invalid numberplates. randomised numberplates andtimes. You willthenusethecodeyou’ve already to written process thespeedlimit(70mph)andwho thislistto whoisbreaking determine Create aprogram for creating afileofdetails for vehicles exceeding thespeedlimitsetfor ofroad. asection You willneedto create asuitablefilewithtest data,including for exampleXX77 787.Produce oftheprogram thatcheckswhetheranumberplate matches apart thegiven pattern. Tell theusereitherway. thetimingsofeachcargoingpast,through numberplateSpeed camerasknow recognition. Valid numberplates are letters, two numbersandthree two letters afterwards, 5 Code ChallengesBooklet

©OCR 2020

Code Challenges A Level andGCSE(9-1)Computer Science 8 7 6 5 9 Display anexampleofyour outputhere. Find thefirsteighthappy numbers. whichdoes notinclude1. endlessly inacycle Those numbersfor whichthisprocess endsin1are happy numbers, whilethosethatdonotendin1 are unhappy numbers. with any positive integer,Starting replace thenumberby thesumofsquares ofitsdigits, andrepeat theprocess untilthenumberequals1(where itwillstay), oritloops A happy numberisdefinedby thefollowing process: Happy Numbers 2. 1. Extensions: the end. The system shouldaskthestudent’s nameandthenaskten questions. The program shouldfeed backiftheanswers are ornot,andthengenerate afinalscore correct at multiplicationanddivision. subtraction, schoolteacher wantsacomputer program ofherstudents. Generate randomquestions(2numbersonly)consistingofaddition, to skills A primary test thebasicarithmetic Arithmetic test (look into how credit cards useachecksum). Takes inacredit MasterCard, card numberfrom Express, American acommoncredit card Discoverer) vendor (Visa, andvalidates sure itto make thatitisavalidnumber Credit Card Validator theconversion.will thenmake oneanother. unitsbetween various Converts ofunitbeingentered,The userenters to thetype wantto andthenthevalue. ofunitthey convert thetype The program Unit Converter (temp, currency, volume) roll playing untilthere orkeep left. isnomoney and £5for 3Bells. The player are skulls loses£1iftwo rolled ifthree andallofhis/hermoney are skulls rolled. The player canchooseto each quitwiththewinningsafter with£1credit,The witheachgocosting20p. player theFruit starts If Machine “rolls” ofthesamesymbol, two theuserwins50p. The player wins£1for three ofthesame Write aprogram to simulate aFruit thatdisplays three Machine symbolsatrandom from Bell, Cherry, Lemon, Orange, Star, Skull. Fruit Machine able to outputtheresults in alphabeticalorder withthestudent’s highestscore firstoutofthe three. inthesetests.The teacher wantsto beableto logstudentperformance The teacher theprogram would like to store thelastthree scores for eachstudentandto be yourExtend program sothatitstores theresults somewhere. The teacher hasthree classes, soyou needto enabletheprogram to them. distinguishbetween 6 Code ChallengesBooklet

©OCR 2020

Code Challenges A Level andGCSE(9-1)Computer Science 13 12 11 10 16 15 14 Determine whether a number is a Kaprekar number or not. See numberornot.See whether anumberisKaprekar Determine Kaprekar Your either goalisto (one perline)andprints implementaprogram ofstrings aseries thattakes True (thegiven isapangram), string orFalse ifitisnot. quickbrown”The fox jumps over dog”; thelazy Pangrams 1. Extensions: overlap them. whenentering Create a menudriven program thatallows theuserto addordelete events from alistofdates andtimings, acalendar. justlike The program you shouldwarn ifany oftheevents Events calendar 2encrypts letterletter inthealphabet(wrappingZto withthe1stto key A).So 25thnext “HI” to “JK”, 20encrypts butkey “HI” to “BC”. aCaesar cipher,Implement bothencodinganddecoding. isaninteger fromThe key 1to 25. This cipherrotates theletters ofthealphabet(A to Z). The encodingreplaces each Caesar Cipher the quizzes. questionsfrom various randomly, afile, anapplicationwhichtakes picked Make andputstogether aquizfor students. Eachquizcanbedifferent to andthenreads grade akey Maker Quiz matches orflagerrors intheregular expression. This isatool thatallows box andtheninaseparate willrunthe regular theuserto text string enter enter expression aregex atext andreturn any It againstthestring pattern. Regex Query Tool 1. Extensions: of your language’s defaultboundedinteger ifthat’s type, less). Show how to spelloutanumberinEnglish. You inputsupto atleastonemillion(or your themaximumvalue own, implementationormake butyou shouldsupport canuseapre-existing Number Names Make itsothatnoneoftheevents are into theprogram hard-coded Make forCreate inputsother thanpositive zero, integers support (like negative integers, andfloating-pointnumbers). note how all26English-languageletters are usedinthesentence. http://mathworld.wolfram.com/KaprekarNumber.html 7 for more information. Code ChallengesBooklet ©OCR 2020

Code Challenges A Level andGCSE(9-1)Computer Science 18 17 20 19 Write aprogram entered thatchecksifa string by theuserisapalindrome. Apalindrome isaword like thatreads asbackwards the sameforwards “racecar” Palindromes for shouldwork thelogicIt gates OR,AND, XOR, NANDandNOR =1 Result Enter secondinput:0 Enter firstinput:1 Enter logic gate :OR For example: Write aprogram thatwillgive thestudents answer to logic gate questions Logic Gate For example, 2012hasarepeated digit, but2013 does not. Write aprogram to countthenumberyears inarangethathas arepeated digit. Years inaRange 4 |5678 3 |4567 2 |3456 1 |2345 0 |1234 ------+ |01234 For thisexample theuserhasentered “+ 4”: below forWrite atablelike aprogram theoperationfrom asymbol(+,-,*or/)andnaturalnumber(>0)makes 0to thattakes n Number Table 8 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 22 21 23 3. 2. 1. Extensions: Create a program thatwillcalculate theFibonacci to Sequence 10places. Fibbing 1. Extensions: Create aprogram thathas3simplecalculators withinit,e.g. VAT, Tax and out thatcalculation. Times table. Allow usersto choose whichcalculator wantto they useandthencarry Simple Life Calculator 4. 3. 2. 1. Extensions: Onceconfirmed, the programconfirmation. stores thesedetails;elseitclearsthemandallows input. anew Create aprogram thatretrieves themembershipdetailsfor ClimbingClub. aRock The withheadings, program arangeofdetailsandthenrepeat for shouldtake themback, Data Entry Use aanoptionmenusothattheusercanusemore thanonecalculationbefore theprogram closes Allow searching for stored users detailsfromRetrieve afile Store membershipdetailsto afile ofmore thanonemembership Allow entry Display thetotal ofallthenumbersshown Print thisinreverse order Allow theuserto specify thenumberofplacesgenerated 9 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 25 24 27 26 1. Extension: Create aprogram strings/words. two thattakes thevalues from thistoThen anASCIIvalueandsubtracts each other. thenconverts Word Subtraction 1. Extension: on screen, usingColumns for (A, B, Inputs Cetc) androws for the1’s and0’s. Create a program thenumberofinputsinalogic thatwould circuit take outthenumberofoutputlinesare andworks neededfor thetruthtable. Have itdraw thetruth table Truth ornot 2. 1. Extension: theminto ascendingordescendingorder,Create of10numbersandthensorts aprogram thatallows entry basedonuserinput. Ordering b. a. 3. 2. 1. Extensions: the password before allowing it. Create aprogram password documentifthecorrect thatwillonlyopenatext isentered. andpasswordThe usershouldchoosetheusername firstanditshouldalsoverify Hack-proof Fill intherest ofthetruthtableifyou can! Repeat Extension 1,butincludethesentence structure Extension Repeat The usercaninputaword into alphabeticalorder. orstring, thestring anditarranges would beshown E.g. as Rabbit My “abbimty “. (Punctuation placementisnotessential) Also add a function thatremovesAlso addafunction any inthesecondword characters thatoccurinthe firstword. E.g. Fish and Tin, would return “Fsh” and “Tn” Verify thatthepassword given by theusermatches: Create arandompassword thatcontainsatleastalowercase, uppercase inlength ofatleast8characters andspecialcharacter Create arandompassword firstasasuggested firstofatleast8characters password The limits in Extension 2aboveThe limitsinExtension 1aboveThe limitsinExtension 10 Code ChallengesBooklet ©OCR 2020

Code Challenges A Level andGCSE(9-1)Computer Science 30 29 28 32 31 3. 2. 1. Extension: Create a program thatauserenters. thatadds25to ofastring thevalueofeach character shouldbesavedThis string new andoutput. Code itup Create a program thatisableto ifaninputisthesameasreverse detect ofthesameinput–i.e. aPalindrome Forwards andBackwards 1. Extension: Create aprogram thatacceptsayear intheformat ####,e.g. 2015. The program thenaddseachdigit oftheyear together andoutputstheanswer. E.g. 2015becomestheoutput8. Year Addition 2. 1. Extension: Create aprogram thatwillcompare shoppinglistsfrom two A”“Week and B”.“Week willreturn any uniqueitems containedonthelist. It Merge Item 1. Extensions: a phonenumberwith “letters” into onethatonlycontainsdigits. Telephone have often letters Keypads associated witheachnumber. This meansthat01411172556couldbestored as0141-CAT-DOOR. Create aprogram thatcanconvert Name that Number Develop thistoDevelop 4 Weeks ofshoppinganhighlightthetop 3mostpopularitems lists,Append thetwo withnorepetition Develop yourDevelop program to thendecodeastring, basedonthecodedvaluethatend userenters yourDevelop program to allow theuserto codedby enter (e.g. wantthe string thenumberthey 12) yourDevelop program to includeaconversion from a ‘coded’ string backto anormal string Can you develop your are program allowed? sothatonlywords inthedictionary Develop thissothattheusercanguessaninteger theMODdivisionis Develop value. If “0” score they apoint,ifitisn’t canguessagain,upto they 3attempts intotal 11 Code ChallengesBooklet

©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 35 34 33 36 1. Extension: Create outifthesesidesform a program thenworks atriangle, andifso, (e.g. oftriangle thataccepts3sidesofatriangle. It whattype Scalene, Isosceles, Right-Angle….) Triangulate 4. of currency 3. 2. 1. Extension: shouldbecateredCombinations ofthewinscenarios for.. e.g. 20wins2x3bonus=6xtheirmoney. Create aprogram thatallows theuserto guessanumber. Arandomnumberisgenerated. theguess==randomnumberthenuserwinsandgetsapay-out. If thenumberisbelow geta2xbonus. 5they If back. get 5xtheirmoney it’sA usercanbetonany it’s numberfrom If it’s If 0to numberthey 30.If aprime back. get3xtheirmoney amultipleof10they back. 2xtheirmoney aneven numberthey ofChanceGame Hint: How doleapyears affectthisprogram? Design aprogram 3inputs, to take onefor day, onefor monthandonefor year. your Get program to day, validate ifthisisanactual and, ifitis, outputtheday oftheweek itis! What’s theday? 1. Extension: spaceforUse anormal eachcharacter. gapsbetween Create aprogram thatallows you to code, andencodeitinto enter Morse astring using ‘ . ‘ and ‘ - words‘ notation.Spacesbetween shouldbereplaced withthe “|” (pipe)character. CodingMor-se Develop yourDevelop program to allow multiplebetsondifferent numbers yourDevelop program to cannotenter validationsothatthey finallyincorporate into anegative aboutofcashever, 1and10units andthatabetshouldbebetween yourDevelop program to store theuser’s current balanceandstop themfrom have bettingifthey left nomoney yourDevelop program to allow auserto enter wantto theamountthey placefor outtheresulting thatbet,andwork pay-out yourDevelop program to translate from to alphanumeric, Morse usingthestandards above Develop yourDevelop program to andanangle, allow 2sidesofatriangle to out thelengthofmissingside work 12 Code ChallengesBooklet ©OCR 2020

Code Challenges A Level andGCSE(9-1)Computer Science 38 37 40 39 1. Extension: numberintoCreate itshexadecimalequivalent. aprogram adenary thatconverts ofNumbers Base 1. Extension: numbers withinthearray. to thenechos theoriginal andthemodifiedarray array screen. E.g. It 1,2,3,4,5,6,7,8,9,10would anarray beoutput1,3,5,7,9,2,4,6,8,10. Create a program thatacceptsandrandominteger (atleast10integers) array andorders themfirstlyby size, (smallto large), andthen putsalltheeven numbersAFTERtheodd Even more Odd 1. Extension: Create aprogram to thesong thelyrics thatprints ‘10 green bottles’ inasfew linesofcodeaspossible. Sing Along • • • 2. 1. Extension: • • • Create aprogram thatreplicates thefamous gameFizz Buzz. The program aninput,e.g. willtake outthelistofFizz 20,andthenprint Buzzupto andincludingthatnumber, where: Fizz Buzz Any multipleofboth3and5isreplaced by theword ‘FizzBuzz’ Any multipleof5isreplaced by theword ‘Buzz’ Any multipleof3isreplaced by theword ‘Fizz’ Allow thenumberinto, theuserto wantto specifythebasethatthey convert usinganinteger, e.g. 16for Hexadecimal thisprogramDevelop numberanditwillcountdown sothatyou from canenter any there starting Allow theuserto enter wantto thebasenumbersthatthey replace words with.E.g. 2and3,whichwould mean: any numberwiththewordReplace prime ‘OOPS!’ Develop yourDevelop program to allow inputaswell, Character andthesecomebefore theintegers, andare listed inreverse alphabeticalorder Any multipleofboth2and3isreplaced by theword ‘FizzBuzz’ Any multipleof3isreplaced by theword ‘Buzz’ Any multipleof2isreplaced by theword ‘Fizz’ 13 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 43 42 41 47 46 45 44 while those thatdonot endin1are unhappy numbers. Have the programme findthe first8happy numbers. until thenumber equals1(where whichdoesnot include 1. itwillstay), oritloopsendlesslyinacycle Those numbersfor whichthisprocess ends in1are happy numbers, A happy numberisdefinedby the following withany process. positive integer, Starting replace thenumberby thesum ofthesquares ofitsdigits, andrepeat theprocess Happy Numbers=) with pairsoftheseoperations.) Print theresults for eachoperationtested to screen. Have theprogramme show addition,multiplication,negation,andinversion anddivisionoperationscanbemade ofcomplexnumbersinseparate functions.(Subtraction Complex Numbers and recursion. The Factorial ofapositive integer, ofzero, n,isdefinedastheproduct ofthesequencen,n-1,n-2,...1andfactorial 0,isdefinedasbeing 1.Solve thisusingboth loops Find thefactorial Have theprogram solve ( aSudoku Sudoku Let the userchangecellswhiletheanimationisrunning • Extension: Have theprogram ananimationofthegamelife make ( The meaningoflife • • Extension: (per tileormetre Have theuserenter the Width andLength ofthefloorandhave theprogram calculate thetotal to costoftilesitwould cover take afloorplanusingcostentered by theuser Tilers mate • Extension: Have theuserenter anumberandfindallPrime Factors (ifthere are any) anddisplay them. Prime Factorisation Have theprogramme into accountthecostofgrout take andlabourto give acustomer aquote withandwithout VAT. Have theprogramme offer different oftileswithdifferent types costsandtell theusercost. Have theprogram for one. numbersuntiltheuserchoosesto thenext stop findprime asking Let theusersetupinitialstate 2 ). https://en.wikipedia.org/wiki/Sudoku https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life ). 14 ). Code ChallengesBooklet

©OCR 2020

Code Challenges A Level andGCSE(9-1)Computer Science 50 49 48 52 51 ***Don’t useany real card details*** it isavalidnumber(lookinto how credit cards useachecksum). Have theprogramme inacredit MasterCard, take card numberfrom Express, American acommoncredit card Discoverer) vendor (Visa, andvalidates sure itto make that Is thiscard valid? Allow inthedictionary theuserto entries add new • Extension: andhave theprogram inputfrom convert upatext-speak text-speak to toSet English dictionary English.(“lol” to outloud”“laugh etc) Text-speak converter • • • Extension: Draw aMandelbrot set( Mandelbrot Set • Extension: ananimationofafirework display,Make withrockets, wheelsetc. Catherine Fireworks • • Extension: Have theprogramme allow auserto andthentheprogramme enter sometext willreverse itbackto thescreen. itandprint Reverse it Read in the text from inthe text afile Read Let theuserspecifynumber, colour, timingandlocationoffireworks. Have theprogramme e.g isapalindrome checkifthetext asitisbackwards (itisthesameforwards “racecar” or “hannah”). Have theprogramme countthevowels theseto screen. andconsonantsprint Allow theuserto zoom in With ananimation colour In http://mathworld.wolfram.com/MandelbrotSet.html ). 15 Code ChallengesBooklet

©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 54 53 55 • • • Extension: The ciphercanignore numbers, symbolsandwhitespace. • • • Have messagesusingoneofthefollowing theprogramme ciphers: encrypt Secret Ciphers • • • Extension: ( shouldadd timestampstoHave allentries. Could alsobemadeinto entries. theprogramme It ashoutbox allow peopleto diary addcommentsorwrite Dear Diary • • Extension: back theloan. Have theprogramme calculate over themonthlypayments atagiven terms ofafixed given interest mortgage term Nth rate. Alsofigure theuserto outhowpay longitwilltake Calculator Mortgage https://en.wikipedia.org/wiki/Shoutbox Ceasar Vernan Vigenere Have externally. theprogramme entries save thediary Embed your programme inawebpage. Add date stampsto eachpost. to dealwithoverAdd payments infunctionality atagiven %eachmonth. (Monthly,Add anoptionfor thecompoundinginterval users to select Weekly, Daily, Continually). Have messageto theprogramme afriend. emailtheencrypted Have messagesalso. theprogramme decrypt Create for separate functions eachCipherandallow theuserto choosewhichoneto use. ). 16

Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 58 57 56 59 Have theprogramme read basedonachosenfield. a.CSVfileofrecords, algorithms them backto them,andthenwrite thefile. Allow sorting theuserto sort choosevarious CSV File Utility • • Extension: rooms.the various The usershouldhave atleast2choicesperroom. You first! willwantto planthisonewithaflowchart Have theprogramme Zork. Create theusersnameanduseitto basedgamelike tell atext take thestory. Have theprogramme allow anon-linearprogression through Text basedgame • • Extension: Have theprogramme display ablankmemetemplate ( Such meme, many like • • Extension: Have theprogramme to asite connect andpullsoutallthelinks, orimages, andsave themto alist. Page Scraper Have suggestionsaboutthedifferent memesonhow to themproperly write Display thefinishedmemesin awebpage Have itputtheresults into aneasilysearchable indexfile. Organize theindexed content anddon’t allow duplicates. Add an inventory system so you must collect a key to get through a certain dooretc. to getthroughAdd system a key acertain soyou aninventory mustcollect Have eachroom asaseparate function. https://imgflip.com/memetemplates 17 ) andallow theuserto (don’t addtheirown text forget asthefont). to useImpact Code ChallengesBooklet

©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 61 60 64 63 62 • Extension: filledwith stars. nightsky toUse graphics draw andrandom functions animaginary song Galaxy Have theprogramme calculate pito atleast30decimalplaces. I like Pi • • Extension: Have theprogramme create randomstrong passwords mixingupperandlower case, symbolsandnumbers. R@nd0m P@ssw0rd generator • Extension: Your nameis(blank),you are (blank)years old, andyou are inform (blank). Have theprogramme askfor your name, ageandform. Have ittell themtheinformation backintheformat: Your nameis… • • • • • Extension: Have theprogramme smallvideofilesinto GIFs. convert Have alookat: GIFyGet withit Add the milky way Add themilky Have thepasswords stored file inanexternal Have thepassword alsouseASCIIcharacters Have theprogramme store file thisinformation inanexternal Remove thebackground Add sometext your GIFtimesymmetrical Make Freeze aregion Crop thevideo http://zulko.github.io/blog/2014/01/23/making-animated-gifs-from-video-files-with-python/ 18 Code ChallengesBooklet for atutorial. ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 68 67 66 65 70 69 • Extension: number,Once theuserguessescorrect thegameisover. throughout trackofthenumber ofguessestheusermakes thegameandtell theuseratend. Keep digit inthewrong theuserguessedcorrectly placeisa “man” aguess, timetheusermakes tell themhow many Every “mice” and “men” have. they number. generate a4-digit Randomly Ask number. theuserto guessa4-digit For place, digit have inthecorrect they thatthe userguessedcorrectly a every “mouse”. For every Have theprogramme allow auserto play the “mice andmen” game. this: The like gameworks mice andmen Of This may help: ( titlesontheBBCNews outalistofallthearticle to print andrequestsUse theBeautifulSoup Pythonpackages soup Beautiful intoHave ananimationofitconverted semaphore andmake theuserenter (https://en.wikipedia.org/wiki/Flag_semaphore). sometext Semaphore Have numerals. itoutinRoman theuserenter anumberandprint What have ever theRomans donefor us? • • Extension: Draw arandomwalkwhere eachstep ofequallengthiseitherup, withequalprobability. orleft down, right https://en.wikipedia.org/wiki/Random_walk. See Silly walks • Extension: Take alistofdishesfrom amenuandadd “spam” to them.See Spam filter Deal with Deal “mice” and “mouse” and “man” and “men ” properly. Fill (http://mathworld.wolfram.com/Plane-FillingFunction.html) your screen withaspacefillingcurve BrownianModel motion( withaddingspamatthebeginning,Experiment endandallplacesin-between http://www.pythonforbeginners.com/beautifulsoup/beautifulsoup-4-python https://en.wikipedia.org/wiki/Brownian_motion https://en.wikipedia.org/wiki/Spam_(Monty_Python) ) in2dimensionswithseveral particles 19

http://www.bbc.co.uk/news . ) Code ChallengesBooklet ©OCR 2020

Code Challenges A Level andGCSE(9-1)Computer Science 73 72 71 expenses and works out the minimum amount of money that must change hands in order for everybody to thatmustchangehandsinorder outtheminimumamountofmoney expenses andworks have for paid the sameamount(within1%). everybody andthemembercostisshared(such astaxis, etc) thetrip after to thegroup. traintickets within1%between Create aprogramme thatcomputes thenetcostfrom alistof A group ofpeopleare memberofatravel club. The group happen,soallexpensesare expenseasthey collated shares to share expensesequallybutitisnotpractical every Travel club thelist oflistsaccordingand create to thelengthofsublists. alistoflists. Sort Create agiven anelementatagiven elementsfrom alistcontainingallintegers numberofrandomlyselected positioninto withinagiven alist alist.Extract range. Insert Lists Write apredicate numbersthatsumupto to agiven prime findthetwo even integer. large. upto thathasnotbeenproved very confirmed hasbeennumerically inthegeneralcase. to becorrect theory It Goldbach’s positive innumber even numbergreater isoneofthemostfamousfacts conjecturesays numbers. thatevery prime than2isthesumoftwo Example:28=5+23.It Goldbach 20 Code ChallengesBooklet

©OCR 2020

Code Challenges A Level andGCSE(9-1)Computer Science 74 75 Given two strings Given strings two String permutation where from dstandsfor 1. thegamenumberstarting isincheck. #d: noking Game isincheck. #d: blackking Game isincheck. #d: white king Game For eachboard configurationread you mustoutputoneofthefollowing answers: andoneblackking. onewhite one, king willcontainexactly empty boardempty consisting onlyof``.’’ characters, whichshouldnotbeprocessed. There eachpairofboard linebetween configurations. willbeanempty Allboards, except for the lowercase letters represent thepiecesasdefinedabove. There are willbenoinvalid and no configurationswhere incheck. characters bothkings You mustread untilyou findan numberofboard each.A``.’’ configurationsintheinput,eachconsistingofeightlinescharacters There willbeanarbitrary square, denotes anempty whileupper- and Movement examplesare shown below, grey piecesindicate thepositionswhere thepiececancapture anotherpiece: Create aprogramme isincheckagiven thatcheckswhetheraKing chessgameconfiguration. Checkmate checker Pawn x and y , print the longest string aof letters such thatthere thelongeststring ofathatissubsequence , print isapermutation Castle Bishop 21 Queen x andthere ofathatissubsequence isapermutation King Knight Code ChallengesBooklet ©OCR 2020 y . Code Challenges A Level andGCSE(9-1)Computer Science 76 17423706905851860660448207621209813287860733969412 45876576172410976447339110607218265236877223636045 36123272525000296071075082563815656710885258350721 53282654108756828443191190634694037855217779295145 54370070576826684624621495650076471787294438377604 71693888707715466499115593487603532921714970056938 86515506006295864861532075273371959191420517255829 35398664372827112653829987240784473053190104293586 80181199384826282014278194139940567587151170094390 58203565325359399008402633568948830189458628227828 92575867718337217661963751590579239728245598838407 64906352462741904929101432445813822663347944758178 62176457141856560629502157223196586755079324193331 70386486105843025439939619828917593665686757934951 47451445736001306439091167216856844588711603153276 44274228917432520321923589422876796487670272189318 28112879812849979408065481931592621691275889832738 89261670696623633820136378418383684178734361726757 23067588207539346171171980310421047513778063246676 91942213363574161572522430563301811072406154908250 74324986199524741059474233309513058123726617309629 46376937677490009712648124896970078050417018260538 37107287533902102798797998220837590246510135740250 Work outthefirstten digits numbers. ofthesumfollowing 50-digit one-hundred That’s alotofnumber 22 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 95548255300263520781532296796249481641953868218774 67720186971698544312419572409913959008952310058822 63783299490636259666498587618221225225512486764533 11487696932154902810424020138335124462181441773470 23053081172816430487623791969842487255036638784583 34413065578016127815921815005561868836468420090470 91430288197103288597806669760892938638285025333403 24074486908231174977792365466257246923322810917141 36270218540497705585629946580636237993140746255962 25267680276078003013678680992525463401061632866526 88902802571733229619176668713819931811048770190271 94953759765105305946966067683156574377167401875275 35829035317434717326932123578154982629742552737307 65378607361501080857009149939512557028198746004375 41052684708299085211399427365734116182760315001271 69793950679652694742597709739166693763042633987085 59959406895756536782107074926966537676326235447210 87086987551392711854517078544161852424320693150332 48403098129077791799088218795327364475675590848030 16726320100436897842553539920931837441497806860984 78182833757993103614740356856449095527097864797581 80386287592878490201521685554828717201219257766954 18336384825330154686196124348767681297534375946515 55037687525678773091862540744969844508330393682126 15732444386908125794514089057706229429197107928209 62467221648435076201727918039944693004732956340691 51934325451728388641918047049293215058642563049483 81142660418086830619328460811191061556940512689692 23 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 10848802521674670883215120185883543223812876952786 87783646182799346313767754307809363333018982642090 97142617910342598647204516893989422179826088076852 76841822524674417161514036427982273348055556214818 73267460800591547471830798392868535206946944540724 99518671430235219628894890102423325116913619626622 32924185707147349566916674687634660915035914677504 62177842752192623401942399639168044983993173312731 75506164965184775180738168837861091527357929701337 32238195734329339946437501907836945765883352399886 55121603546981200581762165212827652751691296897789 42846280183517070527831839425882145521227251250327 97623331044818386269515456334926366572897563400500 82959174767140363198008187129011875491310547126581 11306739708304724483816533873502340845647058077308 86188088225875314529584099251203829009407770775672 23189706772547915061505504953922979530901129967519 62467957194401269043877107275048102390895523597457 41698116222072977186158236678424689157993532961922 29746152185502371307642255121183693803580388584903 40957953066405232632538044100059654939159879593635 34829543829199918180278916522431027392251122869539 38298203783031473527721580348144513491373226651381 18495701454879288984856827726077713721403798879715 29798860272258331913126375147341994889534765745501 23701913275725675285653248258265463092207058596522 37774242535411291684276865538926205024910326572967 76085327132285723110424803456124867697064507995236 24 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 53503534226472524250874054075591789781264330331690 20849603980134001723930671666823555245252804609722 72107838435069186155435662884062257473692284509516 77158542502016545090413245809786882778948721859617 22918802058777319719839450180888072429661980811197 82616570773948327592232845941706525094512325230608 81234880673210146739058568557934581403627822703280 41503128880339536053299340368006977710650566631954 44889911501440648020369068063960672322193204149535 40789923115535562561142322423255033685442488917353 15368713711936614952811305876380278410754449733078 78639167021187492431995700641917969777599028300699 94809377245048795150954100921645863754710598436791 16730939319872750275468906903707539413042652315011 64913982680032973156037120041377903785566085089252 66024396409905389607120198219976047599490197230297 85786944089552990653640447425576083659976645795096 60661826293682836764744779239180335110989069790714 66627891981488087797941876876144230030984490851411 62184073572399794223406235393808339651327408011116 71329612474782464538636993009049310363619763878039 25 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 77 78 Write aprogramme out allthedifferent thatworks ways £2.50canbemadeusingany numberofcoins. 1×£1 +2×50p2×20p1×5p +1×2p3×1p £2.50inthefollowing ispossibleto make way: It 2 fiddy inthe FibonacciWhat istheindexoffirstterm sequenceto contain1000digits? The to F12,isthefirstterm 12thterm, containthree digits. F12 =144 F11 =89 F10 =55 F9 =34 F8 =21 F7 =13 F6 =8 F5 =5 F4 =3 F3 =2 F2 =1 F1 =1 willbe: Hence thefirst12terms Fn =Fn−1 +Fn−2, where F1=1andF21. The Fibonacci sequence isdefinedby therecurrence relation: Fib onachi 26 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science 79 80 determine whethereachofanumbersequencesishappydetermine hopper. is ahappy hopperbecausetheabsolute differences are 3,2,and1,respectively. The definitionimpliesthatany sequenceofasingleinteger isahappy hopper. Write aprogram to A sequenceofn>0integers iscalledahappy hopperiftheabsolute valuesofthedifferences onallpossiblevalues1through successive between elementstake n-1.E.g1423 Happy Hopper he haswhatneedsandany remaining sheetsare always placedbackintheenvelope. itislarger, itisofsize A5,heusesit.If at random.If herepeats the ‘cut-in-half’ procedure until At thebeginning from ofeachsubsequentbatch, hetakes theenvelope onesheetofpaper All theunusedsheetsare placedbackintheenvelope. the firstbatch oftheweek. in halfto sheetsofsize gettwo A3andsoonuntilheobtainstheA5-size sheetneededfor He proceeds to cutitinhalf, sheetsofsize thusgetting two A2. Then hecutsoneofthem the specialpaperwithsize A1. morning, Monday theforemanEvery envelope, opensanew containingalarge sheetof special colour-proofing paperofsize A5. week andeachbatch requires every asheetof shopruns16batches (jobs) A printing Printer problems 27

Code ChallengesBooklet ©OCR 2020 Code Challenges License 1.2 unless otherwise noted. License 1.2unlessotherwise All thelinksbelow leadto Computer Science Alphabet A Level andGCSE(9-1)Computer Science A E D B Enumerations programEmpty Associative array/Iteration Associative array/Creation Assertions Arrays Arithmetic/Integer acallbackto anarray type Abstract Create a two-dimensional array atruntime array Create atwo-dimensional Count inoctal Copy astring Concurrent computing Compound datatype Comments Command-line arguments Collections Classes codes Character method Call anobject Boolean values digits Binary aprimitive datatype Define Constants rosettacode.org andhave ofprogramming achallengeandthensolutionfor thevastmajority languages. Content isavailable underGNUFree Documentation http://rosettacode.org/wiki/Enumerations http://rosettacode.org/wiki/Empty_program http://rosettacode.org/wiki/Associative_array/Iteration http://rosettacode.org/wiki/Associative_array/Creation http://rosettacode.org/wiki/Assertions http://rosettacode.org/wiki/Arrays http://rosettacode.org/wiki/Arithmetic/Integer http://rosettacode.org/wiki/Apply_a_callback_to_an_array http://rosettacode.org/wiki/Abstract_type http://rosettacode.org/wiki/Define_a_primitive_data_type http://rosettacode.org/wiki/Enforced_immutability http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime http://rosettacode.org/wiki/Count_in_octal http://rosettacode.org/wiki/Copy_a_string http://rosettacode.org/wiki/Concurrent_computing http://rosettacode.org/wiki/Compound_data_type http://rosettacode.org/wiki/Comments http://rosettacode.org/wiki/Command-line_arguments http://rosettacode.org/wiki/Collections http://rosettacode.org/wiki/Classes http://rosettacode.org/wiki/Character_codes http://rosettacode.org/wiki/Call_an_object_method http://rosettacode.org/wiki/Boolean_values http://rosettacode.org/wiki/Binary_digits 28

Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science I H G F O N M L Optional parameters Null object Native shebang Named parameters shebang Multiline Modulinos allocation Memory Literals/String Literals/Integer Literals/Floating point List comprehensions programmingInteractive loop Input Input/user Inheritance/Single Inheritance/Multiple Infinity afile Include conversion type Implicit Hello world/Text Hello world/Standard error omission Hello world/Newline Hello world/Graphical Hash from arrays two swap Generic Function definition Formatted output numeric Find limitofrecursion Filter Factors ofaninteger http://rosettacode.org/wiki/Function_definition http://rosettacode.org/wiki/Formatted_numeric_output http://rosettacode.org/wiki/Find_limit_of_recursion http://rosettacode.org/wiki/Filter http://rosettacode.org/wiki/Factors_of_an_integer http://rosettacode.org/wiki/Optional_parameters http://rosettacode.org/wiki/Null_object http://rosettacode.org/wiki/Native_shebang http://rosettacode.org/wiki/Named_parameters http://rosettacode.org/wiki/Multiline_shebang http://rosettacode.org/wiki/Modulinos http://rosettacode.org/wiki/Memory_allocation http://rosettacode.org/wiki/Literals/String http://rosettacode.org/wiki/Literals/Integer http://rosettacode.org/wiki/Literals/Floating_point http://rosettacode.org/wiki/List_comprehensions http://rosettacode.org/wiki/Interactive_programming http://rosettacode.org/wiki/Input_loop http://rosettacode.org/wiki/User_input/Text http://rosettacode.org/wiki/Inheritance/Single http://rosettacode.org/wiki/Inheritance/Multiple http://rosettacode.org/wiki/Infinity http://rosettacode.org/wiki/Include_a_file http://rosettacode.org/wiki/Implicit_type_conversion http://rosettacode.org/wiki/Hello_world/Text http://rosettacode.org/wiki/Hello_world/Standard_error http://rosettacode.org/wiki/Hello_world/Newline_omission http://rosettacode.org/wiki/Hello_world/Graphical http://rosettacode.org/wiki/Hash_from_two_arrays http://rosettacode.org/wiki/Generic_swap 29 Code ChallengesBooklet ©OCR 2020 Code Challenges A Level andGCSE(9-1)Computer Science V U S R P T Variadic function Variables User input/Text User input/Graphical Topic variable Take notes onthecommandline Substring commentsfrom Strip astring prependString length String (included) interpolation String concatenation String comparison String append String from amainroutine Start Special variables Special characters Sleep Simple windowed application Scope/Function namesandlabels modifiers Scope multiplevalues Return constantsandfunctions Real numbers Random Program termination Program name Polymorphism Pick randomelement Parse command-linearguments Parametric polymorphism http://rosettacode.org/wiki/Variadic_function http://rosettacode.org/wiki/Variables http://rosettacode.org/wiki/User_input/Text http://rosettacode.org/wiki/User_input/Graphical http://rosettacode.org/wiki/Topic_variable http://rosettacode.org/wiki/Program_name http://rosettacode.org/wiki/Polymorphism http://rosettacode.org/wiki/Pick_random_element http://rosettacode.org/wiki/Parse_command-line_arguments http://rosettacode.org/wiki/Parametric_polymorphism http://rosettacode.org/wiki/Take_notes_on_the_command_line http://rosettacode.org/wiki/Substring http://rosettacode.org/wiki/Strip_comments_from_a_string http://rosettacode.org/wiki/String_prepend http://rosettacode.org/wiki/String_length http://rosettacode.org/wiki/String_interpolation_(included) http://rosettacode.org/wiki/String_concatenation http://rosettacode.org/wiki/String_comparison http://rosettacode.org/wiki/String_append http://rosettacode.org/wiki/Start_from_a_main_routine http://rosettacode.org/wiki/Special_variables http://rosettacode.org/wiki/Special_characters http://rosettacode.org/wiki/Sleep http://rosettacode.org/wiki/Simple_windowed_application http://rosettacode.org/wiki/Scope/Function_names_and_labels http://rosettacode.org/wiki/Scope_modifiers http://rosettacode.org/wiki/Return_multiple_values http://rosettacode.org/wiki/Real_constants_and_functions http://rosettacode.org/wiki/Random_numbers http://rosettacode.org/wiki/Program_termination 30 Code ChallengesBooklet ©OCR 2020 OCR Resources: the small print Would you prefer a Need to get in touch? OCR’s resources are provided to support the delivery of OCR Word version? If you ever have any questions about qualifications, but in no way constitute an endorsed teaching method that is required by OCR. Whilst every effort is made Did you know that you can save OCR qualifications or services (including to ensure the accuracy of the content, OCR cannot be held this pdf as a Word file using Acrobat administration, logistics and teaching) responsible for any errors or omissions within these resources. We update our resources on a regular basis, so please check the Professional? please feel free to get in touch with our OCR website to ensure you have the most up to date version. Simply click on File > Export to and Customer Support Centre. select Microsoft Word This resource may be freely copied and distributed, as long as General qualifications the OCR logo and this small print remain intact and OCR is (If you have opened this PDF in your browser you will acknowledged as the originator of this work. Telephone 01223 553998 need to save it first. Simply right click anywhere on the Facsimile 01223 552627 Our documents are updated over time. Whilst every effort is made page and select Save as . . . to save the PDF. Then open Email [email protected] to check all documents, there may be contradictions between the PDF in Acrobat Professional.) published support and the specification, therefore please use the information on the latest specification at all times. Where changes www.ocr.org.uk are made to specifications these will be indicated within the If you do not have access to Acrobat Professional there document, there will be a new version number indicated, and a summary of the changes. If you do notice a discrepancy between are a number of free applications available that will also the specification and a resource please contact us at: convert PDF to Word (search for pdf to word converter). [email protected]. Did you know? Did you OCR acknowledges the use of the following content: N/A

Whether you already offer OCR qualifications, are new to OCR, or are considering switching from your current provider/awarding organisation, you can request more information by completing the Expression of Interest form which can be found here: www.ocr.org.uk/expression-of-interest

Please get in touch if you want to discuss the accessibility of resources we offer to support delivery of our qualifications: [email protected]

Looking for a resource? OCR is part of Cambridge Assessment, a department of the University of Cambridge. For staff training purposes and as part of our quality assurance There is now a quick and easy search tool to help find free resources programme your call may be recorded or monitored. for your qualification: www.ocr.org.uk/i-want-to/find-resources/ © OCR 2020 Oxford Cambridge and RSA Examinations is a Company Limited by Guarantee. Registered in England. Registered office The Triangle Building, Shaftesbury Road, Cambridge, CB2 8EA. Registered company number 3484466. OCR is an exempt charity.