title: Words hidden in my phone number

text:
# Question
Title: Words hidden in my phone number
Telephones in the United States (and perhaps some other places) have letters associated with some of the numbers.

```
2 = A, B, C
3 = D, E, F
4 = G, H, I
5 = J, K, L
6 = M, N, O
7 = P, Q, R, S
8 = T, U, V
9 = W, X, Y, Z

```

No letters are associated with the number 0 or 1.

Your challenge: Given any phone number in seven-digit or ten-digit format, return English words or phrases into which it could be translated using the code above. Spaces do not matter.

So, for example 873-5377 can be translated to “useless” or “trek-err” and possibly a few others depending on your words list.

For the purposes of this contest,

1. All digits in the phone number must be used and must be translated into letters. This means that phone numbers containing 0s or 1s can not be translated.
2. If your operating system or programming environment has a built-in words list (/usr/share/dict/words or the equivalent), go ahead and use it. Otherwise, you can assume that a word list has been downloaded to a convenient directory. However, (a) no-preprocessing of the dictionary to limit it to seven and ten letter words or anything like that, and (b) you have to open the dictionary and load the words yourself; you can’t just pass a variable that contains a list of words.
3. If your dictionary includes proper nouns, it’s OK to have them in your output.
4. You can not assume that your input is an integer. The number 213-867-5309 might be input as (213) 867-5409 or 2138675309. Strip all non-numerical characters and make sure what’s left is a seven or ten-digit integer.
5. Your answer can be a function or a complete program, but no snippets.

FOR EXTRA CREDIT

6. You may implement a version of the code that replaces rule 1 with a more forgiving test — you may leave up to 2 numbers as numbers while changing all the other numbers to words. If you choose this path, the code must complete a comprehensive search and not do something trivial like leaving the first two numbers as numbers while doing word substitution on the rest. Obviously in this variation, phone numbers with up to two 0s and 1s may be translated.

Using the same test number as above, rule 6 gives us the answers "us-elf-77", "us-ekes-7", and others in addition to the answers above.

TEST NUMBERS

Show us what you get for 868-454-6523 and 323-454-6503.

SCORING

Shortest code wins, but if you’ve implemented rule 6 you can cut your length in half. I also plan to call out interesting solutions or solutions from verbose languages that might have won if their command names were shorter.

# Answer
# 05AB1E, 207 bytes

```
þ"! ! ABC DEF GHI JKL MNO PQRS TUV WXYZ"S#sSèU
"€‚ƒ„…†‡ˆ‰Š‹ŒŽ•–—™š›œžŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîï"©vyV®vYy«"“ÿ“".Vu}})
ʒg¹þgQ}
ʒ´vXNèyåˆ}¯P}
¹þg7Q¹þgTQ&i´¯}

```

Try it online!

**(1)** The first line of the code, will replace each number in the input with the corresponding set of possible letters.

```
þ                                              # Only digits of input.
 "! ! ABC DEF GHI JKL MNO PQRS TUV WXYZ"       # Push keypad letters.
                                        S#     # Split into list and on spaces.
                                          sS   # Split input into digits.
                                            èU # Push indexes of digits and store in X.

```

**(2)** The second line of the code, will push every possible dictionary word that is stored in 05AB1E. It accomplishes this by pushing all pairings of the dictionary encrypted characters and converting them to their dictionary stored equivalents. There are 100 unique dictionary characters, and 100\*100 unique pairs of them. This means we are getting access to a total of 10,000 words from the 05AB1E dictionary.

**(3)** The third line of the code, will filter the dictionary by the length of the number of digits in the input.

**(4)** The fourth line of the code, will filter again the words from the dictionary which match the filter of possible letters outlined by line #1.

**(5)** The final line of the code, will simply return an empty array provided that the input was not 7 or 10 digits long after parsing.

---

Using no external libraries/files, this code can detect any word that is in the 05AB1E dictionary. More specifically, if the input is limited to 7 characters the following list:

```
["ABILITY", "ABRAHAM", "ABSENCE", "ACADEMY", "ACCEPTS", "ACCOUNT", "ACCUSED", "ACHIEVE", "ACQUIRE", "ACROBAT", "ACRYLIC", "ACTIONS", "ACTRESS", "ADAPTED", "ADAPTER", "ADAPTOR", "ADDRESS", "ADOPTED", "ADVANCE", "ADVERSE", "ADVISED", "ADVISOR", "AFFAIRS", "AFFECTS", "AFRICAN", "AGAINST", "AIRFARE", "AIRLINE", "AIRPORT", "ALABAMA", "ALBANIA", "ALBERTA", "ALCOHOL", "ALGEBRA", "ALGERIA", "ALLEGED", "ALLERGY", "ALLOWED", "ALREADY", "ALTERED", "AMATEUR", "AMAZING", "AMBIENT", "AMENDED", "AMERICA", "AMONGST", "AMOUNTS", "AMPLAND", "ANAHEIM", "ANALYST", "ANALYZE", "ANATOMY", "ANCIENT", "ANDORRA", "ANDREAS", "ANDREWS", "ANGELES", "ANIMALS", "ANOTHER", "ANSWERS", "ANTENNA", "ANTHONY", "ANTIGUA", "ANTIQUE", "ANTONIO", "ANXIETY", "ANYBODY", "ANYMORE", "ANYTIME", "APPAREL", "APPEALS", "APPEARS", "APPLIED", "APPLIES", "APPROVE", "AQUATIC", "ARCHIVE", "ARISING", "ARIZONA", "ARMENIA", "ARRANGE", "ARRIVAL", "ARRIVED", "ARRIVES", "ARTICLE", "ARTISTS", "ARTWORK", "ASPECTS", "ASSAULT", "ASSISTS", "ASSUMED", "ASSUMES", "ASSURED", "ATLANTA", "ATTACKS", "ATTEMPT", "ATTRACT", "AUCTION", "AUDITOR", "AUSTRIA", "AUTHORS", "AVERAGE", "AWARDED", "AWESOME", "BACKING", "BAGHDAD", "BAHAMAS", "BAHRAIN", "BALANCE", "BALLOON", "BANGBUS", "BANGKOK", "BANKING", "BANNERS", "BAPTIST", "BARBARA", "BARGAIN", "BARRIER", "BASKETS", "BATTERY", "BEACHES", "BEARING", "BEATLES", "BECAUSE", "BECOMES", "BEDDING", "BEDFORD", "BEDROOM", "BEIJING", "BELARUS", "BELFAST", "BELGIUM", "BELIEFS", "BELIEVE", "BELONGS", "BENEATH", "BENEFIT", "BENNETT", "BERMUDA", "BERNARD", "BESIDES", "BETTING", "BETWEEN", "BEVERLY", "BICYCLE", "BIDDING", "BIGGEST", "BILLING", "BILLION", "BINDING", "BIOLOGY", "BIZARRE", "BIZRATE", "BLANKET", "BLESSED", "BLOCKED", "BLOGGER", "BLOWING", "BLOWJOB", "BOATING", "BOLIVIA", "BONDAGE", "BOOKING", "BOOLEAN", "BORDERS", "BOROUGH", "BOTTLES", "BOULDER", "BOUQUET", "BOWLING", "BRACKET", "BRADLEY", "BRANDON", "BREASTS", "BRIDGES", "BRIEFLY", "BRISTOL", "BRITAIN", "BRITISH", "BRITNEY", "BROADER", "BROKERS", "BROTHER", "BROUGHT", "BROWSER", "BUDGETS", "BUFFALO", "BUILDER", "BUKKAKE", "BURNING", "BUTTONS", "CABINET", "CALCIUM", "CALGARY", "CALLING", "CAMERAS", "CAMERON", "CAMPING", "CANDLES", "CAPABLE", "CAPITAL", "CAPITOL", "CAPTAIN", "CAPTURE", "CARDIAC", "CARDIFF", "CAREERS", "CAREFUL", "CARRIED", "CARRIER", "CARRIES", "CARROLL", "CARTOON", "CASINOS", "CASTING", "CATALOG", "CAUSING", "CAUTION", "CEILING", "CENTERS", "CENTRAL", "CENTRES", "CENTURY", "CERAMIC", "CERTAIN", "CHAMBER", "CHANCES", "CHANGED", "CHANGES", "CHANNEL", "CHAPTER", "CHARGED", "CHARGER", "CHARGES", "CHARITY", "CHARLES", "CHARLIE", "CHARTER", "CHASSIS", "CHEAPER", "CHECKED", "CHELSEA", "CHESTER", "CHICAGO", "CHICKEN", "CHINESE", "CHOICES", "CHRONIC", "CIRCLES", "CIRCUIT", "CITIZEN", "CLAIMED", "CLARITY", "CLASSES", "CLASSIC", "CLEANER", "CLEANUP", "CLEARED", "CLEARLY", "CLIENTS", "CLIMATE", "CLINICS", "CLINTON", "CLOSELY", "CLOSEST", "CLOSING", "CLOSURE", "CLOTHES", "CLUSTER", "COACHES", "COASTAL", "COATING", "COLEMAN", "COLLECT", "COLLEGE", "COLLINS", "COLOGNE", "COLORED", "COLOURS", "COLUMNS", "COMBINE", "COMFORT", "COMMAND", "COMMENT", "COMMONS", "COMPACT", "COMPANY", "COMPARE", "COMPETE", "COMPILE", "COMPLEX", "COMPUTE", "CONCEPT", "CONCERN", "CONCERT", "CONCORD", "CONDUCT", "CONFIRM", "CONNECT", "CONSENT", "CONSIST", "CONSOLE", "CONSULT", "CONTACT", "CONTAIN", "CONTENT", "CONTEST", "CONTEXT", "CONTROL", "CONVERT", "COOKIES", "COOKING", "COOLING", "COPYING", "CORNELL", "CORNERS", "CORRECT", "COSTUME", "COTTAGE", "COUNCIL", "COUNSEL", "COUNTED", "COUNTER", "COUNTRY", "COUPLED", "COUPLES", "COUPONS", "COURAGE", "COURIER", "COURSES", "COVERED", "CREATED", "CREATES", "CREATOR", "CREDITS", "CRICKET", "CRITICS", "CROATIA", "CRUCIAL", "CRUISES", "CRYSTAL", "CUISINE", "CULTURE", "CUMSHOT", "CURIOUS", "CURRENT", "CUSTODY", "CUSTOMS", "CUTTING", "CYCLING", "DAMAGED", "DAMAGES", "DANCING", "DEALERS", "DEALING", "DEBORAH", "DECADES", "DECIDED", "DECIMAL", "DECLARE", "DECLINE", "DEFAULT", "DEFECTS", "DEFENCE", "DEFENSE", "DEFICIT", "DEFINED", "DEFINES", "DEGREES", "DELAYED", "DELETED", "DELIGHT", "DELIVER", "DEMANDS", "DENMARK", "DENSITY", "DEPENDS", "DEPOSIT", "DERIVED", "DESERVE", "DESIGNS", "DESIRED", "DESKTOP", "DESPITE", "DESTINY", "DESTROY", "DETAILS", "DETROIT", "DEUTSCH", "DEVELOP", "DEVIANT", "DEVICES", "DEVOTED", "DIAGRAM", "DIAMOND", "DIETARY", "DIGITAL", "DIPLOMA", "DISABLE", "DISCUSS", "DISEASE", "DISPLAY", "DISPUTE", "DISTANT", "DIVERSE", "DIVIDED", "DIVORCE", "DOCTORS", "DOLLARS", "DOMAINS", "DONATED", "DOUGLAS", "DRAWING", "DRESSED", "DRESSES", "DRIVERS", "DRIVING", "DROPPED", "DURABLE", "DYNAMIC", "EARLIER", "EARNING", "EASTERN", "ECLIPSE", "ECOLOGY", "ECONOMY", "ECUADOR", "EDITING", "EDITION", "EDITORS", "EDWARDS", "EFFECTS", "EFFORTS", "ELDERLY", "ELECTED", "ELECTRO", "ELEGANT", "ELEMENT", "ELLIOTT", "EMBASSY", "EMERALD", "EMPEROR", "ENABLED", "ENABLES", "ENDLESS", "ENEMIES", "ENGAGED", "ENGINES", "ENGLAND", "ENGLISH", "ENHANCE", "ENJOYED", "ENLARGE", "ENQUIRY", "ENSURES", "ENTERED", "ENTRIES", "EPISODE", "EQUALLY", "EROTICA", "ESCORTS", "ESSENCE", "ESTATES", "ESTONIA", "ETERNAL", "ETHICAL", "EVENING", "EVIDENT", "EXACTLY", "EXAMINE", "EXAMPLE", "EXCERPT", "EXCITED", "EXCLUDE", "EXECUTE", "EXHAUST", "EXHIBIT", "EXISTED", "EXPECTS", "EXPEDIA", "EXPENSE", "EXPERTS", "EXPIRED", "EXPIRES", "EXPLAIN", "EXPLORE", "EXPORTS", "EXPOSED", "EXPRESS", "EXTENDS", "EXTRACT", "EXTREME", "FABRICS", "FACTORS", "FACTORY", "FACULTY", "FAILING", "FAILURE", "FALLING", "FANTASY", "FARMERS", "FARMING", "FASHION", "FASTEST", "FATHERS", "FEATURE", "FEDERAL", "FEEDING", "FEELING", "FEMALES", "FERRARI", "FICTION", "FIFTEEN", "FIGHTER", "FIGURED", "FIGURES", "FILLING", "FILTERS", "FINALLY", "FINANCE", "FINDING", "FINDLAW", "FINGERS", "FINLAND", "FINNISH", "FIREFOX", "FISHING", "FISTING", "FITNESS", "FITTING", "FLIGHTS", "FLORIDA", "FLORIST", "FLOWERS", "FOCUSED", "FOCUSES", "FOLDERS", "FOLDING", "FOLLOWS", "FOOTAGE", "FOREIGN", "FORESTS", "FOREVER", "FORMATS", "FORMING", "FORMULA", "FORTUNE", "FORWARD", "FOUNDED", "FOUNDER", "FRAMING", "FRANCIS", "FREEBSD", "FREEDOM", "FREIGHT", "FRIENDS", "FUCKING", "FUJITSU", "FUNDING", "FUNERAL", "FURTHER", "FUTURES", "GABRIEL", "GADGETS", "GALLERY", "GARBAGE", "GARDENS", "GATEWAY", "GAZETTE", "GENERAL", "GENERIC", "GENESIS", "GENETIC", "GENUINE", "GEOLOGY", "GEORGIA", "GERMANY", "GETTING", "GILBERT", "GLASGOW", "GLASSES", "GLUCOSE", "GOURMET", "GRAMMAR", "GRANTED", "GRAPHIC", "GRATUIT", "GRAVITY", "GREATER", "GREATLY", "GREGORY", "GRENADA", "GRIFFIN", "GROCERY", "GROUNDS", "GROWING", "GUITARS", "HABITAT", "HALIFAX", "HAMBURG", "HAMPTON", "HANDJOB", "HANDLED", "HANDLES", "HANGING", "HAPPENS", "HARBOUR", "HARMFUL", "HARMONY", "HARVARD", "HARVEST", "HAZARDS", "HEADERS", "HEADING", "HEADSET", "HEALING", "HEALTHY", "HEARING", "HEATHER", "HEATING", "HEAVILY", "HEIGHTS", "HELPFUL", "HELPING", "HERSELF", "HEWLETT", "HIGHEST", "HIGHWAY", "HIMSELF", "HISTORY", "HITACHI", "HITTING", "HOBBIES", "HOLDERS", "HOLDING", "HOLIDAY", "HOLLAND", "HOPKINS", "HORIZON", "HORMONE", "HOSTELS", "HOSTING", "HOTMAIL", "HOTTEST", "HOUSING", "HOUSTON", "HOWEVER", "HUNDRED", "HUNGARY", "HUNTING", "HUSBAND", "HYGIENE", "HYUNDAI", "ICELAND", "IGNORED", "ILLEGAL", "ILLNESS", "IMAGINE", "IMAGING", "IMPACTS", "IMPLIED", "IMPLIES", "IMPORTS", "IMPOSED", "IMPROVE", "INCLUDE", "INDEXED", "INDEXES", "INDIANA", "INDIANS", "INDICES", "INDUCED", "INFANTS", "INITIAL", "INJURED", "INQUIRE", "INQUIRY", "INSECTS", "INSIDER", "INSIGHT", "INSTALL", "INSTANT", "INSTEAD", "INSULIN", "INSURED", "INTEGER", "INTENSE", "INTERIM", "INVALID", "INVITED", "INVOICE", "INVOLVE", "IRELAND", "ISLAMIC", "ISLANDS", "ISRAELI", "ITALIAN", "JACKETS", "JACKSON", "JAMAICA", "JANUARY", "JEFFREY", "JELSOFT", "JESSICA", "JEWELRY", "JOHNSON", "JOINING", "JOURNAL", "JOURNEY", "JUMPING", "JUSTICE", "JUSTIFY", "KARAOKE", "KATRINA", "KEEPING", "KENNEDY", "KENNETH", "KEYWORD", "KILLING", "KINGDOM", "KISSING", "KITCHEN", "KNIGHTS", "KNOWING", "LABELED", "LANDING", "LAPTOPS", "LARGELY", "LARGEST", "LASTING", "LATINAS", "LAUNDRY", "LAWSUIT", "LAWYERS", "LEADERS", "LEADING", "LEARNED", "LEASING", "LEATHER", "LEAVING", "LEBANON", "LECTURE", "LEGALLY", "LEGENDS", "LEISURE", "LENDERS", "LENDING", "LEONARD", "LESBIAN", "LESSONS", "LETTERS", "LETTING", "LEVITRA", "LEXMARK", "LIBERAL", "LIBERIA", "LIBERTY", "LIBRARY", "LICENCE", "LICENSE", "LICKING", "LIGHTER", "LIMITED", "LINCOLN", "LINDSAY", "LINKING", "LISTING", "LIVECAM", "LIVESEX", "LOADING", "LOCALLY", "LOCATED", "LOCATOR", "LOCKING", "LODGING", "LOGGING", "LOGICAL", "LONGEST", "LOOKING", "LOTTERY", "LUGGAGE", "MACHINE", "MADISON", "MADNESS", "MADONNA", "MAGICAL", "MAILING", "MAILMAN", "MANAGED", "MANAGER", "MANDATE", "MANUALS", "MAPPING", "MARILYN", "MARKERS", "MARKETS", "MARKING", "MARRIED", "MARTIAL", "MASSAGE", "MASSIVE", "MASTERS", "MATCHED", "MATCHES", "MATTERS", "MATTHEW", "MAXIMUM", "MEANING", "MEASURE", "MEDICAL", "MEDLINE", "MEETING", "MELISSA", "MEMBERS", "MEMPHIS", "MENTION", "MERCURY", "MESSAGE", "METHODS", "MEXICAN", "MICHAEL", "MIDWEST", "MILEAGE", "MILLION", "MINERAL", "MINIMAL", "MINIMUM", "MINOLTA", "MINUTES", "MIRACLE", "MIRRORS", "MISSILE", "MISSING", "MISSION", "MISTAKE", "MIXTURE", "MOBILES", "MODULAR", "MODULES", "MOLDOVA", "MOMENTS", "MONITOR", "MONSTER", "MONTANA", "MONTHLY", "MORNING", "MOROCCO", "MOTHERS", "MOUNTED", "MOZILLA", "MUSCLES", "MUSEUMS", "MUSICAL", "MUSLIMS", "MUSTANG", "MYANMAR", "MYSIMON", "MYSPACE", "MYSTERY", "NAMIBIA", "NATIONS", "NATURAL", "NAUGHTY", "NEAREST", "NEITHER", "NERVOUS", "NETWORK", "NEUTRAL", "NEWPORT", "NIAGARA", "NIGERIA", "NIPPLES", "NIRVANA", "NORFOLK", "NOTHING", "NOTICED", "NOTICES", "NOVELTY", "NOWHERE", "NUCLEAR", "NUMBERS", "NUMERIC", "NURSERY", "NURSING", "OAKLAND", "OBESITY", "OBJECTS", "OBSERVE", "OBVIOUS", "OCTOBER", "OFFENSE", "OFFERED", "OFFICER", "OFFICES", "OFFLINE", "OLYMPIC", "OLYMPUS", "ONGOING", "ONTARIO", "OPENING", "OPERATE", "OPINION", "OPPOSED", "OPTICAL", "OPTIMAL", "OPTIMUM", "OPTIONS", "ORDERED", "ORGANIC", "ORIGINS", "ORLANDO", "ORLEANS", "OUTCOME", "OUTDOOR", "OUTLETS", "OUTLINE", "OUTLOOK", "OUTPUTS", "OUTSIDE", "OVERALL", "PACIFIC", "PACKAGE", "PACKARD", "PACKETS", "PACKING", "PAINFUL", "PAINTED", "PANTIES", "PARENTS", "PARKING", "PARTIAL", "PARTIES", "PARTNER", "PASSAGE", "PASSING", "PASSION", "PASSIVE", "PATCHES", "PATENTS", "PATIENT", "PATRICK", "PATTERN", "PAYABLE", "PAYMENT", "PAYROLL", "PENALTY", "PENDANT", "PENDING", "PENGUIN", "PENSION", "PENTIUM", "PEOPLES", "PERCENT", "PERFECT", "PERFORM", "PERFUME", "PERHAPS", "PERIODS", "PERMITS", "PERSIAN", "PERSONS", "PHANTOM", "PHILIPS", "PHOENIX", "PHRASES", "PHYSICS", "PICKING", "PICTURE", "PIONEER", "PIRATES", "PISSING", "PLACING", "PLANETS", "PLANNED", "PLANNER", "PLASTIC", "PLAYBOY", "PLAYERS", "PLAYING", "PLEASED", "PLUGINS", "POCKETS", "PODCAST", "POINTED", "POINTER", "POKEMON", "POLYMER", "PONTIAC", "POPULAR", "PORSCHE", "PORTION", "POSSESS", "POSTAGE", "POSTERS", "POSTING", "POTTERY", "POULTRY", "POVERTY", "POWERED", "PRAIRIE", "PRAYERS", "PRECISE", "PREDICT", "PREFERS", "PREMIER", "PREMIUM", "PREPAID", "PREPARE", "PRESENT", "PRESSED", "PRESTON", "PREVENT", "PREVIEW", "PRICING", "PRIMARY", "PRINTED", "PRINTER", "PRIVACY", "PRIVATE", "PROBLEM", "PROCEED", "PROCESS", "PRODUCE", "PRODUCT", "PROFILE", "PROFITS", "PROGRAM", "PROJECT", "PROMISE", "PROMOTE", "PROPHET", "PROPOSE", "PROTECT", "PROTEIN", "PROTEST", "PROUDLY", "PROVIDE", "PUBLISH", "PULLING", "PURPOSE", "PURSUIT", "PUSHING", "PUTTING", "PUZZLES", "QUALIFY", "QUALITY", "QUANTUM", "QUARTER", "QUERIES", "QUICKLY", "QUIZZES", "RADICAL", "RAILWAY", "RAINBOW", "RAISING", "RALEIGH", "RANGERS", "RANGING", "RANKING", "RAPIDLY", "RATINGS", "RAYMOND", "REACHED", "REACHES", "READERS", "READILY", "READING", "REALITY", "REALIZE", "REALTOR", "REASONS", "REBATES", "REBECCA", "REBOUND", "RECEIPT", "RECEIVE", "RECIPES", "RECORDS", "RECOVER", "REDHEAD", "REDUCED", "REDUCES", "REFINED", "REFLECT", "REFORMS", "REFRESH", "REFUSED", "REGARDS", "REGIONS", "REGULAR", "RELATED", "RELATES", "RELEASE", "RELYING", "REMAINS", "REMARKS", "REMOVAL", "REMOVED", "RENEWAL", "RENTALS", "REPAIRS", "REPLACE", "REPLICA", "REPLIED", "REPLIES", "REPORTS", "REPRINT", "REQUEST", "REQUIRE", "RESERVE", "RESOLVE", "RESORTS", "RESPECT", "RESPOND", "RESTORE", "RESULTS", "RESUMES", "RETIRED", "RETREAT", "RETURNS", "REUNION", "REUTERS", "REVEALS", "REVENGE", "REVENUE", "REVERSE", "REVIEWS", "REVISED", "REWARDS", "RICHARD", "ROBERTS", "ROLLING", "ROMANCE", "ROMANIA", "ROUGHLY", "ROUTERS", "ROUTINE", "ROUTING", "ROYALTY", "RUNNING", "RUNTIME", "RUSSELL", "RUSSIAN", "SAILING", "SAMPLES", "SAMSUNG", "SATISFY", "SAVINGS", "SCANNED", "SCANNER", "SCHEMES", "SCHOLAR", "SCHOOLS", "SCIENCE", "SCORING", "SCRATCH", "SCREENS", "SCRIPTS", "SEAFOOD", "SEASONS", "SEATING", "SEATTLE", "SECONDS", "SECRETS", "SECTION", "SECTORS", "SECURED", "SEEKERS", "SEEKING", "SEGMENT", "SELLERS", "SELLING", "SEMINAR", "SENATOR", "SENDING", "SENEGAL", "SENIORS", "SENSORS", "SERIOUS", "SERVERS", "SERVICE", "SERVING", "SESSION", "SETTING", "SETTLED", "SEVENTH", "SEVERAL", "SHADOWS", "SHAKIRA", "SHANNON", "SHARING", "SHELTER", "SHEMALE", "SHERIFF", "SHERMAN", "SHIPPED", "SHOPPER", "SHORTER", "SHORTLY", "SHOWERS", "SHOWING", "SHUTTLE", "SIEMENS", "SIGNALS", "SIGNING", "SILENCE", "SILICON", "SIMILAR", "SIMPSON", "SINGING", "SINGLES", "SISTERS", "SITEMAP", "SITTING", "SKATING", "SKILLED", "SMALLER", "SMILIES", "SMOKING", "SOCIETY", "SOLARIS", "SOLDIER", "SOLOMON", "SOLVING", "SOMALIA", "SOMEHOW", "SOMEONE", "SOONEST", "SOURCES", "SPANISH", "SPATIAL", "SPEAKER", "SPECIAL", "SPECIES", "SPECIFY", "SPENCER", "SPIRITS", "SPONSOR", "SPRINGS", "SPYWARE", "STADIUM", "STANLEY", "STARTED", "STARTER", "STARTUP", "STATING", "STATION", "STATUTE", "STAYING", "STEPHEN", "STEVENS", "STEWART", "STICKER", "STOMACH", "STOPPED", "STORAGE", "STORIES", "STRANGE", "STREAMS", "STREETS", "STRETCH", "STRIKES", "STRINGS", "STRIPES", "STUDENT", "STUDIED", "STUDIES", "STUDIOS", "STUFFED", "STYLISH", "SUBJECT", "SUBLIME", "SUCCEED", "SUCCESS", "SUCKING", "SUGGEST", "SUICIDE", "SUMMARY", "SUNRISE", "SUPPORT", "SUPPOSE", "SUPREME", "SURFACE", "SURFING", "SURGEON", "SURGERY", "SURNAME", "SURPLUS", "SURVEYS", "SURVIVE", "SUSPECT", "SWEDISH", "SYMBOLS", "SYSTEMS", "TABLETS", "TACTICS", "TALKING", "TARGETS", "TEACHER", "TEACHES", "TEENAGE", "TELECOM", "TELLING", "TENSION", "TERRACE", "TERRAIN", "TESTING", "TEXTILE", "TEXTURE", "THEATER", "THEATRE", "THEOREM", "THERAPY", "THEREBY", "THEREOF", "THERMAL", "THOMSON", "THOUGHT", "THREADS", "THREATS", "THROUGH", "THUNDER", "TICKETS", "TIFFANY", "TIMOTHY", "TOBACCO", "TODDLER", "TONIGHT", "TOOLBAR", "TOOLBOX", "TOOLKIT", "TOPLESS", "TORONTO", "TORTURE", "TOSHIBA", "TOTALLY", "TOUCHED", "TOURING", "TOURISM", "TOURIST", "TOWARDS", "TRACKED", "TRACKER", "TRACTOR", "TRADING", "TRAFFIC", "TRAGEDY", "TRAILER", "TRAINED", "TRAINER", "TRANSIT", "TRAVELS", "TREATED", "TRIBUNE", "TRIBUTE", "TRIGGER", "TRINITY", "TRIUMPH", "TROUBLE", "TRUSTED", "TRUSTEE", "TSUNAMI", "TUESDAY", "TUITION", "TUNISIA", "TURKISH", "TURNING", "TWISTED", "TYPICAL", "UKRAINE", "UNIFIED", "UNIFORM", "UNKNOWN", "UNUSUAL", "UPDATED", "UPDATES", "UPGRADE", "UPSKIRT", "URUGUAY", "USUALLY", "UTILITY", "UTILIZE", "VACCINE", "VAMPIRE", "VANILLA", "VARIETY", "VARIOUS", "VARYING", "VATICAN", "VEHICLE", "VENDORS", "VENTURE", "VERIZON", "VERMONT", "VERSION", "VESSELS", "VETERAN", "VICTIMS", "VICTORY", "VIETNAM", "VIEWERS", "VIEWING", "VILLAGE", "VINCENT", "VINTAGE", "VIOLENT", "VIRTUAL", "VIRUSES", "VISIBLE", "VISITED", "VISITOR", "VITAMIN", "VOLTAGE", "VOLUMES", "WAITING", "WALKING", "WALLACE", "WANTING", "WARMING", "WARNING", "WARRANT", "WARRIOR", "WASHING", "WATCHED", "WATCHES", "WEAPONS", "WEARING", "WEATHER", "WEBCAMS", "WEBCAST", "WEBLOGS", "WEBPAGE", "WEBSITE", "WEBSTER", "WEDDING", "WEEKEND", "WEIGHTS", "WELCOME", "WELDING", "WELFARE", "WESTERN", "WHEREAS", "WHETHER", "WICHITA", "WILLIAM", "WILLING", "WINDOWS", "WINDSOR", "WINNERS", "WINNING", "WINSTON", "WISHING", "WITHOUT", "WITNESS", "WORKERS", "WORKING", "WORKOUT", "WORRIED", "WORSHIP", "WRAPPED", "WRITERS", "WRITING", "WRITTEN", "WYOMING", "YOUNGER", "ZEALAND"]

```

For 10 characters, you'd be able to detect:

```
["ABORIGINAL", "ABSOLUTELY", "ABSORPTION", "ACCEPTABLE", "ACCEPTANCE", "ACCESSIBLE", "ACCOMPLISH", "ACCORDANCE", "ACCOUNTING", "ACCREDITED", "ACCURATELY", "ACDBENTITY", "ACTIVATION", "ACTIVITIES", "ADAPTATION", "ADDITIONAL", "ADDRESSING", "ADJUSTABLE", "ADJUSTMENT", "ADMISSIONS", "ADOLESCENT", "ADVANTAGES", "ADVENTURES", "ADVERTISER", "AFFILIATED", "AFFILIATES", "AFFORDABLE", "AFTERWARDS", "AGGRESSIVE", "AGREEMENTS", "ALEXANDRIA", "ALGORITHMS", "ALLOCATION", "AMBASSADOR", "AMENDMENTS", "ANALYTICAL", "ANNOTATION", "ANTARCTICA", "ANTIBODIES", "APARTMENTS", "APPARENTLY", "APPEARANCE", "APPLIANCES", "APPLICABLE", "APPLICANTS", "APPRECIATE", "APPROACHES", "ARCHITECTS", "ARTIFICIAL", "ASSESSMENT", "ASSIGNMENT", "ASSISTANCE", "ASSOCIATED", "ASSOCIATES", "ASSUMPTION", "ATMOSPHERE", "ATTACHMENT", "ATTEMPTING", "ATTENDANCE", "ATTRACTION", "ATTRACTIVE", "ATTRIBUTES", "AUSTRALIAN", "AUTHORIZED", "AUTOMATION", "AUTOMOBILE", "AUTOMOTIVE", "AZERBAIJAN", "BACKGROUND", "BANGLADESH", "BANKRUPTCY", "BASKETBALL", "BEASTALITY", "BEHAVIORAL", "BENEFICIAL", "BESTIALITY", "BIOLOGICAL", "BIRMINGHAM", "BLACKBERRY", "BOUNDARIES", "BRITANNICA", "BURLINGTON", "BUSINESSES", "CALCULATED", "CALCULATOR", "CALIFORNIA", "CAMCORDERS", "CANDIDATES", "CAPABILITY", "CARTRIDGES", "CATEGORIES", "CHALLENGED", "CHALLENGES", "CHANCELLOR", "CHARACTERS", "CHARITABLE", "CHARLESTON", "CHRISTIANS", "CHRONICLES", "CIGARETTES", "CINCINNATI", "CITYSEARCH", "CLASSIFIED", "COLLEAGUES", "COLLECTING", "COLLECTION", "COLLECTIVE", "COLLECTORS", "COLUMNISTS", "COMMENTARY", "COMMERCIAL", "COMMISSION", "COMMITMENT", "COMMITTEES", "COMPARABLE", "COMPARISON", "COMPATIBLE", "COMPLAINTS", "COMPLEMENT", "COMPLETELY", "COMPLETING", "COMPLETION", "COMPLEXITY", "COMPLIANCE", "COMPONENTS", "COMPRESSED", "COMPROMISE", "CONCEPTUAL", "CONCERNING", "CONCLUSION", "CONDITIONS", "CONDUCTING", "CONFERENCE", "CONFIDENCE", "CONFIGURED", "CONNECTING", "CONNECTION", "CONNECTORS", "CONSIDERED", "CONSISTENT", "CONSISTING", "CONSORTIUM", "CONSPIRACY", "CONSTANTLY", "CONSTITUTE", "CONSTRAINT", "CONSULTANT", "CONSULTING", "CONTACTING", "CONTAINERS", "CONTAINING", "CONTINUING", "CONTINUITY", "CONTINUOUS", "CONTRACTOR", "CONTRIBUTE", "CONTROLLED", "CONTROLLER", "CONVENIENT", "CONVENTION", "CONVERSION", "CONVICTION", "COORDINATE", "COPYRIGHTS", "CORRECTION", "CORRUPTION", "COUNSELING", "CREATIVITY", "CUMULATIVE", "CURRENCIES", "CURRICULUM", "CUSTOMIZED", "DECORATING", "DECORATIVE", "DEFINITELY", "DEFINITION", "DELEGATION", "DELIVERING", "DEMOCRATIC", "DEPARTMENT", "DEPENDENCE", "DEPLOYMENT", "DEPRESSION", "DESCENDING", "DESCRIBING", "DESIGNATED", "DETERMINED", "DETERMINES", "DEVELOPERS", "DEVELOPING", "DIAGNOSTIC", "DICTIONARY", "DIFFERENCE", "DIFFICULTY", "DIMENSIONS", "DIRECTIONS", "DISABILITY", "DISCIPLINE", "DISCLAIMER", "DISCLOSURE", "DISCOUNTED", "DISCOVERED", "DISCRETION", "DISCUSSING", "DISCUSSION", "DISPATCHED", "DISPLAYING", "DISTRIBUTE", "DOCUMENTED", "DOWNLOADED", "EARTHQUAKE", "ECOLOGICAL", "EDITORIALS", "EFFICIENCY", "ELECTRICAL", "ELECTRONIC", "ELEMENTARY", "EMPLOYMENT", "ENCOURAGED", "ENCOURAGES", "ENCRYPTION", "ENDANGERED", "ENGAGEMENT", "ENROLLMENT", "ENTERPRISE", "EQUIVALENT", "ESPECIALLY", "ESSENTIALS", "ESTIMATION", "EVALUATING", "EVALUATION", "EVENTUALLY", "EVERYTHING", "EVERYWHERE", "EXCELLENCE", "EXCEPTIONS", "EXCITEMENT", "EXECUTIVES", "EXHIBITION", "EXPERIENCE", "EXPERIMENT", "EXPIRATION", "EXPLAINING", "EXPLICITLY", "EXPRESSION", "EXTENSIONS", "EXTRACTION", "FACILITATE", "FACILITIES", "FAVOURITES", "FEDERATION", "FELLOWSHIP", "FORMATTING", "FORWARDING", "FOUNDATION", "FRAGRANCES", "FREQUENTLY", "FRIENDSHIP", "FUNCTIONAL", "GENERATING", "GENERATION", "GENERATORS", "GEOGRAPHIC", "GEOLOGICAL", "GIRLFRIEND", "GOVERNANCE", "GOVERNMENT", "GRADUATION", "GREENHOUSE", "GREENSBORO", "GUARANTEED", "GUARANTEES", "GUIDELINES", "HARASSMENT", "HEADPHONES", "HEALTHCARE", "HELICOPTER", "HIGHLIGHTS", "HISTORICAL", "HORIZONTAL", "HOUSEHOLDS", "HOUSEWARES", "HOUSEWIVES", "HUMANITIES", "HUNTINGTON", "HYPOTHESIS", "IDENTIFIED", "IDENTIFIER", "IDENTIFIES", "IMMIGRANTS", "IMMUNOLOGY", "IMPORTANCE", "IMPOSSIBLE", "IMPRESSION", "IMPRESSIVE", "INCENTIVES", "INCOMPLETE", "INCREASING", "INCREDIBLE", "INDICATING", "INDICATION", "INDICATORS", "INDIGENOUS", "INDIVIDUAL", "INDONESIAN", "INDUSTRIAL", "INDUSTRIES", "INFECTIONS", "INFECTIOUS", "INFLUENCED", "INFLUENCES", "INITIATIVE", "INNOVATION", "INNOVATIVE", "INSPECTION", "INSTALLING", "INSTITUTES", "INSTRUCTOR", "INSTRUMENT", "INSULATION", "INTEGRATED", "INTERESTED", "INTERFACES", "INTERNSHIP", "INTERSTATE", "INTERVIEWS", "INTRODUCED", "INTRODUCES", "INVESTMENT", "INVITATION", "IRRIGATION", "JAVASCRIPT", "JOURNALISM", "JOURNALIST", "KAZAKHSTAN", "KILOMETERS", "LABORATORY", "LANDSCAPES", "LAUDERDALE", "LEADERSHIP", "LEGITIMATE", "LIKELIHOOD", "LIMITATION", "LIMOUSINES", "LITERATURE", "LITIGATION", "LOUISVILLE", "LUXEMBOURG", "MACROMEDIA", "MADAGASCAR", "MAINSTREAM", "MAINTAINED", "MANAGEMENT", "MANCHESTER", "MASTERCARD", "MEANINGFUL", "MECHANICAL", "MECHANISMS", "MEDICATION", "MEDITATION", "MEMBERSHIP", "METABOLISM", "MICROPHONE", "MILFHUNTER", "MILLENNIUM", "MINISTRIES", "MITSUBISHI", "MODERATORS", "MONITORING", "MONTGOMERY", "MOTIVATION", "MOTORCYCLE", "MOZAMBIQUE", "MULTIMEDIA", "MYSTERIOUS", "NATIONALLY", "NATIONWIDE", "NAVIGATION", "NETWORKING", "NEWSLETTER", "NEWSPAPERS", "NOMINATION", "NOTTINGHAM", "OBITUARIES", "OBJECTIVES", "OBLIGATION", "OCCASIONAL", "OCCUPATION", "OCCURRENCE", "OFFICIALLY", "OPERATIONS", "OPPOSITION", "ORGANIZING", "ORIGINALLY", "PAPERBACKS", "PARAGRAPHS", "PARAMETERS", "PARLIAMENT", "PARTICULAR", "PASSENGERS", "PERCENTAGE", "PERCEPTION", "PERFORMING", "PERIPHERAL", "PERMISSION", "PERSISTENT", "PERSONALLY", "PETERSBURG", "PHARMACIES", "PHENOMENON", "PHILOSOPHY", "PHOTOGRAPH", "PHYSICALLY", "PHYSICIANS", "PHYSIOLOGY", "PITTSBURGH", "POLYPHONIC", "POPULARITY", "POPULATION", "PORTSMOUTH", "PORTUGUESE", "POSSESSION", "POSTPOSTED", "POWERPOINT", "PREDICTION", "PREFERENCE", "PRESCRIBED", "PRESENTING", "PREVENTING", "PREVENTION", "PREVIOUSLY", "PRINCIPLES", "PRIORITIES", "PRIVILEGES", "PROCEDURES", "PROCEEDING", "PROCESSING", "PROCESSORS", "PRODUCTION", "PRODUCTIVE", "PROFESSION", "PROGRAMMER", "PROGRAMMES", "PROHIBITED", "PROJECTION", "PROJECTORS", "PROMOTIONS", "PROPERTIES", "PROPORTION", "PROTECTING", "PROTECTION", "PROTECTIVE", "PROVIDENCE", "PROVINCIAL", "PROVISIONS", "PSYCHIATRY", "PSYCHOLOGY", "PUBLISHERS", "PUBLISHING", "PUNISHMENT", "PURCHASING", "QUALIFYING", "QUANTITIES", "QUEENSLAND", "QUOTATIONS", "REASONABLE", "REASONABLY", "RECIPIENTS", "RECOGNISED", "RECOGNIZED", "RECOMMENDS", "RECORDINGS", "RECREATION", "RECRUITING", "REDUCTIONS", "REFERENCED", "REFERENCES", "REFLECTION", "REGARDLESS", "REGISTERED", "REGRESSION", "REGULATION", "REGULATORY", "RELATIVELY", "RELAXATION", "RELOCATION", "REMARKABLE", "REMEMBERED", "REPOSITORY", "REPRESENTS", "REPRODUCED", "REPUBLICAN", "REPUTATION", "REQUESTING", "RESEARCHER", "RESISTANCE", "RESOLUTION", "RESPECTIVE", "RESPONDENT", "RESPONDING", "RESTAURANT", "RESTRICTED", "RETIREMENT", "REVELATION", "REVOLUTION", "RICHARDSON", "SACRAMENTO", "SCHEDULING", "SCIENTIFIC", "SCIENTISTS", "SCREENSHOT", "SECURITIES", "SELECTIONS", "SEPARATELY", "SEPARATION", "SETTLEMENT", "SIGNATURES", "SIMPLIFIED", "SIMULATION", "SITUATIONS", "SOUNDTRACK", "SPECIALIST", "STATEMENTS", "STATIONERY", "STATISTICS", "STRATEGIES", "STRENGTHEN", "STRUCTURAL", "STRUCTURED", "STRUCTURES", "SUBJECTIVE", "SUBMISSION", "SUBMITTING", "SUBSCRIBER", "SUBSECTION", "SUBSEQUENT", "SUBSIDIARY", "SUBSTANCES", "SUBSTITUTE", "SUCCESSFUL", "SUFFICIENT", "SUGGESTING", "SUGGESTION", "SUNGLASSES", "SUPERVISOR", "SUPPLEMENT", "SUPPORTERS", "SUPPORTING", "SURPRISING", "SURROUNDED", "SUSPENSION", "SYSTEMATIC", "TECHNICIAN", "TECHNIQUES", "TECHNOLOGY", "TELEVISION", "TERRORISTS", "THEMSELVES", "THEREAFTER", "THOROUGHLY", "THREATENED", "THROUGHOUT", "THUMBNAILS", "THUMBZILLA", "TOURNAMENT", "TRACKBACKS", "TRADEMARKS", "TRADITIONS", "TRANSCRIPT", "TRANSEXUAL", "TRANSITION", "TRANSLATED", "TRANSLATOR", "TRAVELLING", "TREATMENTS", "TREMENDOUS", "ULTIMATELY", "UNDERLYING", "UNDERSTAND", "UNDERSTOOD", "UNDERTAKEN", "UNEXPECTED", "UNIVERSITY", "UZBEKISTAN", "VALIDATION", "VARIATIONS", "VEGETABLES", "VEGETARIAN", "VEGETATION", "VETERINARY", "VIETNAMESE", "VIOLATIONS", "VISIBILITY", "VOCABULARY", "VOCATIONAL", "VOLKSWAGEN", "VOLLEYBALL", "VOLUNTEERS", "VULNERABLE", "WALLPAPERS", "WARRANTIES", "WASHINGTON", "WATERPROOF", "WEBMASTERS", "WELLINGTON", "WIDESCREEN", "WIDESPREAD", "WILDERNESS", "WITHDRAWAL", "YUGOSLAVIA"]

```

It works for other lengths too, but I thought I'd specifically mention the ones within the spec that it will indeed work for. For example 227 results in:

```
["ABS", "BAR", "BBS", "CAP", "CAR", "CAS", "CBS"]

```

If the winner of this challenge is being chosen by shortest code, I can make this 140 bytes shorter if needed.
> 5 votes

# Answer
# VDM-SL, ~~313~~ ~~395~~ ~~385~~ ~~289~~ 278 bytes

```
f(i)==let m={'2'|->"abc",'3'|->"def",'4'|->"ghi",'5'|->"jkl",'6'|->"mno",'7'|->"pqrs",'8'|->"tuv",'9'|->"wxyz"},d=IO`freadval[set of ?],q=[i(p)|p in set inds i&i(p) in set dom m]in let r in set d("f").#2 be st forall x in set inds q&len(q)=len(r)and r(x)in set elems m(q(x))in r

```

Turns out IO is easier than I thought!

Still expensive because of building the map (I'm sure there'll be a good map comprehension for it I've just not thought of it yet) and could save further bytes if the string was guaranteed to only contain values in the domain of the map

### Explanation:

```
f(i)==
let m=...,                           /* m is a map of char to seq of char */
d=IO`freadval[set of ?]            /* d is the file read function that will read a set of something */
q=[i(p)|p in set inds i&i(p) in set dom m] /* q is a sequence comprehension defined by
                                             take the values in i where i is in the domain
                                             of our map m */
let r in set d("f").#2                    /* let r be a value in my dictionary of words (read from the file f) */
be st                                     /* such that */
forall x in set inds q&len(q)=len(r)      /* the length of q and r are the same */
and r(x)in set elems m(q(x))              /* for every char in q the char in
                                                  r at that position is in the range of the
                                                  map for that char in q */
in r         /* return r*/

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 217 bytes

```
n=>n.Where(c=>c>47&c<58).Select(c=>", , abc def ghi jkl mno pqrs tuv wxyz".Split()[c-48]).Aggregate(new[]{""},(a,b)=>a.SelectMany(c=>b.Select(d=>c+d)).ToArray()).Where(x=>File.ReadAllText("a.txt").Contains($@"
{x}
"))

```

Expects the dictionary in a file named `a.txt`.

Try it online!
> 2 votes

---
Tags: code-challenge, permutations
---


title: Relevant Part for a Badminton Serve

text:
# Question
Title: Relevant Part for a Badminton Serve
## Introduction:

I saw there was only one other badminton related challenge right now. Since I play badminton myself (for the past 13 years now), I figured I'd add some badminton-related challenges. Here the second (first one can be found here):

## Challenge:

Some rules about badminton serves:

* A serve will always be done diagonally over the net.
* You must always serve after the line that's parallel and nearest to the net.
* The area in which you are allowed to serve differs depending on whether it's a single (1 vs 1) or double/mix (2 vs 2).
    + For singles (1 vs 1), the blue area in the picture below is where you are allowed to serve. So this is including the part at the back, but excluding the parts at the side.
    + For doubles/mix (2 vs 2), the green area in the picture below is where you are allowed to server. So this is excluding the part at the back, but including the parts at the side.
* You may not stand on the lines when serving. But the shuttle will still be inside if they land on top of a line.

Here the layout of a badminton field:

## Challenge rules:

**Input:**

You will be given two inputs:

* Something to indicate whether we're playing a single or double/mix (i.e. a boolean)
* Something to indicate which block you're serving from (i.e. `[1,2,3,4]` or `['A','B','C','D']` as used in the picture above).

**Output:**

Only the relevant lines for the current serve (including the net), including an `F` to indicate where you serve from, and multiple `T` to indicate where you will potentially serve to.

Although in reality you're allowed to serve from and to anywhere in the designated areas, we assume a person that will serve will always stands in the corner of the serve area closes to the middle of the net, which is where you'll place the `F`. And they will serve to any of the four corners of the area where they have to serve to, which is where you'll place the `T`s.
As ASCII-art, the entire badminton field would be the following (the numbers are added so you don't have to count them yourself):

```
 2        15              15        2

+--+---------------+---------------+--+
|  |               |               |  |    1
+--+---------------+---------------+--+
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |    9
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |
+--+---------------+---------------+--+
|  |               |               |  |    2
|  |               |               |  |
O=====================================O    37 times '='
|  |               |               |  |
|  |               |               |  |    2
+--+---------------+---------------+--+
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |    9
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |
|  |               |               |  |
+--+---------------+---------------+--+
|  |               |               |  |    1
+--+---------------+---------------+--+

```

**Examples:**

Here two examples for outputting only the relevant parts of the serve:

Input: Single and serve block `A`
Output:

```
                   T---------------T
                   |               |
                   +---------------+
                   |               |
                   |               |
                   |               |
                   |               |
                   |               |
                   |               |
                   |               |
                   |               |
                   |               |
                   T---------------T
                   |               |
                   |               |
O=====================================O
   |               |
   |               |
   +---------------+
   |              F|
   |               |
   |               |
   |               |
   |               |
   |               |
   |               |
   |               |
   |               |
   +---------------+
   |               |
   +---------------+

```

As you can see, the `F` is added in the corner within the block, but the `T` are replacing the `+` in the ASCI-art output.

---

Input: Double and serve block `C`
Output:

```

+--+---------------+
|  |               |
|  |               |
|  |               |
|  |               |
|  |               |
|  |               |
|  |               |
|  |               |
|  |              F|
+--+---------------+
|  |               |
|  |               |
O=====================================O
                   |               |  |
                   |               |  |
                   T---------------+--T
                   |               |  |
                   |               |  |
                   |               |  |
                   |               |  |
                   |               |  |
                   |               |  |
                   |               |  |
                   |               |  |
                   |               |  |
                   T---------------+--T

```

## Challenge rules:

* Leading and trailing newlines are optional (including the leading and trailing two empty lines when the input is single). Trailing spaces are optional as well. Leading spaces are mandatory however.
* Any four reasonable distinct inputs to indicate which block we're serving from are allowed (for integers, stay within the \[-999,999\] range); as well as any two reasonable distinct inputs to indicate whether its a single or double/mix (please note this relevant forbidden loophole, though). **Please state the I/O you've used in your answer!**
* You are allowed to use a lowercase `f` and `t` (or mixed case) instead of `F` and `T`.
* You are allowed to return a list of lines or matrix of characters instead of returning or printing a single output-string.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

# Answer
# Charcoal, 81 bytes

```
ＮθＦ⮌Ｅθ⁺¹⁶×³ιＦ✂541⊖θＵＲι±×³Ｉκ×=¹⁸O⟲Ｏ↙⁴Ｊ¹±³FＦ²Ｆ²«Ｊ×ι±⁺¹²×³θ⁺²×⁻¹⁵×³θκT»Ｆ№ABη‖↑Ｆ№ACη‖

```

Try it online! Link is to verbose version of code. Takes the first input as `1` or `2` for singles or doubles, second input as one of `ABCD` as in the question. Explanation:

```
Ｆ⮌Ｅθ⁺¹⁶×³ιＦ✂541⊖θＵＲι±×³Ｉκ

```

Loop over the relevant widths and the heights of the `D` court and draw the rectangles.

```
×=¹⁸O⟲Ｏ↙⁴

```

Draw the net and apply rotational symmetry to add the `A` court.

```
Ｊ¹±³F

```

Add the `F` to the `D` court.

```
Ｆ²Ｆ²«Ｊ×ι±⁺¹²×³θ⁺²×⁻¹⁵×³θκT»

```

Add the `T`s to the relevant places in the `A` court.

```
Ｆ№ABη‖↑Ｆ№ACη‖

```

Reflect the output as necessary to serve from the correct court.
> 2 votes

# Answer
# Python 2, ~~285~~ 284 bytes

```
R=str.replace
s,q=input()
A=' '*19
l='| '[s]+'  |'+A[4:]+'|'+A
r=['T--+','   T'][s]+'-'*15+'T'+A
h=[r]+[l,R(r,*'T+')]*s+[l]*8+[l[:18]+'F'+'|'+A,r,l,l,'O'+'='*37+'O']
h+=[R(l[::-1],*'T+')for l in h[-2::-1]]
h[9+2*s]=R(h[9+2*s],*'F ')
for l in[l[::q%2*2-1]for l in h[::q/2*2-1]]:print l

```

Try it online!

Takes input as `0/1` (or `False/True`) for game type (`Double/Single`),

and `0-3` for serving block (`0,1,2,3` = `C,D,A,B`)
> 3 votes

# Answer
# JavaScript (ES7),  ~~216 ... 205 201~~  199 bytes

Takes input as `(block)(double)`, where *block* is either \\$-2\\$ (top right), \\$-1\\$ (bottom left), \\$1\\$ (bottom right) or \\$2\\$ (top left) and *double* is a Boolean value.

```
b=>d=>(g=x=>y<31?`+-| =OTF
`[X=x-19,Y=y-15,p=X*Y*b<0,q=Y>0^b&1,X*=X,Y*=Y,i=x*24%35>2|~16>>Y%62%6&2,x<39?Y?p*X|(d?Y:X-87)>169?3:i?X-1|Y-16|q?i:7:q*(d?X-87:Y)%169&&6:x%38?4:5:++y&&8]+g(-~x%40):'')(y=0)

```

Try it online!

Formatted version

### How?

We iterate from \\$y=0\\$ to \\$y=30\\$ and from from \\$x=0\\$ to \\$x=39\\$ for each value of \\$y\\$.

We first define \\$X=x-19\\$ and \\$Y=y-15\\$.

The variables `p = X * Y * b < 0` and `q = Y > 0 ^ b & 1` are used to determine what do draw in each quarter according to the block \\$b\\$.

From now on, both \\$X\\$ and \\$Y\\$ are squared in order to easily test absolute positions within each quarter of the field.

The expression `x * 24 % 35 > 2` yields *false* if \\$x\\$ belongs to \\$\\{0, 3, 19, 35, 38\\}\\$ (the positions of the vertical lines) or *true* otherwise.

Try it online!

The expression `~16 >> Y % 62 % 6 & 2` yields \\$0\\$ if \\$y\\$ belongs to \\$\\{0, 2, 12, 18, 28, 30\\}\\$ (the positions of the horizontal lines, excluding the net) or \\$2\\$ otherwise.

Try it online!

The variable \\$i\\$ is defined as the result of a bitwise OR between the two values above, and is therefore interpreted as:

* 3: space
* 2: `|`
* 1: `-`
* 0: `+` or `T`

The expression `(d ? Y : X - 87) > 169` is used to crop the field according to the game type \\$d\\$ (single or double). The similar expression `(d ? X - 87 : Y) % 169` is used to draw the `T`'s at the appropriate positions.
> 1 votes

# Answer
# Jelly, ~~108~~ 99 bytes

```
“¢¥Þ‘Ṭ+þ³ḤN+“¢¤€‘¤ṬḤ;Ø0¤×3R¤¦€³+0x39¤µ‘03³?‘;20¤¦€1,-2¦;565DWx“¢%¢‘¤;UṚ$ị“|-+TO= ””F21¦€³Ḥ_⁵¤¦UṚƭ⁴¡

```

Try it online!

I’m sure this can be better golfed.

Dyadic link with left argument 0 or 1 for singles/doubles and right argument 0,1,2,3 for different serve quadrants. Returns a list of strings

Thanks to @KevinCruijssen for saving a byte!
> 1 votes

---
Tags: code-golf, string, ascii-art
---


title: Terrain Reachability

text:
# Question
Title: Terrain Reachability
Turn-based tactics games like Advance Wars, Wargroove, and Fire Emblem are made up of a square grid of varying terrain with units of differing movement classes requiring different costs for each terrain type. We'll be investigating a subset of that problem.

## Challenge

Your task is to determine if one location is reachable from another given a grid of terrain costs and a movement speed.

Units can only move orthogonally where the cost of moving onto a square is the value of the corresponding cell on the grid (moving off is free). For instance, moving from a cell valued 3 onto a cell valued 1 costs 1 movement, but going the other way requires 3. Some squares may be inaccessible.

### Example

```
1 [1] 1  1  1
1  2  2  3  1
2  3  3  3  4
1  3 <1> 3  4

```

Moving from `[1]` to `<1>` requires a minimum of 7 movement points by moving right one square and then down three. Thus, if given 6 or less as the movement speed, you should output a falsy answer.

## Example Test Cases

These will use top-left-origin zero-indexed (row, column) coordinates rather than bracketed cells for start and end to make parsing easier. Unreachable cells will be represented with `X`

Case 1a

```
1 1 2 1 X
1 2 2 1 1
2 1 1 2 1
X X X 1 2
Speed: 5
From (2, 3) to (0, 1)

Output: True

```

Case 1b

```
1 1 2 1 X
1 2 2 1 1
2 1 1 2 1
X X X 1 2
Speed: 4
From (2, 3) to (0, 1)

Output: False

```

Case 1c

```
1 1 2 1 X
1 2 2 1 1
2 1 1 2 1
X X X 1 2
Speed: 5
From (0, 1) to (2, 3)

Output: False

```

Case 2a

```
3 6 1 1 X 4 1 2 1 X
5 1 2 2 1 1 1 X 1 5
2 1 1 1 2 1 1 1 X 1
2 1 1 3 1 2 3 4 1 2
1 1 2 1 1 4 1 1 1 2
3 2 3 5 6 1 1 X 1 4
Speed: 7
From (3, 4) to (2, 1)

Output: True

```

Case 2b

```
3 6 1 1 X 4 1 2 1 X
5 1 2 2 1 1 1 X 1 5
2 1 1 1 2 1 1 1 X 1
2 1 1 3 1 2 3 4 1 2
1 1 2 1 1 4 1 1 1 2
3 2 3 5 6 1 1 X 1 4
Speed: 4
From (3, 4) to (2, 1)

Output: False

```

Case 2c

```
3 6 1 1 X 4 1 2 1 X
5 1 2 2 1 1 1 X 1 5
2 1 1 1 2 1 1 1 X 1
2 1 1 3 1 2 3 4 1 2
1 1 2 1 1 4 1 1 1 2
3 2 3 5 6 1 1 X 1 4
Speed: 7
From (1, 8) to (2, 7)

Output: True

```

Case 3a

```
2 1 1 2
2 3 3 1
Speed: 3
From (0, 0) to (1, 1)

Output: False

```

Case 3b

```
2 1 1 2
2 3 3 1
Speed: 3
From (1, 1) to (0, 0)

Output: True

```

## Rules, Assumptions, and Notes

* Standard loopholes are banned, I/O can be in any convenient format
* You may assume coordinates are all on the grid
* Movement speed will never be over 100
* Inaccessible cells may be represented with very large numbers (e.g. 420, 9001, 1 million) or with 0 or null, whichever is most convenient for you.
* All inputs will consist of positive integers (unless using null or 0 to represent unreachable cells)

# Answer
# TSQL query, ~~205~~ 191 bytes

Input is a table variable @t

@x=start xpos, @y=start ypos @i=end xpos , @j=end ypos @ =speed

```
DECLARE @t table(x int,y int,v int)
INSERT @t
values
(0,0,1),(0,1,1),(0,2,2),(0,3,1),(0,4,null),
(1,0,1),(1,1,2),(1,2,2),(1,3,1),(1,4,1),
(2,0,2),(2,1,1),(2,2,1),(2,3,2),(2,4,1),
(3,0,null),(2,1,null),(2,2,null),(2,3,1),(2,4,2)

DECLARE @x INT=2,@y INT=3,@i INT=0,@j INT=1,@ INT=5;

WITH C as(SELECT @y f,@x r,@ s
UNION ALL
SELECT f+a,r+b,s-v FROM C
JOIN(values(1,0),(0,1),(-1,0),(0,-1))x(a,b)ON
s>0JOIN @t
ON f+a=x and r+b=y)SELECT
max(iif(S>=0and f=@j and r=@i,1,0))FROM c

```

**Try it online** ungolfed version
> 2 votes

# Answer
# Python 2, 220 bytes

```
def f(m,a,w,h,r,c,R,C):
 T=[w*[999]for _ in' '*h];T[r][c]=0;P=[(r,c)];j,k=1,0
 for u,v in P:exec"U,V=u+j,v+k;j,k=-k,j\nif h>U>-1<V<w:q=T[U][V];T[U][V]=min(T[u][v]+m[U][V],q);P+=[(U,V)]*(q>T[U][V])\n"*4
 return a>=T[R][C]

```

Try it online!

Takes an array `m` of integers, with `'X'` as a larger-than-100 value;, a speed `a`, `m` having width `w` and height `h`; and returns whteher we can start at the zero-indexed row/column cell `(r,c)` and get to the final cell `(R,C)`.

The algorithm is a modified flood-fill. Slightly ungolfed code:

```
def f(m,a,w,h,r,c,R,C):
 T = [w*[999]for _ in ' '*h] # make an array same size as m, with all
                             #   values 999, whose values will represent
                             #   the cost of getting to each cell.
 T[r][c] = 0                 # set the starting location to a cost of 0
 P = [(r,c)]                 # initialize a set of cells whose neighbors'
                             #   cost might need to be be updated
 j,k = 1,0                   # and also j,k which will take on values:
                             #  (1,0), (0,1), (-1,0), (0,1), used to
                             #  probe orthogonal neighbors
 for u,v in P:               # scan the cells in P
    for _ in '1234':         # look at each of 4 orthogonal positions
        U,V = u+j,v+k        # U and V get the indexes of a neighbor
                             #   of the current cell.
        j,k = -k,j           # this 'rotates' the j,k pairing.
        if h>U>-1<V<w:       # if the coordinates are in bounds...
            q = T[U][V]      # save the current 'cost' of getting to cell (U,V)
                             # see if we can reduce that cost, which is calculated
                             #   by taking the cost of the currently scanned cell
                             #   + the value from m for the neighbor cell.
            T[U][V] = min(T[u][v]+m[U][V] ,q)
                             # if we can reduce the cost, add the neighbor
                             #   to P because **it's** neighbors might,
                             #   in turn, need updating.
            P += [(U,V)]*(q>T[U][V])
 return a>=T[R][C]           # return if speed is enough for the cost.

```
> 0 votes

# Answer
# JavaScript (ES7),  ~~116~~  113 bytes

Takes input as `(matrix)([endRow, endCol])(speed, startRow, startCol)`. Expects large values for unreachable squares. Returns \\$0\\$ or \\$1\\$.

```
m=>e=>o=g=(s,y,x)=>m.map((r,Y)=>r.map((v,X)=>r[s<v|(x-X)**2+(y-Y)**2-1||g(s-v,Y,X,r[X]=1/0),X]=v),o|=y+[,x]==e)|o

```

Try it online!

### Commented

```
m =>                        // m[] = matrix
e =>                        // e[] = target coordinates
  o =                       // o   = success flag, initialized to a non-numeric value
  g = (                     // g   = recursive depth-first search function taking:
    s,                      //   s    = speed
    y, x                    //   y, x = starting coordinates
  ) =>                      //
    m.map((r, Y) =>         // for each row r[] at position Y in m[]:
      r.map((v, X) =>       //   for each value v at position X in r[]:
        r[                  //     this statement ultimately updates r[X]:
          s < v |           //       abort if s is less than v
          (x - X) ** 2 +    //       or the quadrance between (x, y)
          (y - Y) ** 2 - 1  //       and (X, Y) is not equal to 1
          || g(             //       otherwise, do a recursive call to g:
               s - v,       //         subtract v from s
               Y, X,        //         pass (Y, X) as the new coordinates
               r[X] = 1 / 0 //         temporarily make this cell unreachable
             ),             //       end of recursive call
          X                 //       restore r[X] ...
        ] = v               //     ... to its original value
      ),                    //   end of inner map()
      o |= y + [, x] == e   //   set the flag o if (y + ',' + x) matches (e + '')
    ) | o                   // end of outer map(); return o

```
> 0 votes

# Answer
# Jelly, 59 bytes

```
+2¦µ_2ịæ.Ø½œị$Ʋ+5ịƲ$4¦01Ñḣ3Ḋ⁼/Ɗ?ḣ2=/ẸƊoF<0ẸƊƊ?
çⱮØ.,U$;N$¤Ẹ

```

Try it online!

Not terribly fast; tries all paths until the speed units are exhausted, even retracing its steps. However, this avoids the need to check whether spaces are visited. Input is provided as `[nrows, ncols],[start_row, start_col],[end_row, end_col],speed,flattened matrix column-major`

### Explanation

Helper link

```
+2¦                                       | add the right argument to the second item in the left argument (current location)
   µ                                      | start a new monadic chain with the modified left argument
                    4¦                    | for the fourth item (speed)...
    _                                     |   subtract...
                 ịƲ$                      |     the item located at...
     2ịæ.Ø½œị$Ʋ                           |       the dot product of the current position and (number of columns,
                                          |       right-padded with 1)
               +5                         |       plus five
                                        ? | Now, if...
                                       Ɗ  |   next three as a monad
                           ḣ2=/ẸƊ         |   either current row or current column are equal to nrows/ncolumns respectively
                                 o        | or
                                  F<0ẸƊ   |   any value is negative
                 0                        | return zero
                          ?               | else if...
                   ḣ3Ḋ⁼/Ɗ                 | the second and third items (current and end pos) are equal
                  1                       | return 1
                   Ñ                      | else pass the current list back to the main link

```

Main link

```
ç             | call the helper link with the current list...
 Ɱ            |   and each of
  Ø.,U$;N$¤   |   [0,1],[1,0],[0,-1],[-1,0]
           Ẹ  | Check if any are true

```
> 0 votes

# Answer
# Jelly, 38 bytes

```
ạƝṢ€Ḅ’¬Ạ
ŒṪ’ḟŒPŒ!€ẎW€j¥@€ÇƇḊ€‘œị⁸§Ṃ’<⁵

```

An extremely inefficient full program accepting the terrain (with unvisitables as 101) then the start and end co-ordinates then the speed.

**Try it online!** (not much point trying most of the test cases!)

### How?

Creates a list of all permutations of each of the power-set of "all terrain locations except the start & end", surrounds each of these with the start & end, filters to those which make only orthogonal moves of distance one, drops the start from each, indexes back into the terrain, sums each, takes the minimum, subtracts one and tests that this is less than the speed.
> 0 votes

---
Tags: code-golf, decision-problem, grid
---


title: set intersection of two lists

text:
# Question
Title: set intersection of two lists
Your goal is to compute the set intersection of two lists of integers. The intersection is defined as the unique un-ordered group of integers found at least once in both input list.

# Input

The input may be in any format desired (function parameter, stdio, etc.), and consists of two lists of integers. You many not assume anything about each list other than they may contain any non-negative number of integers (i.e. they are unsorted, possibly may contain duplicates, may have different lengths, and may even be empty). It is assumed that each integer will fit in your language's native signed integer type, may be more than 1 decimal digit long, and are signed.

Example input:

```
1 4 3 9 8 8 3 7 0
10 1 4 4 8 -1

```

# Output

The output is any list-like of integers representing the set intersection of the two lists to any format desired (return value, stdio, etc.). There is no requirement that the output be sorted, though you are welcome to provide an implementation that happens to always be sorted. The output must form a valid un-ordered set (e.g. it must not contain any duplicate values).

Example test cases (note that the order of the output is not important):

First two lines are the input lists, third line is the output. `(empty)` denotes the empty list.

```
(empty)
(empty)
(empty)

1000
(empty)
(empty)

3 1 2 4 3 1 1 1 1 3
3 1 -1 0 8 3 3 1
1 3

1 2 1
3 3 4
(empty)

```

# Scoring

This is code golf; shortest answer in bytes wins.

Standard loop-holes are prohibited. You may use any built-in features not designed for set-like operations.

Prohibited built-in features:

* set creation/removing duplicates
* set difference/intersection/union
* Generalized membership testing (e.g. anything similar to the `in` keyword in Python, `indexOf`-like functions, etc). Note that the use of "foreach item in list" constructs are allowed (assuming they don't violate any of the other restrictions), despite the fact that Python re-uses the `in` keyword to create this construct.
* These prohibited built-ins are "viral", i.e. if there's a larger built-in containing any of these sub-features, it is similarly prohibited (e.g. filtering by membership in a list).

Any built-ins not on the above list are allowed (ex. sorting, integer equality testing, list append/remove by index, filtering, etc.).

For example, take the following two example snippets (Python-like code):

```
# prohibited: filters by testing if each value in tmpList is a member of listA
result = tmpList.filter(listA)

# ok: filtering by a lambda which manually iterates over listA and checks for equality
def my_in_func(val, slist):
    for a in slist:
        if(val == a):
            return True
    return False
result = filter(lambda v: my_in_func(val, listA), tmpList)

```

You are welcome to implement any of these set-like features yourself and they will count towards your score.

Your solution should complete in a reasonable amount of time (say, less than a minutes on whatever hardware you have for two lists ~length 1000 each).

# Answer
## Haskell, ~~45~~ 42 bytes

```
y#(e:s)=[e|any(==e)y,all(/=e)s]++y#s
_#x=x

```

Try it online!

Edit: -2 bytes thanks to @Ørjan Johansen, -1 byte thanks to @dfeuer.
> 7 votes

# Answer
# MATL, 18 bytes

```
YY_iti!=Xa)hStdfQ)

```

**Try it online!**

This works in two steps. First the intersection is computed, possibly with duplicates. This is based on comparing all elements of one array with all elements of the other, and keeping elements of the first that are present in the second.

Then duplicates are removed. For this, the array from the previous step is sorted, and entries are kept if different from the preceding. A `-inf` value is prepended so that the first (i.e. lowest) value is not lost.

```
YY_                 % push -infinity
   it               % take first input. Duplicate
     i!             % take second input. Transpose
        =           % test all combinations of elements of the two inputs for equality
        Xa          % row vector that contains true for elements of first array that
                    % are present in the second, possibly duplicated
          )         % index into first array to keep only those elements. Now we need
                    % to remove duplicates
           h        % append -infinity
            S       % sort
             tdf    % duplicate. Find entries that differ from the preceding
                Q)  % add 1 and index into array to keep only non-duplicates

```
> 4 votes

# Answer
# Jelly, 13 bytes

```
=S¥Ðf
ṂrṀ{ç³ç

```

Try it online!

### How it works

```
ṂrṀ{ç³ç  Main link. Arguments: A (list 1), B (list 2)

Ṃ        Yield m, the minimum of A.
  Ṁ{     Yield M, the maxmimum of A.
 r       Create an inclusive range from m to M.
    f³   Apply the helper link with right argument A.
      f  Apply the helper link with right argument B.

=S¥Ðf    Helper link. Arguments: n (integer in range), L (list, A or B)

=        Test all elements of L for equality with n.
 S       Add the results.
  ¥      Combine the two previous links into a dyadic chain.
   Ðf    Filter by the result of the sums.

```
> 4 votes

# Answer
# golflua, 68 chars

```
\f(a,b)k={}~@_,v p(a)~@_,w p(b)?w==v k[w]=w$$$~@_,v p(k)I.w(v," ")$$

```

which is called as

```
> f({1,2,3,4},{3,4,5})
3 4
> f({3,1,2,4,3,1,1,1,1,3},{3,1,-1,0,8,3,3,1})
3 1

```

In regular Lua, this would be

```
function foo(a,b)
   local k={}
   for i,v in pairs(a)
      for j,w in pairs(b)
         if v==w then
            k[v] = v
         end
      end
   end
   for i,v in pairs(k)
      print(v," ")
   end
end

```

So basically I'm iterating over the each element of the two tables and only storing the equivalent values. By using the value as the key (`k[w]=w`), I'm eliminating all duplicates. We then output the new table by iterating over the index & value of `pairs`
> 3 votes

# Answer
## JavaScript (ES6), 66 bytes

```
(a,b)=>a.filter((e,i)=>b.some(f=>e==f)&a.slice(0,i).every(f=>e-f))

```

Without using `indexOf`, as I'm not convinced that it's permitted.
> 3 votes

# Answer
# Pyth, ~~12~~ 11 bytes

```
eMrSsq#RQE8

```

Demonstration

Explanation:

```
eMrSsq#RQE8
               Implicit: Q is one of the lists.
     q#RQE     For every element in the first list, filter the second list on
               equality with that element.
    s          Concatenate. We now have the intersection, with duplicates.
  rS      8    Sort and run length encode, giving counts and elements.
eM             Take just the elements.

```
> 3 votes

# Answer
# bash + GNU coreutils, 184 Bytes

```
[ -z "$1" ] && exit
p='{if(a[$0]++==0)print $0}'
while read A; do
while read B; do
[ $A = $B ] && echo $A
done < <(grep -oP '\d*'<<<$1|awk "$p")
done < <(grep -oP '\d*'<<<$2|awk "$p")

```

Invocation:

```
./codegolf.sh '12 4 654 12 3 56' '4 4 56 33 3 3 3'

```

Output:

```
4
56
3

```

No output if intersection is empty. This script does not sort and makes sanity check if first set is empty. Explanation:

```
[ -z "$1" ] && exit  # Exit if first set is empty
p='{if(a[$0]++==0)print $0}' # The AWK program we will use
while read A; do   # read the list with two
while read B; do   # encapsulated loops
[ $A = $B ] && echo $A   # if they match, then print
done < <(grep -oP '\d*'<<<$1|awk "$p")
done < <(grep -oP '\d*'<<<$2|awk "$p")
# the process substitution greps the numbers and pipes them to awk. Our awk program makes them unique without sorting; it uses associative arrays with index names same as lines (our numbers here).

```

Bonus to know: You could change to `grep -o .` to do this with random strings instead of numbers.
> 2 votes

# Answer
# Perl 6, ~~26~~ 37 bytes

```
{%(@^a.grep(any(@^b)):p.invert).keys}

```

**usage**

```
> my &f = {%(@^a.grep(any(@^b)):p.invert).keys}
-> @a, @b { #`(Block|559823336) ... }
> f([3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1])
(1 3)

```

**Cheeky non-competing answer**

```
> [3,1,2,4,3,1,1,1,1,3] ∩ [3,1,-1,0,8,3,3,1]
set(3, 1)

```

or if you like it in a boring ol' `f` function

```
> my &f = &infix:<∩>
sub infix:<∩> (|p is raw) { #`(Sub+{<anon|130874592>}+{Precedence}|102325600) ... }
> f([3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1])
set(3, 1)

```
> 2 votes

# Answer
# Retina, 63 bytes

The last two lines remove duplicates. The input is two space-delimited lists separated by a comma. The output is whitespace-delimited.

```
+`( -?\d+)\b(.*,.*)\1\b
$1_$2
-?\d+\b|_|,

+`(-?\d+)(.*)\1
$1$2

```

**Try it online**

If duplicates in the output are allowed, my program would be 42 bytes.
> 2 votes

# Answer
# Jq 1.5, 99 bytes

```
def f(a;b):(a+b|min)as$m|[range($m;a+b|max)|[]]|.[a[]-$m][0]=1|.[b[]-$m][1]=1|.[[[1,1]]]|map(.+$m);

```

Expanded

```
def f(a;b):
     (a+b|min) as $m         # find smallest value in either array
   | [range($m;a+b|max)|[]]  # create array of [] for indices [min,max]
   | .[ a[]-$m ][0]=1        # store 1 in [0] at corresponding indices of a
   | .[ b[]-$m ][1]=1        # store 1 in [1] at corresponding indices of b
   | .[[[1,1]]]              # find all the indices where we stored a 1 for a and b
   | map(.+$m)               # convert back from indices to values
;

```

This avoids using `{}` objects and since jq does not have bit operations this emulates them with an array.

Try it online!
> 2 votes

# Answer
# Axiom, 411 bytes

```
b(x,v)==(l:=1;h:=#v;repeat(l>h=>break;m:=(l+h)quo 2;x<v.m=>(h:=m-1);x>v.m=>(l:=m+1);return m);0);g(a,b)==(if #a>#b then(v:=a;w:=b)else(v:=b;w:=a);c:=sort(v);for x in w repeat(if binSearch(x,c)~=0 then return 1);0)
f(a:List INT,b:List INT):List INT==(r:List INT:=[];#a*#b=0=>r;x:=sort(a);y:=sort(b);i:=1;repeat(i>#x=>break;v:=x.i;binSearch(v,y)=0=>(i:=i+1);r:=concat(r,v);while i<=#x and x.i=v repeat i:=i+1);r)

```

ungolf and test

```
--suppose v.1<=v.2<=....<=v.#v as the default function sort() produce
--   binary serch of x in v, return the index i with v.i==x
--   return 0 if that index not exist
--traslated in Axiom from C  book
--Il Linguaggio C, II Edizione
--Brian W.Kerninghan, Dennis M.Ritchie
binSearch(x,v)==
    l:=1;h:=#v
    repeat
       l>h=>break
       m:=(l+h)quo 2
       x<v.m=>(h:=m-1)
       x>v.m=>(l:=m+1)
       return m
    0

--N*log(N)+n*log(n)+N*n*log(n) so it is N*n*log(n) or n*N*log(N)
ListIntersection(a:List INT,b:List INT):List INT==
    r:List INT:=[];#a*#b=0=>r
    x:=sort(a);y:=sort(b)
    i:=1
    repeat
        i>#x=>break
        v:=x.i
        binSearch(v,y)=0=>(i:=i+1)
        r:=concat(r,v)
        while i<=#x and x.i=v repeat i:=i+1
    r

(5) -> f([],[])
   (5)  []
                                                       Type: List Integer
(6) -> f([1000],[])
   (6)  []
                                                       Type: List Integer
(7) -> f([3,1,2,4,3,1,1,1,1,3],[3,1,-1,0,8,3,3,1])
   (7)  [1,3]
                                                       Type: List Integer
(8) -> f([1,2,1],[3,3,4])
   (8)  []
                                                       Type: List Integer

```
> 2 votes

# Answer
# Axiom, 257 bytes

```
W(x,y)==>while x repeat y;f(a,b)==(r:List INT:=[];#a*#b=0=>r;x:=sort(a);y:=sort(b);i:=1;j:=1;repeat(j>#y=>break;W(i<=#x and x.i<y.j,i:=i+1);i>#x=>break;W(j<=#y and y.j<x.i,j:=j+1);j>#y=>break;v:=y.j;if x.i=v then(r:=concat(r,v);W(j<=#y and y.j=v,j:=j+1)));r)

```

This without the use of binsearch... But i don't know the big O... Unglofed and results:

```
--N*log(N)+n*log(n)+???
ListIntersection(a:List INT,b:List INT):List INT==
    r:List INT:=[];#a*#b=0=>r
    x:=sort(a);y:=sort(b)
    i:=1;j:=1
    repeat
        j>#y=>break
        while i<=#x and x.i<y.j repeat i:=i+1
        i>#x=>break
        while j<=#y and y.j<x.i repeat j:=j+1
        j>#y=>break
        v:=y.j;if x.i=v then
                        r:=concat(r,v)
                        while j<=#y and y.j=v repeat j:=j+1
    r

(3) -> f([3,1,2,4,3,1,1,1,1,3],[3,1,-1,0,8,3,3,1])
   (3)  [1,3]
                                                       Type: List Integer
(4) -> f([],[])
   (4)  []
                                                       Type: List Integer
(5) -> f([1,2,1],[3,3,4])
   (5)  []
                                                       Type: List Integer

```

Not executed many tests so could be bugged...
> 2 votes

# Answer
# Jelly, 12 bytes

```
pEÐfḢ€ĠḢ€$ị$

```

Try it online!
> 2 votes

# Answer
# Husk, 9 bytes

```
mo←←kIfE*

```

Try it online!

```
m            Map
 o←←         taking the first element from the first element
    kI       over lists of identical values from
        *    the Cartesian product of the two input lists
      f      filtered by
       E     both elements of a pair being equal.

```

Looking in Husk's source code on GitHub, `k` ("keyon") is implemented as the composition of sorting the list and grouping adjacent values, so although I can't actually find the implementation of "groupOn" it's probably safe to assume that it doesn't do anything setty, since Haskell is a functional language and grouping adjacent equal values is a pretty straightforward reduce-over-a-linked-list operation. (I *can* find the implementation of `k`'s other type signature "keyby", which I could use here by changing `I` to `=`, but I don't know Haskell so I can't tell how exactly it works.)

Also, a nice little Brachylog answer I came up with before I realized set operations of all sorts were disallowed: `⟨∋∈⟩ᵘ`
> 2 votes

# Answer
# R, ~~141~~ 83 bytes

~~```
l=sapply(strsplit(readLines(file("stdin"))," "),as.numeric)
r=rle(sort(unlist(l)))[[2]]
r[sapply(r,function(x)any(x==l[[1]])&any(x==l[[2]]))]

```~~

Improved by Giuseppe

```
function(a,b){r=rle(sort(c(a,b)))[[2]];r[sapply(r,function(x)any(x==a)&any(x==b))]}

```

Try online ~~here~~ here
> 2 votes

# Answer
# Python3, 51 bytes

```
lambda a,b:[v for v in a if{n:1 for n in b}.get(v)]

```

If the input lists can contain duplicates:

## Python3, 67 bytes

```
lambda a,b:list({v:1 for v in a if {n:1 for n in b}.get(v)}.keys())

```
> 1 votes

# Answer
# PHP, ~~78~~, 77 bytes

```
function($a,$b){foreach($a as$x)foreach($b as$y)$x==$y?$c[$x]=$x:0;return$c;}

```

Try it online!

No frills, but rule-compliant (I think).

***Output***

```
[], []
[]

[1000], []
[]

[3,1,2,4,3,1,1,1,1,3], [3,1,-1,0,8,3,3,1]
[3,1]

[1,2,1], [3,3,4]
[]

```
> 1 votes

---
Tags: code-golf, math, set-theory
---


# Question
Title: The Strange Unsorting Machine for Nefarious Purposes
Good Evening Golfers!

Your challenge is to completely unsort a series of numbers.

# Input

Exactly 100 integers will be fed to your program. Your program may accept the input either as a file, or via stdin. Each integer will be separated by a newline character.

Those 100 integers will range from the minimal to the maximal values of a signed integer in your chosen language.

There will be no duplicate values. The values may be ordered, unordered or partially ordered - your program should be able to handle each case.

# Output

The output must be each of the 100 integers, completely unsorted, each separated by a newline character. The output may be via stdout, or to a file.

*Completely Unsorted* means that no value is adjacent to any value which it would be adjacent to if the list were completely sorted in an ordered sequence.

# Score

1 point per character, and lowest score wins. There is a bonus of -100 for any solution using no built in or library sorting functions. There is a bonus of -20 for any solutions using no built in random number functions.

I have tried to define this question as completely as possible. If you have any questions, please ask. If you have any comments on how I could do better next time, please let me know.

Fore!

# Answer
## GolfScript (score 27 - 120 = -93)

```
~].,{{.2$<{\}*}*]}*.(;+2%n*

```

Note: that `$` is referencing an element on the stack. There is sorting, but it's done with an manually coded bubble sort.

Thanks to Howard, for -90 =\> -92; and Ilmari, who inspired -92 =\> -93.
> 9 votes

# Answer
# Python -26

(94-120): New, crude approach. Keep popping lowest elements into new list to get the elements sorted, then iterate:

```
t=l=[]
i=N=100
exec't=t+[input()];'*N+'l+=[t.pop(t.index(min(t)))];'*N+'print l[i%N];i+=3;'*N

```

# Python -13

(107-120): First approach: Removes four lowest elements at a time, then print these four in another order:

```
exec'l=[]'+'+[input()]'*100
while l:
 a,b,c,d=eval('l.pop(l.index(min(l))),'*4)
 for e in[b,d,a,c]:print e

```
> 6 votes

# Answer
# C: 11 (131 - 120)

The programm reads from stdin and does a simple insert sort, after that it prints the nth together with th n+50th number, like many of the other solutions.

```
main(){int*i,a[101],*j=a;while(scanf("%d",a)>0)for(i=++j;i-->a;)i[1]=*i>=*a?*i:*(i=a);while(a<(i=j-50))printf("%d\n%d\n",*i,*j--);}

```
> 4 votes

# Answer
## J, -63 (57-120) characters

Since everyone else is going down the self-written sort route...

```
,50(}.,.{.)($:@([-.m),~m=.]#~]=<./)^:(0<#),".[;._2[1!:1[3

```

Doesn't use any random number function, nor any built-in sort.

Uses a simple recursive selection sort to sort the input.
> 3 votes

# Answer
# Mathematica -56 44 4 (95-120) = -25

**Edit**:

This version relies on neither built-in functions for sorting lists, nor randomization functions.

```
Riffle[RotateLeft[#[[All, 2]], 2], #[[All, 1]]] &
[Partition[l //. {x___, a_, b_, y___} /; b < a :> {x, b, a, y}, 2]]

```
> 3 votes

# Answer
# Ruby 1.9, -59

### (61-120)

Recursion! This one does in fact, unlike my previous Ruby attempts, unsort the list regardless of their original order.

```
p *(f=->l{l[1]&&f[l-m=l.minmax]+m||[]})[$<.map &:to_i].rotate

```

### Previous attempts

Cute one-liner, now using builtin sort to work properly:

```
$<.map(&:to_i).sort.each_slice(4){|a,b,c,d|p b,d,a,c}

```

First one -- Didn't necessarily unsort the last 4 values:

```
l=$<.map &:to_i
48.times{l-=p *l.minmax}
a,b,c,d=l
p b,d,a,c

```
> 3 votes

# Answer
## Python 2: 90 char

```
n=100
s=sorted(int(raw_input())for i in range(n))
for i in range(n):print s[(4*i+4*i/n)%n]

```

lazy attempt but just for starters
> 1 votes

# Answer
# Python 27 (147 - 100 - 20)

```
R=range
def S(L):
 for i in R(len(L)-1):
    if L[i]>L[i+1]:L[i:i+2]=[L[i+1],L[i]];S(L)
a=map(input,['']*100);S(a)
for i in R(100):print a[i/2+i%2*50]

```

Note: the spaces before `if L[i]>...` should be a tab but apparently show up as spaces in a code block.
> 1 votes

# Answer
# Python 48 = (148 - 100)

```
from random import*
x=[input()for i in range(100)]
while any(abs(x[i]-x[i+1])>1 for i in range(99)):n=randint(1,99);x=x[n:]+x[:n]
for j in x:print j

```

Haven't tested this because it isn't guaranteed (or likely) to run in any reasonable amount of time, but should work in theory given infinite time.
> 1 votes

# Answer
# Perl 5: 95 - 120 = -25 chars

Counting the following command line:

```
perl -ne '$n=$_;splice@n,(grep{$n[$_]>$n}0..@n),0,$n}{print for map{@n[$_,$#n/2+$_+1]}0..$#n/2'

```
> 1 votes

# Answer
# Ruby: -50 (70 chars - 120)

I did the same as many other answers: iteratively remove the max and min from the input list and append them to the output. However, I realized that if the 2 numbers on either side of the median are themselves consecutive, the output will be incorrect (because those 2 consecutive numbers will appear together at the end of the output). To fix this, I rotate the "unsorted" list right by 1 element:

```
n=$*.map &:to_i;u=[];50.times{u+=n.minmax;n-=u.last 2};p *u.rotate(-1)

```

Or, to work with arbitrarily many inputs (using only 4 more characters):

```
n=$*.map &:to_i;u=[];(u+=n.minmax;n-=u.last 2)while n.any?;p *u.rotate(-1)

```

*Note: Some fewer-char Ruby answers have already been posted, but those solutions did not address the median issue (and/or assumed a sorted input list).*
> 1 votes

# Answer
## J 37 - 100 = -63

```
({~?~@#)^:(+./@(1=|)@(2&(-/\))@/:)^:_

```

Uses no sort (though does use rank up) Uses random numbers.

Explanation:

```
({~?~@#)             NB. Randomizes the array
^: foobar ^:_        NB. as long as
foo =: +./@(1 = |)   NB. as any 1 == absolute value of
bar =: (2&(-/\))@/:  NB. differences between adjacent ranks
foobar =: foo@bar

```
> 1 votes

# Answer
# Brachylog, 22 bytes - 120 = -98

```
ṇịᵐpX¬{p≤₁s₂.&s₂p}∧Xẉᵐ

```

Try it online!

The TIO link only has an input of eight integers, rather than one hundred, because this is so dreadfully slow that it can't handle any more in 60 seconds. The reason for this is that, among other things, rather than implement some simple but normal sorting algorithm for the mandatory bonus, I for the sake of brevity used what amounts to a deterministic bogosort: `p≤₁` backtracks through every permutation of the input until it finds one which is non-decreasing. Although a larger reason would probably be that it employs a similar degree of brute force to find the output, and that it recomputes the sorted version every time... I attempted to test it on an actual input of size 100, but I'm not sure just how many days it will take.

An overall better version:

# Brachylog, 14 bytes - 20 = -6

```
p.¬{os₂.&s₂p}∧

```

Try it online!

This ignores the antiquated I/O requirements for brevity, and neglects to take the -100 bonus so it can possibly be tested without a supercomputer (although as of writing this, I've had it running on only 20 items for several minutes and it still hasn't given me anything).

```
 .                The output is
p                 a permutation of
                  the input
  ¬{        }∧    such that it cannot be proven that
         s₂       a pair of adjacent values in
        &         the output
       .   p      is a permutation of
     s₂           a pair of adjacent values in
    o             the output sorted.

```
> 1 votes

# Answer
# Forth (gforth), 79 - 120 = -21 bytes

```
: f 100 0 do dup i 2 mod 4 * 2 - i + i 99 = i 0 = - 3 * + cells + @ . cr loop ;

```

Try it online!

Ignore antiquated input requirements and takes input as an address in memory where the numbers are stored.

### Explanation

Loops through all numbers from 0 to 99. For each number (n):

* If n is 0:
    + output the value at array address + 1
* Else If n is 99:
    + output the value at array address + 98
* Else If n is odd:
    + output the value at array address + (n + 2)
* Else (n is even):

+ output the value at array address + (n - 2)
* Output a newline

### Code Explanation

```
: f               \ start new word definition
  100 0 do        \ loop from 0 to 99
    dup           \ duplicate the array address
    i             \ place the loop index on the stack
    2 mod 4 * 2 - \ convert to 2 if it's odd and -2 if it's even
    i +           \ add the result to the the loop index
    i 99 =        \ if i = 99 place -1 on top of the stack, else place a 0
    i 0 =         \ i i = 0 place -1 on top of the stack, else place 0
    - 3 *         \ subtract previous two results from each other and multiply by 3
\ the above line is used to avoid writing if/then by instead using math to get 98 and 1
    +             \ add result to existing result from above
    cells         \ multiply by the size of a single integer in memory
    +             \ add to the array's starting address
    @ . cr        \ get the value at the calculated address, print it, then print a newline
  loop            \ end the loop
;                 \ end the word definition

```
> 0 votes

---
Tags: code-challenge, sorting, permutations
---


# Question
Title: Rearrange a number into alphabetical order
Given a non-negative integer (`n`), create a function that returns `n` in alphabetical order, according to the literal spelling of each digit in `n`.

### Examples:

```
Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320

```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

This is code-golf, so the shortest code in bytes wins.

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

# Answer
# Perl 6,  ~~32~~  28 bytes

```
~~{+[~] .comb.sort: *.Str.uniname}~~
{+[~] .comb.sort: *.uniname}

```

### Explanation:

```
{
  # turn the following into a Numeric
  +

  # fold the following list using string concatenation operator
  [~]

    # split $_ into individual characters
    # (implicit method call on implicit parameter)
    .comb

    .sort:
    *.uniname # sort by the Unicode name of the character (digit)
}

```

### Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

my @tests = (
  101 => 110,
  31948 => 84913,
  5544 => 5544,
  1234567890 => 8549176320,
);

# give the lambda a lexical name for clarity
my &int-sort = {+[~] .comb.sort: *.uniname}

plan 3 * @tests;

for @tests -> $_ ( :key($input), :value($expected) ) {
  put '';
  isa-ok $input, Int, "input ($input) is an Int";

  my $output = int-sort $input;

  is $output, $expected, .gist;
  isa-ok $output, Int, "output ($output) is an Int"
}

```

```
1..12

ok 1 - input (101) is an Int
ok 2 - 101 => 110
ok 3 - output (110) is an Int

ok 4 - input (31948) is an Int
ok 5 - 31948 => 84913
ok 6 - output (84913) is an Int

ok 7 - input (5544) is an Int
ok 8 - 5544 => 5544
ok 9 - output (5544) is an Int

ok 10 - input (1234567890) is an Int
ok 11 - 1234567890 => 8549176320
ok 12 - output (8549176320) is an Int

```
> 12 votes

# Answer
## 05AB1E, ~~12~~ ~~11~~ 10 bytes

```
•OWÿ¾•vy†J

```

**Explained**

```
•OWÿ¾•        # push sortorder (236719458)
      v       # for each number in sortorder
       y†     # filter to the front
         J    # join
              # implicitly print

```

Try it online

Saved 1 byte thanks to Adnan
> 8 votes

# Answer
# JavaScript (ES6), 54

*Edit* same char count, but avoiding the global variable `z`

Input / output as strings

```
n=>[...n].sort((a,b)=>n[a]-n[b],n='9487216503').join``

```

**Test**

```
f=n=>[...n].sort((a,b)=>n[a]-n[b],n='9487216503').join``

function test() {
  O.textContent=f(I.value)
}

test()
```

```
<input id=I type=number value=31948 oninput='test()'>
<pre id=O></pre>
```
> 8 votes

# Answer
## Haskell, ~~62 51~~ 44 bytes

As @nimi suggested, using a list comprehension is shorter than composing functions:

```
f x=0+read[a|a<-"8549176320",b<-show x,a==b]

```

For reference my version:

```
f n=read.(=<<)(\x->filter(==x)$show n)$"8549176320"

```

The pointfree version is a bit longer:

```
f=flip(read.)"8549176320".(=<<).flip(filter.(==)).show

```

Straightforward: Filter the digits in the correct order and then concatenate the result.
> 6 votes

# Answer
# Pyth, ~~12~~ 10 bytes

```
ox`C" »Ä\0

```

Not sure if it can be golfed further. Input needs to be enclosed in quotes.

2 bytes saved thanks to @isaacg!

In pythonic pseudocode:

```
                Q = input()
o          Q    sort(Q, key = lambda N:
  `C" »Ä\0        repr(base256toDec(" »Ä\0"))
 x        N         .index(N)     # 8 being absent from the number yields -1
                )

```

Test it here.
> 5 votes

# Answer
# Perl, 37 bytes

36 bytes code + 1 byte command line (-F)

```
say sort{8549176320=~/$b.*$a/||-1}@F

```

Usage example:

```
echo -n "04823" | perl -F -M5.010 entry.pl

```
> 4 votes

# Answer
# Mathematica ~~35 78~~ 47 bytes

31 bytes saved thanks to a suggestion by LIAMnYP!

```
FromDigits@SortBy[IntegerDigits@#,IntegerName]&

```

`IntegerDigits` breaks up the number into digits which are then sorted according to their names in English. `FromDigits` assembles the digits into a base-10 number.

---

```
FromDigits@SortBy[IntegerDigits@#,IntegerName]&[1234567890]

```

8549176320
> 3 votes

# Answer
# C, ~~142~~ ~~141~~ 117

Pass parameter as `long long *` to `f()`; the function modifies the parameter:

```
f(long long*n){char*c="8549176320",g[10]={0};for(;*n;*n/=10)++g[*n%10];for(;*c;++c)for(;g[*c-48]--;*n=*n*10+*c-48);}

```

`long long` is necessary since the last test case overflowed an `int` when sorted.
> 3 votes

# Answer
# MATL, 19 bytes

```
Vt'8549176320'&m2$S

```

**Try it online!**

### Explanation

```
V              % Implicitly input number. Convert to string (¹)
t              % Push copy of (¹)
'8549176320'   % Push this string (²), which defines order
&m             % Indices (³) of each element of (¹) in (²)
2$S            % Sort copy of (¹) according to (³). Implicitly display

```
> 3 votes

# Answer
# Jelly, 11 bytes

```
“U1°ŀ”OṾf@€

```

Try it here.

## Explanation

```
“U1°ŀ”O       Get the Unicode ordinals of “U1°ŀ”
                (all of which are coincidentally single bytes
                in the Jelly code page!)
              The result is [85, 49, 176, 320].
       Ṿ      Uneval. This gets us the string “85,49,176,320”.
        f@€   For each char in this string, extract all chars
                from the first command line argument that
                equal it.

```
> 3 votes

# Answer
## Python 2 - 95 bytes

```
def s(n):
    l=list("8549176320")
    return "".join(sorted(list(n),key=lambda x: l.index(x)))

```

Attempting further golfing...I think the line 2 is unnecessary and this can become 1 lambda.

EDIT: 49 char version in comments, thx to xnor and vaultah for help.
> 2 votes

# Answer
**-- Oracle 11 (SQL): 164 bytes**

```
  SELECT LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',')WITHIN GROUP(ORDER BY 1)FROM(SELECT SUBSTR(&1,level,1)s FROM dual CONNECT BY LEVEL<=LENGTH(&1));

```

**Long form and explanation**

```
  SELECT LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',') WITHIN GROUP (ORDER BY 1)
  FROM ( SELECT SUBSTR(&1,level,1)s FROM dual
           CONNECT BY LEVEL <= LENGTH(&1)
        );

```

Get the input as parameter to script:

```
  SELECT &1 FROM dual

```

"create" rows by using connect by based on length of input:

```
  CONNECT BY LEVEL <= LENGTH(&1)

```

Rip out each digit from the string for each position:

```
  SELECT SUBSTR(&1,level,1)s FROM dual

```

Convert the digit to Julian date, and back to Char to get spelling:

```
  TO_CHAR(TO_DATE(s,'j'),'jsp')

```

Check for zero - special case.

```
  DECODE(s,0,'zero'

```

Use LISTAGG function to concatenate rows back into a single row list, comma delimited, ordered alphabetically

```
  LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',') WITHIN GROUP (ORDER BY 1)

```

Always fun trying to tweak SQL for things like this ... :) really tests my knowledge of the bugger ...
> 2 votes

# Answer
# Racket, ~~142~~ 130 bytes

```
(λ(n)(string->number(list->string(sort(string->list(~a n))char<? #:key(λ(m)(string-ref "9487216503"(-(char->integer m)48)))))))

```

Of which conversions are ~~more than~~ *almost* half of the length (~~76~~ 64 bytes).
> 1 votes

# Answer
# Ruby, 60 bytes

```
->n{n.to_s.chars.sort_by{|c|'8549176320'.index c}.join.to_i}

```
> 1 votes

# Answer
# TSQL, 260 bytes

Used reversed bubble sort to avoid refering to the length, to save some bytes

**Golfed:**

```
DECLARE @ varchar(99)=101

,@i INT=99,@j INT=98WHILE @i>1SELECT
@=IIF(CHARINDEX(x,'598327614')>CHARINDEX(y,'598327614'),STUFF(STUFF(@,@j,1,x),@i,1,y),@),@i-=IIF(@j=1,1,0),@j=IIF(@j=1,@i,@j-1)FROM(SELECT
SUBSTRING(@,@i,1)x,SUBSTRING(@,@j,1)y)z
PRINT @

```

**Ungolfed:**

```
DECLARE @s BIGINT=1234567890

DECLARE @ char(99)=@s,@i INT=99,@j INT=98
WHILE @i>1
  SELECT
    @=IIF(CHARINDEX(x,'236719458')>CHARINDEX(y,'236719458'),
        STUFF(STUFF(@,@j,1,x),@i,1,y),@),
    @i-=IIF(@j=1,1,0),
    @j=IIF(@j=1,@i,@j-1)
  FROM(SELECT SUBSTRING(@,@i,1)x,SUBSTRING(@,@j,1)y)z
PRINT CAST(@ as bigint)

```

Insisting on using integer types as input and output added 37 bytes
> 1 votes

# Answer
# ClojureScript, 45 bytes

```
#(apply str(sort-by(vec"9487216503")(str %)))

```

Uses some screwy string-\>int conversion from Javascript leak through, so it's not valid Clojure.
> 1 votes

# Answer
## Firebird, 317 bytes

**Golfed:**

```
select list(s,'')from(with recursive q as(select 1 p,substring(:a from 1 for 1)s from rdb$database q union all select q.p+1 p,substring(:a from q.p+1 for 1)s from q where q.p<char_length(:a))select s from q order by iif(s=8,0,iif(s=5,1,iif(s=4,2,iif(s=9,3,iif(s=1,4,iif(s=7,5,iif(s=3,7,iif(s=2,8,iif(s=0,9,6))))))))))

```

**Ungolfed:**

```
select list(s, '')
from (
   with recursive q as (
      select 1 as p, substring(:a from 1 for 1) s
      from rdb$database q
      union all
      select q.p + 1 as p, substring(:a from q.p + 1 for 1) as s
      from q
      where q.p < char_length(:a)
   )
   select s
   from q
   order by iif(s = 8, 0,
               iif(s = 5, 1,
                  iif(s = 4, 2,
                     iif(s = 9, 3,
                        iif(s = 1, 4,
                           iif(s = 7, 5,
                              iif(s = 3, 7,
                                 iif(s = 2, 8,
                                    iif(s = 0, 9, 6)))))))))
)

```

There's no split functionality in Firebird. Instead I created a recursive query to get the next character over and over. Then reselect those while sorting by our proper order. Finally concatenate those results back together in a list. Override the default comma delimiter with blank. I could save 11 bytes by creating a new dummy table instead of `rdb$database` but I thought that may be against the rules.
> 1 votes

# Answer
## ZX Spectum, machine code, ~~53~~ ~~48~~ ~~47~~ ~~45~~ 44 bytes

```
    org 49200 ; #c030

; table converts ascii to alfabetical order
; start from BASIC with any number as : PRINT "1234567890" AND USR 49208

```

`convtab defb 249 ; zero
 defb 244 ; one
 defb 248 ; two
 defb 247 ; three
 defb 2+205 ; four
 defb 1+205 ; five
 defb 246 ; six
 defb 245 ; seven
 ; defb 0 ; eight
 ; defb 3 ; nine
 ; last 2 conversions hidden in call-command`

````
start Call #2bf1    ; fetch stackindex
    call #2ab2 ; store back
    ld h,#c0    ; set highbyte of table

Sort Push de
loop ld b,d
    ld c,e
    inc de
    ld a,(bc)   ; fetch number
    Ld l,a
    ld a,(de)
    cp 34       ; endmarker "
    Jr z,exit   ; end reached?
    push hl     ; save number
    ld l,a
    Ld a,(hl)   ; convert second number
    pop hl
    cp (hl)     ; compare numbers
    jr nc,loop  ; in order, no swap
swap ld a,(bc)  ; swap original numbers
    ld l,a
    ld a,(de)
    ld (bc),a
    ld a,l
    ld (de),a
Exit pop de
    Ret z
    jr sort     ; check number for order

````
> 1 votes

# Answer
# Factor, 128

```
[ 10 base> [ 48 - ] { } map-as dup [ number>text ] map zip [ second first ] sort-with [ first ] map [ 48 + ] ""map-as 10 >base ]

```

Hooray for builtins! :D
> 0 votes

# Answer
# PHP, 126 bytes

As far as I know php doesn't have any builtins that would really help with this (the best I could do using a usort(str\_split()) was 5 bytes longer) so the only thing I'm happy within this answer is the games played with $i to save a couple of bytes on the itteration.

```
<?php for($i=-1;$i<9;)$a[++$i]=preg_replace("/[^$i]/","",$argv[1]);array_multisort([9,4,8,7,2,1,6,5,0,3],$a);echo implode($a);

```
> 0 votes

# Answer
# APL, 23 bytes

```
{⍎n['8549176320'⍋n←⍕⍵]}

```

Explanation:

* `n←⍕⍵`: get the string representation of `n` and store it in `n`
* `'8549176320'⍋`: find a permutation of `n` that sorts `n` given the order `8549176320`.
* `n[`...`]`: reorder `n` by that permutation
* : evaluate the result (to turn it back into a number)
> 0 votes

# Answer
# Clojure, 53 bytes

Well, list comprehension idea from Haskell solution seems to be the shortest:

```
#(apply str(for[p"8549176320"b(str %):when(= p b)]p))

```

My original approach is 1 byte longer:

```
#(apply str(sort-by(zipmap"549176320"(range))(str %)))

```

You can see both function online here: https://ideone.com/afac5n
> 0 votes

# Answer
## Common Lisp, 104

```
(lambda(n)(#1=parse-integer(sort(format()"~A"n)'string<= :key(lambda(u)(format()"~R"(#1#(string u)))))))

```

### Ungolfed

```
(lambda (n)
  (parse-integer
   (sort (format nil "~A" n)
         #'string<=
         :key (lambda (u) (format nil "~R" (parse-integer (string u)))))))

```

Convert integer as string, sort characters using the `string<=` comparison while using a custom `:key` function which converts a given character as the English representation of the numerical value it represents. Usually I would not use a key function which does as much as this one, but it costs less in bytes than decorate/sort/undecorate.
> 0 votes

# Answer
# Python 3, 234 bytes

This is a direct translation of my Factor answer, just for fun.

```
def f(n):
 s=list(map(int,str(n)))
 return int("".join(list(map(str,list(map(lambda x:x[1],sorted(list(zip(list(map(lambda t:{0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"}[t],s)),s)))))))))

```

The semantics of the evaluation of "lazy" map and zip objects is the most subtle hard-to-find-bug-inducing piece of genuine horse excrement in the universe. Sometimes, `s = map(f, x)` won't allow `s` to be used properly or at all.
> 0 votes

# Answer
# Python 3, 74 bytes

```
lambda x:''.join(i[1]for i in sorted(['9487216503'[int(j)],j]for j in x))

```
> 0 votes

# Answer
## Pyke, 14 bytes

```
.#uЀB`@

```

Try it here!
> 0 votes

# Answer
## Python 2.7.11, 67 bytes

```
lambda n:''.join(sorted(list(n),key=lambda s:"9487216503"[int(s)]))

```

Takes a string as input and outputs a string.
> 0 votes

# Answer
## C, 80 bytes

Takes a string containing a number in base 10 and prints to `stdio`:

```
F(char*i){for(char*p,d,*o="8549176320";*o;++o)for(p=i;d=*p++;d-*o||putchar(d));}

```
> 0 votes

# Answer
# PHP, 107 bytes

```
function($a){usort($a,function($a,$b){return($z=array_flip([8,5,4,9,1,7,6,3,2,0]))[$a]-$z[$b];});return$a;}

```

Try it online!

Uses a user-defined comparison function to adjust the sorting order.

***Output***

```
101         110
31948       84913
5544        5544
1234567890  8549176320

```
> 0 votes

---
Tags: code-golf, number, sorting
---