title: Golfing Emoticons

text:
# Question
Title: Golfing Emoticons
## Introduction

Your challenge today (inspired by this challenge) is to write a number of snippets, functions or full programs each that output various ascii emoticons, without reusing characters.

## Challenge

* The list of valid ascii emoticons for this challenge is both here and in the code block at the bottom of this post.
* Each snippet should be on a separate line in your submission.
* You may only use one language for all the snippets.
* Each snippet must either output to stdout or return a string containing the emoticon and an optional trailing new line, and *nothing else*.
* You may not use any character more than once across all snippets, however using a character multiple times in a single snippet is fine.
* You may not use any character not in your language's codepage (or ascii, if your language doesn't use a custom codepage) in any of the snippets. Put another way, you are restricted to only characters that can be encoded in one byte.
* No snippet can take any input.
* Standard loopholes are disallowed.
* Your score is the number of unique snippets that each print a different ascii emoticon in the text file above.
* Highest score wins!

*Good luck!*

---

Allowed emoticons, space separated:

```
:-) :) :-] :] :-3 :3 :-> :> 8-) 8) :-} :} :o) :c) :^) =] =) :-D :D 8-D 8D x-D xD X-D XD =D =3 B^D :-)) :-( :( :-c :c :-< :< :-[ :[ :-|| >:[ :{ :@ >:( :'-( :'( :'-) :') D-': D:< D: D8 D; D= DX :-O :O :-o :o :-0 8-0 >:O :-* :* ;-) ;) *-) *) ;-] ;] ;^) :-, ;D :-P :P X-P XP x-p xp :-p :p :-b :b d: =p >:P :-/ :/ :-. >:\ >:/ :\ =/ =\ :L =L :S :-| :| :$ :-X :X :-# :# :-& :& O:-) O:) 0:-3 0:3 0:-) 0:) 0;^) >:-) >:) }:-) }:) 3:-) 3:) >;) |;-) |-O :-J #-) %-) %) :-###.. :###.. <:-| ',:-| ',:-l <_< >_>

```

*EDIT: Apologies, there was a Unicode character in one of the emoticons which I missed. I have since deleted the emoticon containing it. I hope it won't cause too much inconvenience.*

# Answer
# Lenguage, 131

I have put all the emoticons I am representing in the format `<emoticon> <byte> <length>` where the program is `<byte>` repeated `<length>` times.

```
:-) 0 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
:) 1 2892400118827976939438684163170029797380
:-] 2 736490387500841447075516267663006608725303862349670620478812283647578112884440609487323312712386965678607264902605611675427012612
:] 3 264202969342699153645046819327998571303367330111090974890246487724490982787908355751940
:-3 4 8657402899421565866640894175739857184468743778771208393372298092586390046095597770136092676
:3 5 3105690979328168701182830269522101416768856653828
:-> 6 74366524642622405428665075721999126422007787328051598231869446920043450605361049824610086990930509828
:> 7 26677682375393393246302105048632582268435010638972146679812
8-) 8 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
8) 9 2892400118827976939438684163170029797380
:-} a 58350780111110182577346156792191842346790220983533887814420020926317170260174910391653244380390906064837889652367278401208674211826539380018313418995597836292
:} b 20932315791834567081523240053201294833948611487434768542347530871005539691107893137313828947907611434178521119850500
:o) c 3239118979209708736174752985014882031111216334552277195105326435158161594234375948611157455571250214219021418006029673058983092521806556299268
:c) d 47135384800053852612833041130432422958419430281388881777898152870448562232695635591679564906662772946483627525782544884262590480388
:^) e 1438457788087580951319367710279309782666608590130275933163395778517107001730213488515614614316939287805297916050613997699858436
=] f 264202969342699153645046819327998571303367330111090974890246487724490982787908355751940
=) 10 2892400118827976939438684163170029797380
:-D 11 19494738235915607848691977610067738996770809401324758166895184293407870315491767045222586644150487567302660
:D 12 6993394368615125679158619025868739646176627428942714419231588356
8-D 13 19494738235915607848691977610067738996770809401324758166895184293407870315491767045222586644150487567302660
8D 14 6993394368615125679158619025868739646176627428942714419231588356
x-D 15 19494738235915607848691977610067738996770809401324758166895184293407870315491767045222586644150487567302660
xD 16 6993394368615125679158619025868739646176627428942714419231588356
X-D 17 19494738235915607848691977610067738996770809401324758166895184293407870315491767045222586644150487567302660
XD 18 6993394368615125679158619025868739646176627428942714419231588356
=D 19 6993394368615125679158619025868739646176627428942714419231588356
=3 1a 3105690979328168701182830269522101416768856653828
B^D 1b 3477977520889650736889014052879324099230182173920756338825997078602142158679966714563481466490641782098496260504558444186939511707432172833580792152068
:-)) 1c 5487280990934680753018828240506400232950626778227616999140473333355621344480221047070135810437858502018906538135322099716
:-( 1d 1007854344721600164966761853515619549954862308079750322896556241040396276639727620
:( 1e 361550014853497117429835520396253724676
:-c 1f 193066536141020580302164136470251204437686055691792055134797767284510716823978799133444882487675968730852822850628645467043138793111556
:c 20 69259223195372526933127153405918857475749925384641832521628775278048964191953448010235510788
:-< 21 1161976947540975084822891808156236350343871677000806222372960108125678915708766403509532609233289220
:< 22 416838787115521769473470391384884097944297041233939791876
:-[ 23 11507662304700647610554941682234478261332872849213603444981441931993408013819384523239426761131046338728238514103212682428547076
:[ 24 4128171395979674275703856551999977676615114532985796482660101370695171606061068058628
:-|| 25 4490503514653154593994888171790391155410203882196166795024427350741089979748728649713594708726872557302769860059030544234798515347871831399522962560307902130717984058775353233427641373262315637622954685896613847112512731353207673251960307641577181784460210162728903376900
>:[ 26 6326404256268962375341314423857191467014094403422416400818262089647958639442872076631144582027712607626673470721042183428656778636530024452
:{ 27 327067434247415110648800625831270231780447054491168258474180169859461557673560830270528577311056428659039392497668
:@ 28 1707371672025177167763334723112485265179840680894217387507716
>:( 29 554073785562980215465017227247350859805999403077134660534580217077888830965463104478137810948
:'-( 2a 10717345685419298345739898907239062955989543426288201658648697659470455871802103594384430744225253295339799090003181572
:'( 2b 3844659212957764301173255361616590690802154974454843970302450614408994357252
:'-) 2c 85738765483354386765919191257912503647916347410305613269189581275763646974416828755075445953802026362718392720025452548
:') 2d 30757273703662114409386042892932725526417239795638751762419604915271954857988
D-': 2e 193066536141020580302164136470251204437686055691792055134797767284510716823978805646550931167703616753827688239442675846684408073420804
D:< 2f 638803582514482637985938722326699671446185653303063005249221931372282624304643888007010225504954128458626105348
D: 30 6513106048680027648022974865388814030379641269280309252
D8 31 101767282010625432000358982271700219224681894832504836
D; 32 52104848389440221184183798923110512243037130154242473988
D= 33 3334710296924174155787763131079072783554376329871518334980
DX 34 8062834757772801319734094828124956399638895572237883755195510489639007043088023556
:-O 35 167458526334676536652185920425610358671588951972278350803847452800159342788092683232963125354305467608039012907876356
:O 36 60072800202465067205832115025259229538134452493771044576134610843949072388
:-o 37 13267431338842966983371788226620956799431546865783704518985364512972676097928094894007982561650102539906104005323704405147662831001648414716854276
:o 38 4759457577127833947434564846207944091008496681623630261662476839548057726257842008934364673202165121028
:-0 39 16908990037932745833282996436991908563415515192912516393305269712082793058780464394797060
8-0 3a 16908990037932745833282996436991908563415515192912516393305269712082793058780464394797060
>:O 3b 92061298437605180884439533457875826090662949768337659782530130027559915316565778290258379740810961922785987127587463814832979972
:-* 3c 64502678062182410557872758624999651197111187717104020665379599426585361704942567428
:* 3d 23139200950623815515509473305360238379012
;-) 3f 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
;) 40 2892400118827976939438684163170029797380
*-) 41 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
*) 42 2892400118827976939438684163170029797380
;-] 43 736490387500841447075516267663006608725303862349670620478812283647578112884440609487323312712386965678607264902605611675427012612
;] 44 264202969342699153645046819327998571303367330111090974890246487724490982787908355751940
;^) 45 1438457788087580951319367710279309782666608590130275933163395778517107001730213488515614614316939287805297916050613997699858436
:-, 46 4128171395979674275703856551999977676615116013894657322584294363301463149116324315140
;D 47 6993394368615125679158619025868739646176627428942714419231588356
:-P 48 1339668210677412293217487363404882869372711615778226806430779622401274742304741465863705002834443740864312103263010820
:P 49 480582401619720537646656920202073836305075619950168356609076886751592579076
X-P 4a 1339668210677412293217487363404882869372711615778226806430779622401274742304741465863705002834443740864312103263010820
XP 4b 480582401619720537646656920202073836305075619950168356609076886751592579076
x-p 4c 106139450710743735866974305812967654395452374926269636151882916103781408783424759152063860493200820319248832042589635241181302648013187317734834180
xp 4d 38075660617022671579476518769663552728067973452989042093299814716384461810062736071474917385617320968196
:-p 4e 106139450710743735866974305812967654395452374926269636151882916103781408783424759152063860493200820319248832042589635241181302648013187317734834180
:p 4f 38075660617022671579476518769663552728067973452989042093299814716384461810062736071474917385617320968196
:-b 50 24133317017627572537770517058781400554710756961474006891849720910563839602997349891680610310959496091356602856328580683380392349138948
:b 51 8657402899421565866640894175739857184468740673080229065203596909756120523994181001279438852
d: 52 6513106048680027648022974865388814030379641269280309252
=p 53 38075660617022671579476518769663552728067973452989042093299814716384461810062736071474917385617320968196
>:P 54 736490387500841447075516267663006608725303598146701278260241040220479322532526226322067037926487695382287897020699710518663839748
:-/ 55 2113623754741593229160374554623988570426939399114064549163158714010349132347558049349636
:/ 56 758225336750041186812214421270044291203334148
:-. 57 207303614669421359115184191040952449991117919777870383109146320515198064030126482718877866076650545526414792977894485163640282912122988497207300
>:\ 58 50611234050151699002730515390857531736112755227379331206546096717183669115542976613049156656221700861013387765768337467429254229092240195588
>:/ 59 1161976947540975084822891808156236350343871260162019107609415971405328717636882880482535666496831492
:\ 5a 33025371167837394205630852415999821412920916263886371861280810965561372848488544468996
=/ 5b 758225336750041186812214421270044291203334148
=\ 5c 33025371167837394205630852415999821412920916263886371861280810965561372848488544468996
:L 5d 117329687895439584386390849658709432691668852526896571437762911804588036
=L 5e 117329687895439584386390849658709432691668852526896571437762911804588036
:S 5f 246058189629296915275088343143461804188198717414486198583847366016815400484868
:-| 60 7293847513888772822168269599023980293348777622941735976802502615789646282521863798956655547548863258104736206545909800151084276478317422502289177374449729540
:| 61 2616539473979320885190405006650161854243576435929346067793441358875692461388486642164228618488451429272315139981316
:$ 62 88269046595092069685018437596741636
:-X 63 22475902938868452364365120473114215354165767283620319228479378773424625026990985396952005392834074880328590847857837270368260
:X 64 8062834757772801319734094828124956399638895572237883755195510489639007043088023556
:-# 65 30757273703662114409386042892932725523524850710441599209489631379406624653316
:# 66 11033630824386508710627304699592708
:-& 67 15747724136275002577605653961181555468044723563746098795258691266256191822495748
:& 68 5649218982085892459841180006191464452
O:-) 69 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
O:) 6a 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
0:-3 6b 13267431338842966983371788226620956799431542106326127399808819977829395756624898061251158122488584656200472850638276239892043942732572982687825924
0:3 6c 4759457577127833947434564846207944091008496681623630264768167818876226427440672278456466089971021774852
0:-) 6d 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
0:) 6e 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
0;^) 6f 17635441167744220073677733420687434891802896487030356826420001439272855399824227332478064740691799715855116951261424132542286393800713533574133832361923633475307938715070413175521284
>:-) 70 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
>:) 71 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
}:-) 72 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
}:) 73 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
3:-) 74 12356258313025317139338504734096077084011903131684407032848168143843669217661859524670204261772879079170965450478974953193258440804270084
3:) 75 4432590284503841723720137817978806878447995224617077284276641736623110647723704835825102487556
>;) 76 35460722276030733789761102543830455027583961796936618253966333061189046605718849544410611318788
|;-) 77 98850066504202537114708037872768616672095225053475256206345501846339744503156212400486939296710743380901705521624650127283876034609414148
|-O 78 167458526334676536652185920425610358671588951972278350803847452800159342788092683232963125354305467608039012907876356
:-J 79 5110428660115861103887509778613597371569487059700877404902571191411112755984273780302829753244185412842987454468
#-) 7a 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
%-) 7b 8062834757772801319734094828124956399638898464638002583172449928323170213117820932
%) 7c 2892400118827976939438684163170029797380
:-###.. 7d 63472263633935557923861736647125082748737134197688614613290540778155514115230551308688039019425910919616813001134916326957795000550316350938650788017945200937461476004474628334886705185455259784117223106102133685656049509651941592790179381411044907204635644645761089920625788481467539398532818999535942522921715094779750348520526769510592544772
:###.. 7e 22769557902708180570154032292525047244944529305685155554445656280981063526325050092172056931673139842713852077242156754930562874861800287931116285873505222881198972551491106610897147536510025664107567227744828946111351823651821405717420690800875100093349774665482097539926086501615885057530438321438724
<:-| 7f 11177788790790293702887103501120273414294472080999244458727694432909828650049566346015521682938653081799074785621881328429812576053504382165802153936498504910891056847057744922241561963821608276490675534388264964
',:-| 80 3894890932912594723800954614979778034738167705203999534297740046617805825001409260143039659396608186752825803082434011496463988584644917884342322616438404709718180718461226350290450773715077612074236332176364411401648796852480132979965285722014892425220
',:-l 81 13837432294794619465253598686799485174738918065898472542221995406271893447330289675331867938000869552982499765940481536206846117610229348870882129377116615066676461930445989701931533395349580971164855939208722231376387401455759135799771140
<_< 82 1658428917355370872921473528327619599928942763290765923893927134800978736248000485688913034091267225200427530628638653297304681376663135508758532
>_> 83 106139450710743735866974305812967654395452336850609019129211336627262639119872031084090434181841102412827361960232873811027499608106440672560545796

```
> 15 votes

# Answer
# Haskell, 3

Here is a start at a haskell solution.

## xD

```
"xD"

```

Try it online!

This one is just a normal string it uses the characters `"xD`

## :\]

```
':':']':[]

```

Try it online!

This is a desugared string using cons to construct a list of characters. It uses the emoticon `:]` because both `:` and `]` are already used. In total this uses the characters `':][`.

## 8)

```
drop 8(show(88,8,8,8))

```

Try it online!

This is where things start to get a little more interesting. Since we need a way to make a string without the characters `"` or `'` we use the `show` function. `show` takes something showable and makes a string out of it. Here we show the tuple `(88,8,8,8)`. This in tuple in particular ends with `8)`, the string we want, so we drop the first `8` chracters from the string using `drop 8`. The unique characters in this solution are `drop 8(shw,)`

---

If we could find some other way to make `Char`s I'd probably be able to make a 4th. `mempty`, could be used instead of `[]` in answer 2, and there are ways of extracting the `,` from answer 3.
> 7 votes

# Answer
# Charcoal, 10

These are just the ones I can do without using Charcoal's `cat`-like ability, which would allow me to add `XP` and `|-0`.

```
%)      ←)%
:(      ℅⁵⁸℅×±⁵±⁸
:-|     :¹↑¹
;]      ⮌];
<_<     <_‖Ｏ
=/      =↗÷χχ
8-0     Ｉ⊖⁹¬⁰Ｉ⁰
B^D     ↓ＥD^Bι
DX      §α³§α²³
xp      ↶⁴px

```

Try them online! I've added `Ｄ⎚` commands to separate the snippets which sort of spaces them out, although it's not perfect, as the code should really be all on one line. Explanation:

```
←)%

```

The  causes the string literal `)%` to be printed leftwards i.e. reversed.

```
℅⁵⁸℅×±⁵±⁸

```

The character code for `:` is 58. The characer code for `(` is 5 times 8. (They are both negated here in case I needed a separator later.)

```
:¹↑¹

```

The `:` is a literal. The `¹` prints a line of length 1 horizontally, which is just a `-`. The  causes the second line to be printed vertically, which gives the `|`.

```
⮌];

```

The  reverses the string literal `];`.

```
<_‖Ｏ

```

The `<_` is a string literal and the `‖Ｏ` causes the `<` to be reflected to the other side of the `_`.

```
=↗÷χχ

```

The `=` is a string literal and the `↗÷χχ` draws a line of length 10/10 i.e. 1 diagonally, i.e. `/`.

```
Ｉ⊖⁹¬⁰Ｉ⁰

```

The numbers `9-1` and `0` are cast to string and so print as digits, while the `0` in the middle is logically negated turning it into `1` which is another way of printing a `-`. (And I haven't even used it as a literal yet!)

```
↓ＥD^Bι

```

This takes the string literal `D^B` and converts it into an array, which would normally print vertically, however the print direction is overriden to vertical which results in... reversed output again!

```
§α³§α²³

```

This looks up the characters at positions 3 and 23 in the upper case alphabet (0-indexed).

```
↶⁴px

```

The `↶⁴` rotates the print direction through 180° thus causing the string literal `px` to be printed reversed yet again.
> 7 votes

# Answer
# Jelly, 6

<sup>+1 to come?? dylnan suggested the use of  to free up `Ȯ`, but can it be used?</sup>

Six full programs:

;\] `“;]`
xp `⁾xp`
;D `⁽8Ạb⁹Ọ`
:0 `”:®ṭ`
XP `24,16ịØA`
8-0 `7‘.NṾṖ⁺`

31 distinct bytes used, confirmation here.
> 5 votes

# Answer
# Ruby, 7

=\ Try it online! A string literal

```
'=\\'

```

\>\_\> Try it online! Another string literal

```
">_>"

```

:p Try it online! Prints the `:p` symbol including the syntax (`:`) since it's using the `p` method

```
p:p

```

%) Try it online! Yet another string literal

```
%{%)}

```

XP Try it online! Here document notation (basically a multiline string literal)

```
<<A
XP
A

```

;\] Try it online! Array of 2 characters (`':'` and `']'`) joined with `'-'`

```
[?;,?]]*?-

```

D8 Try it online! The source string of a regular expression

```
/D8/.source

```

\__

Honorable mention Try it online! Executes the code in bash, returns `emoticon` with a trailing `\n`

```
`echo D8`

```
> 5 votes

# Answer
# Python 2, 4

This answer is a pretty simple start. For the first two we just use python's two different string syntaxes. For the third we use the same method as my Haskell answer where we make a tuple get its string representation and slice it up. For the last part we use the `chr` function to make the characters `:` and `)` and add them together.

## xD

```
"xD"

```

## =\

```
'=\\'

```

## 8)

```
`88,8,8`[8:]

```

## :)

```
chr(11+11+11+11+11+1+1+1)+chr(11+11+11+1+1+1+1+1+1+1+1)

```
> 3 votes

# Answer
# , 4

```
`!`<-`qu\157\164e`;!B^D
intToUtf8(c(88,80))
">_>"
'=]'

```

Try it online!

A first attempt at an R solution. The need to use brackets for any function call seriously reduces the possibilities. The first snippet is a call to `quote` which simply returns its argument \- Thanks @BLT for showing me a way to do it without parenthesis, allowing me to use `intToUtf8` on the following line.

I used another trick that @Giuseppe mentioned in a comment to another question once to spell `quote` without `o` and `t`.
> 3 votes

# Answer
# Fission, 3

### |;-)

```
R"|;-)";

```

Try it online!

### XP

```
V!P'!X'L

```

Try it online!

### :o

```
/t<O/oO
U{\ {

```

Try it online!

There are only 3 ways to output something in Fission, so here we are
> 2 votes

# Answer
# Javascript, 5

Three trivial ones, then two interesting ones:

# xD

```
"xD"

```

# XP

```
'XP'

```

# \<\_\<

```
`<_<`

```

# :3

```
[[a=>0?0:0][0]+[]][0][6]+3

```

No characters for string literals left for the fourth one, so we get strings by concatenating with an array. The colon comes from writing a function which uses a colon, then converting it to a string.

# 8)

```
String((function(){(8)})).slice(12,14)

```

This one works very similarly to the fourth one, but uses slightly different methods to do everything.

Thanks to @steve-bennett for suggesting using the `String` constructor and `.slice` as an alternative to concatenating with arrays, and indexing. Managed to squeeze out +1 point from it.
> 2 votes

# Answer
## Perl 5, 6

### :-)

```
':-)'

```

### :)

```
v58.41

```

### :-3

```
"\x3a\x2d\x33"

```

### =\]

```
<<A;
=]
A

```

### B^D

```
q*B^D*

```

### XP

```
`echo XP`

```

Try it online.
> 2 votes

---
Tags: string, code-challenge, restricted-source
---


title: Solve sin(θ) = x in the range a ≤ θ ≤ b

text:
# Question
Title: Solve sin(θ) = x in the range a ≤ θ ≤ b
## Challenge

Given a number, `x` where `-1 ≤ x ≤ 1`, and the integers `a` and `b`, where `b > a`, solve the equation `sin(θ) = x` for `θ`, giving *all* solutions in the range `a° ≤ θ ≤ b°`.

## Rules

`x` will have a maximum of three decimal places of precision. The output, `θ`, must also be to three decimal places, no more, no less.

Your output may be as a list or separated output.

You may use built-in trig functions.

You may not use radians for `a` and `b`.

You will never be given invalid input.

Output may be in any order.

## Examples

```
x, a, b => outputs
0.500, 0, 360 => 30.000, 150.000
-0.200, 56, 243 => 191.537
0.000, -1080, 1080 => 0.000, 180.000, 360.000, 540.000, 720.000, 900.000, 1080.000, -1080.000 -900.000, -720.000, -540.000, -360.000, -180.000

```

## Winning

Shortest code in bytes wins.

# Answer
> 2 votes
# APL, ~~51~~ ~~46~~ ~~40~~ 39 bytes

*3 bytes saved thanks to @KritixiLithos*

*~~6~~ 7 bytes saved thanks to @Adám*

```
{3⍕⍵/⍨1E¯6>|⎕-1○○⍵÷180}⊢+1E3÷⍨(⍳1001×-)

```

Called as a dyad with `a` as left argument and `b` as right argument, prompts for `x`.

Requires `⎕IO←0`.

**How?**

```
                         ⊢+1E3÷⍨(⍳1001×-)  ⍝ build the range a to b with step of 0.001
                                  1001×-   ⍝ 1001 * (b - a)
                                 ⍳         ⍝ range
                           1E3÷⍨           ⍝ divide every element by 1000
                         ⊢+                ⍝ add a back

{3⍕⍵/⍨1E¯6>|⎕-1○○⍵÷180}                  ⍝ filter the solutions
                  ○⍵÷180                   ⍝ convert to radian - π * ⍵ / 180
                1○                          ⍝ compute sine
             |⎕-                           ⍝ distance from x
       1E¯6>                                ⍝ small enough
    ⍵/⍨                                    ⍝ compress with the original list
 3⍕                                        ⍝ format to 3 decimal places

```

# Answer
> 3 votes
## Mathematica, 60 bytes

```
NumberForm[t/.NSolve[Sin[t/180Pi]==#&&#2<=t<=#3,{t}],{9,3}]&

```

input

> \[0, -1080, 1080\]

output

> {-1080.000,-900.000,-720.000,-540.000,-360.000,-180.000,0.000,180.000,360.000,540.000,720.000,900.000,1080.000}

# Answer
> 3 votes
# Fortran 95 (gfortran), 180 bytes

```
#define G >=i)write(*,'(f9.3)')
#define H read(*,*)
program a
H x
H i
H j
o=ASIN(x)*57.2957
p=o-180+o
q=o-360*999
do
r=q-p
if(r<=j.and.r G r
if(q>=j)exit
if(q G q
q=q+360
enddo
end

```

Structure ungolfed:

```
program a
        implicit none
        real :: x
        integer :: i
        integer :: j
        real :: o
        real :: r
        real :: q
        real :: p

        read(*,*) x
        read(*,*) i
        read(*,*) j

        o=ASIN(x)*57.2957
        p=o-180+o
        q=o-360*999

        do
                r=q-p
                if(r<=j.and.r >=i) then
                        write(*,'(f9.3)') r
                endif
                if(q>=j) then
                        exit
                endif
                if(q >=i) then
                        write(*,'(f9.3)') q
                endif
                q = q + 360
        end do
end program a

```

# Answer
> 1 votes
# PHP\>=7.1, 88 Bytes

```
for([,$s,$f,$t]=$argv;$f<=$t;$f+=.001)round(sin(deg2rad($f)),5)!=$s?:printf("%.3f_",$f);

```

Online Version

# Answer
> 0 votes
# Python 2, 100 bytes

```
from math import*
x,a,b=input()
while a<=b:
    if round(sin(pi*a/180),5)==x:print a
    a=round(a+.001,3)

```

**Try it online**

# Answer
> 0 votes
# Axiom, ~~266~~  ~~215~~ 210 bytes

```
g(y,a,b)==(r:List Float:=[];t:=y+truncate((a-y)/360)*360;repeat(t>b=>break;if t>=a then r:=append(r,[t]);t:=t+360);r)
f(x,a,b)==(abs(x)>1 or a>b=>[];y:=asin(x)*180/%pi;z:=180-y;sort(append(g(y,a,b),g(z,a,b))))

```

ungolf and test

```
-- g/180=r/pi  => r=pi*g/180
--y+k*360=a
--    a-y
-- k=------
--    360
-- find all angles of the same class of angles [y+k*360] in interval [a,b]
gg(y,a,b)==
   r:List Float:=[]
   t:=y+truncate((a-y)/360)*360 --truncate(1.9)=1, truncate(-3.1)=-4 is ok
   repeat
     t>b=>break
     if t>=a then r:=append(r,[t])
     t:=t+360
   r

-- ff returns the list of solution y of sin(y)=x with y in the interval [a,b]
ff(x,a,b)==
   abs(x)>1 or a>b =>[]
   y:=asin(x)*180/%pi -- z and y are the only 2 solutions in one 360 Len interval
   z:=180-y
   sort(append(gg(y,a,b),gg(z,a,b)))

(6) -> f(0.5, 0, 360)
   (6)  [30.0,150.0]
                                                         Type: List Float
(7) -> f(-0.2, 56, 243)
   (7)  [191.5369590328 1548769]
                                                         Type: List Float
(8) -> f(0.0, -1080, 1080)
   (8)
   [- 1080.0, - 900.0, - 720.0, - 540.0, - 360.0, - 180.0, 0.0, 180.0, 360.0,
    540.0, 720.0, 900.0, 1080.0]

(14) -> m:=f(-0.1, -2035, -243)
   (14)
   [- 1974.2608295227 33214, - 1805.7391704772 66786, - 1614.2608295227 33214,
    - 1445.7391704772 66786, - 1254.2608295227 33214, - 1085.7391704772 66786,
    - 894.2608295227 332137, - 725.7391704772 667863, - 534.2608295227 332137,
    - 365.7391704772 667863]
                                                         Type: List Float
(15) -> map(x+->sin(%pi*x/180), m)
   (15)
   [- 0.0999999999 9999999987, - 0.1000000000 0000000016,
    - 0.0999999999 9999999986 2, - 0.1000000000 0000000028,
    - 0.0999999999 9999999985 4, - 0.1000000000 0000000018,
    - 0.0999999999 999999999, - 0.1000000000 0000000019,
    - 0.0999999999 9999999989 2, - 0.1000000000 0000000014]
                                                         Type: List Float

```

# Answer
> 0 votes
# , 74 bytes

```
function(x,a,b,u=seq(a,b,.001))sprintf("%.3f",u[abs(sinpi(u/180)-x)<1e-6])

```

Try it online!

The tolerance `1e-6` was chosen to fit the second test case, so is somewhat arbitrary. This answer takes advantage of R's vectorized functions.

---
Tags: code-golf, math, number, trigonometry
---


title: The Spain license plates game

text:
# Question
Title: The Spain license plates game
> This question is based on a question I asked in Spanish language. Yes, I asked for an algorithm in Spanish Language. :)

In Spain, current license plates have this pattern:

> 1234 XYZ

where XYZ are three consonants taken from the full set of Spanish consonants (except the 'Ñ', I think).

Sometimes, when traveling with my wife, we use to play a game. When we see a license plate, we take its three consonants and try to form a word that contains those three consonants, appearing in the same order as in the license plate. Examples (in Spanish):

```
BCD
    BoCaDo (valid)
    CaBezaDa (not valid)
FTL
    FaTaL (valid)
    FLeTar (not valid)
FTR
    FleTaR (valid, wins)
    caFeTeRa (valid, loses)

```

The winner is the one who uses the least number of characters, as you can see in the last example.

### The challenge

Write the shortest program or function that receives a list of words and a set of three consonants and finds the shortest word in the list that contains the three consonants in the same order. For the purposes of this game, case does not matter.

* The input for the word list (first parameter) will be an array of your language `string` type. The second parameter (the three consonants) will be another `string`. If it's better for your language, consider the `string` with the three consonants the last item of the whole list of parameters. The output will be another `string`.
* The words in the word list won't be invented or infinite words, they will word that appear in any standard dictionary. If you need a limit, suppose no word in the word list will be longer than 50 characters.
* If there are several words with the same lenght that could be the valid answer, you can return any one of them. Just make sure you return just one word, or an empty string if no words match the pattern of three consonants.
* You can repeat consonants in the group, so valid inputs for the three consonants are both `FLR` and `GGG`.
* The Spanish consonants are exactly the same as English, with the addition of the "Ñ". The vowels are the same with the adition of the stressed vowels: "áéíóúü". There won't be any other kind of marks such as "-" or "'".
* You can suppose the case will always be the same in both the word list and the three consonants.

If you want to test your algorithm with a real collection of Spanish words, you can download a file (15.9 MB) from Dropbox with more than a million words.

### Test cases

```
Input: 'psr', {'hola' 'repasar' 'pasarais' 'de' 'caída' 'pequeñísimo' 'agüeros'}
Output: 'repasar'

Input: 'dsd', {'dedos' 'deseado' 'desde' 'sedado'}
Output: 'desde'

Input: 'hst', {'hastío' 'chest'}
Output: 'chest'

```

This is , so may the shortest program that helps me to always beat my wife wins! :)

# Answer
# 05AB1E, ~~10~~ 8 bytes

Saved 2 bytes thanks to *Leo*

```
ʒæså}éR`

```

Try it online!

**Explanation**

```
ʒ         # filter list, keep only members for which the following is true
  så      # input is in the
 æ        # powerset of the current word
    }     # end filter
     é    # sort by length
      R   # reverse
       `  # push separately (shortest on top)

```

I would have used `head` at the end saving a byte but that would output an empty list if there isn't a match.
> 7 votes

# Answer
# PHP, 111 bytes

```
$y=array_map(str_split,preg_grep("#".chunk_split($_GET[1],1,".*")."#",$_GET[0]));sort($y);echo join($y[0]??[]);

```

Try it online!
> 6 votes

# Answer
# MATL, ~~30~~ 29 bytes

```
xtog!s2$S"1G!'.*'Yc!@gwXXn?@.

```

Try it online!

### Explanation

```
x         % Implicitly take first input (string with three letters). Delete.
          % Gets copied into clipboard G, level 1
t         % Implicitly take second input (cell array of strings defining the
          % words). Duplicate
o         % Convert to numeric array of code points. This gives a matrix where
          % each string is on a row, right-padded with zeros
g         % Convert to logical: nonzeros become 1
!s        % Sum of each row. This gives the length of each word
2$S       % Two-input sort: this sorts the array of strings according to their
          % lengths in increasing order
"         % For each word in the sorted array
  1G      %   Push first input, say 'xyz'
  !       %   Transpose into a column vector of chars
  '.*'Yc  %   Concatenate this string on each row
  !       %   Transpose. This gives a char array which, when linearized in
          %   column-major order, corresponds to 'x.*y.*z.*'
  @g      %   Push corrent word
  w       %   Swap
  XX      %   Regexp matching. Gives a cell array with substrings that match
          %   the pattern 'x.*y.*z.*'
  n       %   Number of matchings
  ?       %   If non-zero
    @     %     Push cell array with current word, to be displayed as output
    .     %     Break loop
          %   Implicit end (if)
          % Implicit end (for)
          % Implicitly display stack

```
> 6 votes

# Answer
# Jelly,  ~~12 11~~  10 bytes

```
ŒPċðÐfLÞḣ1

```

A full program that accepts a list of lists of lowercase characters (the words) and a list of lowercase characters (the letters) and prints the first of the shortest words which contain a sub-sequence equal to the letters (or nothing if none exist).

**Try it online!**

### How?

```
ŒPċðÐfLÞḣ1 - Main link: words; characters
   ðÐf     - filter keep words for which this is truthy:
ŒP         -   the power-set (all sub-sequences of the word in question)
  ċ        -   count (how many times the list of characters appears)
           - ...note 0 is falsey while 1, 2, 3, ... are truthy
       Þ   - sort by:
      L    -  length
        ḣ1 - head to index 1 (would use Ḣ but it yields 0 for empty lists)
           - implicit print (smashes together the list of lists (of length 1))

```
> 5 votes

# Answer
# Pyth - ~~22~~ ~~21~~ ~~19~~ ~~12~~ 11 bytes

```
h+f/yTQlDEk

```

-1 Thanks to Maltysen.

Takes 2 lines as input. 1st is the 3-letter string (lowercase), and the 2nd is a lowercase list of words.

Try it here

Explanation:

```
h+f/yTQlDEk
       lDE   # Sort word list by length
  f          # Filter elements T of the word list...
    yT       # by taking the powerset...
   /  Q      # and checking whether the 3-letter string Q is an element of that.
 +        k  # Add empty string to the list (in case no results found)
h            # And take the first result (the shortest)

```

Old 19-byte solution:

```
h+olNf/-T"aeiou"QEk

```
> 5 votes

# Answer
# Brachylog v2, 11 bytes

```
tlᵒ∋.&h⊆.∨Ẹ

```

Try it online!

Function submission. (The TIO link has a command-line argument to run a function as though it were a full program.)

## Explanation

Just a direct translation of the specification again…

```
tlᵒ∋.&h⊆.∨Ẹ
t            The last element of {standard input}
   ∋.        contains the return value as an element
     &       and
      h      the first element of {standard input}
       ⊆.    is a subsequence of the return value
         ∨   alternate behaviour if no solution is found:
          Ẹ  return empty string
  ᵒ          tiebreak override: favour answers that have a low
 l           length

```

You can actually almost answer with `h⊆.&t∋` – swapping the evaluation order means that Brachylog will pick the shortest answer by default (as the first constraint it sees is , which has the rather convenient "shortest" as a default tiebreak) – but in that case, Brachylog's evaluation algorithm would unfortunately go into an infinite loop if the answer is not actually found. So almost half the answer is dedicated to handling the case of there being no appropriate answer. Even then, the `lᵒ` tiebreak override (which is technically a sort, making use of 's default tiebreak of preferring elements nearer the start of the list) is only two bytes; the other three come from the need to output an empty string specifically when the output is not found, as opposed to Brachylog's default "no solutions" sentinel value (because the final `.` would be implicit if we didn't have to follow it with ).

Interestingly, there's a feature that was previously implemented in Brachylog that would have saved a byte here. At one point, you could extract elements from the input argument using `?₁`, `?₂`, etc. syntax; that would allow you to rearrange the program to `tlᵒ∋.⊇?₁∨Ẹ`, which is only 10 bytes. Unfortunately, the implementation that was used didn't actually work (and caused many otherwise working programs to break), so it was reverted. You can think of the program as being "conceptually" 10 bytes long, though.
> 5 votes

# Answer
# Haskell ~~129~~ ~~125~~ 74 bytes

```
import Data.List
l#w=sortOn length[p|p<-w,isInfixOf l$filter(`elem`l)p]!!0

```

CREDIT to @nimi
> 4 votes

# Answer
## JavaScript (ES6), ~~77~~ ~~75~~ 72 bytes

Takes the 3 consonants `c` and the list of words `l` in currying syntax `(c)(l)`. Both inputs are expected in the same case.

```
c=>l=>l.map(w=>x=!w.match([...c].join`.*`)||!x[w.length]&&x?x:w,x='')&&x

```

### Test cases

```
let f =

c=>l=>l.map(w=>x=!w.match([...c].join`.*`)||!x[w.length]&&x?x:w,x='')&&x

console.log(f('psr')(['hola', 'repasar', 'pasarais', 'de', 'caída', 'pequeñísimo', 'agüeros'])) // 'repasar'
console.log(f('dsd')(['dedos', 'deseado', 'desde', 'sedado'])) // 'desde'
```
> 3 votes

# Answer
## Perl, 53 bytes

**48 bytes code + 5 for `-paF`.**

```
$"=".*";($_)=sort{$a=~y///c-length$b}grep/@F/,<>

```

This takes advantage of the fact that lists interpolated into the `m//` operator utilise the `$"` variable which changes the initial input string from `psr` to `p.*s.*r` which is then matched for each additional word and is sorted on `length`.

Try it online!
> 3 votes

# Answer
### R, 101 bytes

First time golfing! I'm sure this can be condensed somehow

Takes the string x and a character vector y of possible inputs

```
w=pryr::f((b=y[sapply(gsub(paste('[^',x,']'),'',y),function(l)regexpr(x,l))>0])[which.min(nchar(b))])

```

Try it online!

Edit: My version was 135, thanks Scrooble for the -34!
> 3 votes

# Answer
# Retina, 58 bytes

```
O#$^`¶.+
$.&
s`^((.)(.)(.).*¶(?-s:(.*\2.*\3.*\4.*)))?.*
$5

```

Try it online! Takes the three consonants on one line and then the list of words on all subsequent lines. Explanation: `O` sorts the list `¶.+` excluding the first line `#` numerically `$` keyed by `$.&` length. A match is then sought for a line that includes the three consonants in order. If a suitable line exists than the last, i.e. shortest, such line becomes the output, otherwise the output is empty. The `?-s:` temporarily turns off the effect of `s`` so that only one line is matched.
> 2 votes

# Answer
# Pip, 17 bytes

```
@:qJ`.*`N_FI#_SKg

```

Takes the word list as command-line arguments, and the consonants from stdin. Try it online!

### Explanation

```
                   g is list of cmdline args (implicit)
              SKg  Sort g using this key function:
            #_      Length of each item (puts shortest words first)
          FI       Filter on this function:
  q                 Line of input
   J`.*`            joined on regex .* (turns "psr" into `p.*s.*r`)
        N_          Count regex matches in item (keeps only words that match)
@:                 Get first element of result (using : meta-operator to lower precedence)
                   If the list is empty, this will give nil, which results in empty output

```
> 1 votes

# Answer
# Java 8, ~~132~~ 126 bytes

```
s->a->{String r="";for(String x:a)r=(x.length()<r.length()|r.isEmpty())&x.matches(r.format(".*%s.*%s.*%s.*",s))?x:r;return r;}

```

-6 bytes thanks to *@Nevay*.

**Explanation:**

Try it online.

```
s->a->{              // Method with two String-array parameters and String return-type
  String r="";       //  Result-String, starting empty
  for(String x:a)    //  Loop over the words
    r=(x.length()<r.length()
                     //   If a word is smaller than the current `r`,
      |r.isEmpty())  //   or `r` is still empty
      &x.matches(r.format(".*%s.*%s.*%s.*",s))?
                     //   And if the word is valid
       x             //    Change `r` to the current word
      :              //   Else:
       r;            //    Leave `r` the same
  return r;}         //  Return the result

```
> 1 votes

# Answer
# Python, 77 bytes

```
import re
lambda s,a:min([x for x in a if re.search('.*'.join(s),x)],key=len)

```

Try it online!
> 0 votes

# Answer
# MATL, ~~28~~ ~~27~~ 26 bytes

```
x"l1G@g3XNXm/@gn*v]&X<2Gw)

```

Try it online!

`x` \- Implicitly take first input (string with three letters) and delete it. Gets copied into clipboard G, level 1 automatically (this part was inspired by @Luis Mendo's answer).

`"` \- Implicitly take second input (cell array of words), iterate through it.

`l` \- Push 1 to be used later

`1G` \- Push first input (say 'psr')

`@g` \- Push the current word as array

`3XN` \- `nchoosek` \- Get all combinations of 3 letters from the word

`Xm` \- See if the license plate code 'psr' is one of these combinations. Returns 0 for false and 1 for true.

`/` \- Dividing the 1 (that we pushed earlier) by this result. Changes the 0s to `Inf`s

`@gn` \- Get the length of the current word

`*` \- Multiply the length by the division result. Returns the length as it is when word contains the 3 characters, otherwise returns `Inf`

`v` \- vertically concatenate these results into a single array

`]` \- close loop

`&X<` \- get the index of the minimum value from that array i.e. the index where the word containing the letters and with minimum length was found

`2G` \- Push the second input again

`w` \- Bring the min index back on top of stack

`)` \- Index into array of words with the min index, returning the valid word with minimum length

(Implicit output.)

---

Older:

```
x"@g1Gy3XNXm1w/wn*v]&X<2Gw)

x"@g1Gy3XNXm1w/wn*v]2Gw2$S1)

```
> 0 votes

---
Tags: code-golf, string, search
---


title: Small Ramsey Numbers

text:
# Question
Title: Small Ramsey Numbers
Background: the Ramsey number \\$R(r,s)\\$ gives the minimum number of vertices \\$v\\$ in the complete graph \\$K\_v\\$ such that a red/blue edge coloring of \\$K\_v\\$ has at least one red \\$K\_r\\$ or one blue \\$K\_s\\$. Bounds for larger \\$r, s\\$ are very difficult to establish.

Your task is to output the number \\$R(r,s)\\$ for \\$1 \le r,s \le 5\\$.

## Input

Two integers \\$r, s\\$ with \\$1 \le r \le 5\\$ and \\$1 \le s \le 5 \\$.

## Output

\\$R(r,s)\\$ as given in this table:

```
  s   1    2    3    4      5
r +--------------------------
1 |   1    1    1    1      1
2 |   1    2    3    4      5
3 |   1    3    6    9     14
4 |   1    4    9   18     25
5 |   1    5   14   25  43-48

```

Note that \\$r\\$ and \\$s\\$ are interchangeable: \\$R(r,s) = R(s,r)\\$.

For \\$R(5,5)\\$ you may output any integer between \\$43\\$ and \\$48\\$, inclusive. At the time of this question being posted these are the best known bounds.

# Answer
# JavaScript (ES6), ~~51~~ 49 bytes

Takes input in currying syntax `(r)(s)`.

```
r=>s=>--r*--s+[9,1,,13,2,,3,27,6][r<2|s<2||r*s%9]

```

Try it online!

### How?

As a first approximation, we use the formula:

$$(r-1)(s-1)$$

```
 0  0  0  0  0
 0  1  2  3  4
 0  2  4  6  8
 0  3  6  9 12
 0  4  8 12 16

```

If we have \\$\min(r,s)\<3\\$, we simply add \\$1\\$:

```
 1  1  1  1  1
 1  2  3  4  5
 1  3  -  -  -
 1  4  -  -  -
 1  5  -  -  -

```

Otherwise, we add a value picked from a lookup table whose key \\$k\\$ is defined by:

$$k=(r-1)(s-1)\bmod9$$

```
 k:                    table[k]:           (r-1)(s-1):         output:
 -  -  -  -  -         -  -  -  -  -       -  -  -  -  -       -  -  -  -  -
 -  -  -  -  -         -  -  -  -  -       -  -  -  -  -       -  -  -  -  -
 -  -  4  6  8   -->   -  -  2  3  6   +   -  -  4  6  8   =   -  -  6  9 14
 -  -  6  0  3         -  -  3  9 13       -  -  6  9 12       -  -  9 18 25
 -  -  8  3  7         -  -  6 13 27       -  -  8 12 16       -  - 14 25 43

```
> 7 votes

# Answer
# JavaScript (Node.js), ~~56~~ 55 bytes

```
f=(x,y)=>x<2|y<2||f(x,y-1)+f(x-1,y)-(x*y==12)-7*(x+y>8)

```

Try it online! I noticed that the table resembles Pascal's triangle but with correction factors. Edit: Saved 1 byte thanks to @sundar.
> 5 votes

# Answer
# Jelly,  ~~17~~  16 bytes

```
’ScḢƊ_:¥9“ ı?0‘y

```

**Try it online!** Or see a test-suite.

Replace the `0` with `+`, `,`, `-`, `.`, or `/` to set \\$R(5,5)\\$ equal to \\$43\\$, \\$44\\$, \\$45\\$, \\$46\\$, or \\$47\\$ respectively (rather than the \\$48\\$ here).

### How?

Since \\$R(r,s)\leq R(r-1,s)+R(r,s-1)\\$ we may find that:

$$R(r,s)\leq \binom{r+s-2}{r-1}$$

This is `’ScḢƊ` and would produce:

```
 1  1  1  1  1
 1  2  3  4  5
 1  3  6 10 15
 1  4 10 20 35
 1  5 15 35 70

```

If we subtract one for each time nine goes into the result we align three more with our goal (this is achieved with `_:¥9`):

```
 1  1  1  1  1
 1  2  3  4  5
 1  3  6  9 14
 1  4  9 18 32
 1  5 14 32 63

```

The remaining two incorrect values, \\$32\\$ and \\$63\\$ may then be translated using Jelly's `y` atom and code-page indices with `“ ı?0‘y`.

```
’ScḢƊ_:¥9“ ı?0‘y - Link: list of integers [r, s]
’                - decrement              [r-1, s-1]
    Ɗ            - last 3 links as a monad i.e. f([r-1, s-1]):
 S               -   sum                  r-1+s-1 = r+s-2
   Ḣ             -   head                 r-1
  c              -   binomial             r+s-2 choose r-1
        9        - literal nine
       ¥         - last 2 links as a dyad i.e. f(r+s-2 choose r-1, 9):
      :          -   integer division     (r+s-2 choose r-1)//9
     _           -   subtract             (r+s-2 choose r-1)-((r+s-2 choose r-1)//9)
         “ ı?0‘  - code-page index list   [32,25,63,48]
               y - translate              change 32->25 and 63->48

```
> 4 votes

# Answer
# Python 2, 62 bytes

```
def f(c):M=max(c);u=M<5;print[48,25-u*7,3*M+~u-u,M,1][-min(c)]

```

Try it online!

---

### Python 2, 63 bytes

```
def f(c):M=max(c);print[48,M%2*7+18,3*~-M+2*(M>4),M,1][-min(c)]

```

Try it online!

This is ridiculous, I will soon regret having posted this... But eh, ¯\\\_(ツ)\_/¯. Shaved off 1 byte thanks to our kind Jonathan Allan :). Will probably be outgolfed by about 20 bytes shortly though...
> 2 votes

# Answer
# Julia 0.6, ~~71~~ ~~61~~ ~~59~~ 57 bytes

```
A->((r,s)=sort(A);r<3?s^~-r:3r+(s^2-4s+3)*((r==s)+r-2)-3)

```

Try it online!

### Ungolfed (well, a bit more readable):

```
function f_(A)
  (r, s) = sort(A)

  if r < 3
    result = s^(r-1)
  else
    result = 3*r +
               (s^2 - 4*s + 3) * ((r == s) + r - 2) -
               3
  end

  return result
end

```

### What does it do?

Takes input as array `A` containing r and s. Unpacks the array into r and s with the smaller number as r, using `(r,s)=sort(A)`.

If r is 1, output should be 1. If r is 2, output should be whatever s is.
\\$ s^{r - 1} \\$ will be \\$ s^0 = 1 \\$ for r=1, and \\$ s^1 = s \\$ for r = 2.
So, `r<3?s^(r-1)` or shorter, `r<3?s^~-r`

For the others, I started with noticing that the output is:

* for r = 3, \\$ 2\times3 + \[0, 3, 8\] \\$ (for s = 3, 4, 5 respectively).
* for r = 4, \\$ 2\times4 + \ \ \[10, 17\] \\$ (for s = 4, 5 respectively)
* for r = 5, \\$ 2\times5 + \ \ \ \ \ \[35\] \\$ (for s = 5)

(I initially worked with f(5,5)=45 for convenience.)

This looked like a potentially usable pattern - they all have `2r` in common, 17 is 8\*2+1, 35 is 17\*2+1, 10 is 3\*3+1. I started with extracting the base value from \[0, 3, 8\], as `[0 3 8][s-2]` (this later became the shorter `(s^2-4s+3)`).

Attempting to get correct values for r = 3, 4, and 5 with this went through many stages, including

```
2r+[0 3 8][s-2]*(r>3?3-s+r:1)+(r-3)^3+(r>4?1:0)

```

and

```
2r+(v=[0 3 8][s-2])+(r-3)*(v+1)+(r==s)v

```

Expanding the latter and simplifying it led to the posted code.
> 2 votes

# Answer
# x86, ~~49~~ 37 bytes

Not very optimized, just exploiting the properties of the first three rows of the table. While I was writing this I realized the code is basically a jump table so a jump table could save many bytes. Input in `eax` and `ebx`, output in `eax`.

-12 by combining cases of `r >= 3` into a lookup table (originally just `r >= 4`) and using Peter Cordes's suggestion of `cmp`/`jae`/`jne` with the flags still set so that `r1,r2,r3` are distinguished by only one `cmp`! Also indexing into the table smartly using a constant offset.

```
start:
        cmp     %ebx, %eax
        jbe     r1
        xchg    %eax, %ebx              # ensure r <= s

r1:
        cmp     $2, %al
        jae     r2                      # if r == 1: ret r
        ret

r2:
        jne     r3                      # if r == 2: ret s
        mov     %ebx, %eax
        ret

r3:
        mov     table-6(%ebx,%eax),%al  # use r+s-6 as index
        sub     %al, %bl                # temp = s - table_val
        cmp     $-10, %bl               # equal if s == 4, table_val == 14
        jne     exit
        add     $4, %al                 # ret 18 instead of 14

exit:
        ret

table:
        .byte   6, 9, 14, 25, 43

```

Hexdump

```
00000507  39 d8 76 01 93 3c 02 73  01 c3 75 03 89 d8 c3 8a  |9.v..<.s..u.....|
00000517  84 03 21 05 00 00 28 c3  80 fb f6 75 02 04 04 c3  |..!...(....u....|
00000527  06 09 0e 19 2b                                    |....+|

```
> 2 votes

# Answer
# Python 2, 70 bytes

```
f=lambda R,S:R<=S and[1,S,[6,9,14][S-3],[18,25][S&1],45][R-1]or f(S,R)

```

Try it online!
> 1 votes

# Answer
# MATL, ~~25~~ 21 bytes

```
+2-lGqXnt8/k-t20/k6*-

```

Try it on MATL Online

Attempt to port Jonathan Allan's Jelly answer to MATL.

`+2-lGqXn` \- same as that answer: compute \\$ \binom{r+s-2}{r-1} \\$

`t8/k` \- duplicate that, divide by 8 and floor

`-` \- subtract that from previous result (We subtract how many times 8 goes in the number, instead of 9 in the Jelly answer. The result is the same for all but the 35 and 70, which here give 31 and 62.)

`t20/k` \- duplicate that result too, divide that by 20 and floor (gives 0 for already correct results, 1 for 31, 3 for 62)

`6*` \- multiply that by 6

`-` \- subtract that from the result (31 - 6 = 25, 62 - 18 = 44)

---

Older:

```
+t2-lGqXntb9<Q3w^/k-t20>+

```

Try it on MATL Online
> 1 votes

# Answer
# Python 3, 74 bytes

```
lambda *a:[[1]*5,[2,3,4,5],[6,9,14],[18,25],[43]][min(a)-1][max(a)-min(a)]

```

Try it online!
> 0 votes

# Answer
# Proton, 52 bytes

Near-port of my Python answer.

```
c=>[48,(M=max(c))%2*7+18,3*M-(M>4?1:3),M,1][-min(c)]

```

Try it online!
> 0 votes

# Answer
# Java 8, 62 bytes

```
(r,s)->--r*--s+new int[]{9,1,0,13,2,0,3,27,6}[r<2|s<2?1:r*s%9]

```

Lambda function, port of Arnauld's JavaScript answer. Try it online here.

# Java, 83 bytes

```
int f(int x,int y){return x<2|y<2?1:f(x,y-1)+f(x-1,y)-(x*y==12?1:0)-7*(x+y>8?1:0);}

```

Recursive function, port of Neil's JavaScript answer. Try it online here.
> 0 votes

# Answer
# C (gcc), 57 bytes

```
f(x,y){x=x<2|y<2?:f(x,y-1)+f(x-1,y)-(x*y==12)-7*(x+y>8);}

```

Recursive function, port of Neil's JavaScript answer. Try it online here.

# C (gcc), 63 bytes

```
f(r,s){r=--r*--s+(int[]){9,1,0,13,2,0,3,27,6}[r<2|s<2?:r*s%9];}

```

Port of Arnauld's JavaScript answer. Try it online here.
> 0 votes

---
Tags: code-golf, integer, graph-theory
---


title: Socket - Plug compatibility

text:
# Question
Title: Socket - Plug compatibility
Traveling with electronics is always fun, especially when you need an adapter to charge them. Your challenge is to make planning a trip a little easier by checking if a given plug will be compatible with a given socket.

### Challenge

Given a plug type and a socket type, return a value that indicates whether they will work together or not.

### Compatibility table

```
Socket  Accepted plugs  |  Plug  Accepting Sockets
A       A               |  A     A, B
B       A, B            |  B     B
C       C               |  C     C, D, E, F, H, J, K, L, N, O
D       C, D, E, F      |  D     D
E       C, E, F         |  E     D, E, F, H, K, O
F       C, E, F         |  F     D, E, F, H, K, O
G       G               |  G     G
H       C, E, F, H      |  H     H
I       I               |  I     I
J       C, J            |  J     J
K       C, E, F, K      |  K     K
L       C, L            |  L     L
M       M               |  M     M
N       C, N            |  N     N
O       C, E, F, O      |  O     O

```

The tables show the same information, only transposed.

For reference.

### Input

* The input will be given as two uppercase or two lowercase letters (you choose).
* Inputs will always be `/[A-O]/` (or `/[a-o]/`), there's no need to handle invalid inputs.
* You may accept the two inputs in any order (please specify which).
* Input can be taken in any reasonable format (string, stdin, array, ...).
* If you take both inputs in a single string, they can be separated by no more than one character and there must be nothing surrounding them
* Good inputs: `"G,K"`, `"EF"`, `"a b"`, `['l', 'o']`
* Bad inputs: `"K l"`, `"f(O)(I)"`, `[1,5]`

### Output

* Output can be returned in any reasonable format.
* Output must be either `truthy`/`falsy` or one of 2 constant values
* Good outputs: `false`/`any positive number`, `1`/`2`, `'T'`/`'F'`
* Bad outputs: `an even number`/`an odd number`, `1`/`more than 1`

### Examples

Using the format `socket`, `plug` =\> `true` / `false`.

```
A, A => true
I, K => false
O, C => true
C, O => false
E, F => true
F, E => true

```

Standard loopholes are disallowed.

This is so the answer with the fewest bytes in each language wins.

# Answer
> 7 votes
# Retina 0.8.2, ~~30~~ 29 bytes

```
(.)\1|[DEFHKO][CEF]|[JLN]C|BA

```

Try it online! Link includes test cases.

# Answer
> 7 votes
# Python 3, 76 bytes

```
lambda s,p:any([s==p,p in"CEF"and s in"DEFHKO",s=="B"<p,s in"JLN"and"C"==p])

```

Try it online!

# Credits:

# Answer
> 6 votes
# Python 3, ~~72 Bytes~~ ~~73 bytes~~ 70 bytes

```
lambda p,s:s in{"A":"AB","C":y+"CJLN","E":y,"F":y}.get(p,p)
y="DEFHKO"

```

Try it online!

Edit: Thanks to Chas Brown for cutting some fat!

# Answer
> 4 votes
# C (gcc) (x86 architecture), 76 60 bytes

Many thanks to Arnauld for the changes!

Arguments are given in (plug, socket) order.

```
c[15]={6,0,56696,0,35184,35184};f(a,b){a=a==b|c[a-65]>>b&1;}

```

Try it online!

# Answer
> 3 votes
## Haskell, 67 bytes

```
p#s=p==s||or[elem s b|a:b<-words"AB CDEFHJKLNO EDFHKO FDEHKO",a==p]

```

Arguments to function `#` are two characters, plug first, socket second.

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js), 79 bytes

```
S=>P=>P==S|P<'B'&S<'C'|P=='C'&'JLN'[K='includes'](S)|'CEF'[K](P)&'DEFHKO'[K](S)

```

Invoked as a curried function, `f(socket)(plug)`.

Try it online! (includes testcases, showing a matrix of results.)

# Answer
> 3 votes
# Jelly, 31 bytes

```
Oḅ⁴_ȷe“j⁼⁽⁾ƇƑƓƘƝƤḄẸỊṂṢỴẒĊḞĿ‘o⁼/

```

A monadic link accepting a list of characters `[plug,socket]` which yields `1` if compatible or `0` if not.

**Try it online!** Or see a test-suite (which separates out the two classes).

# Answer
> 3 votes
# , ~~132 129~~ 113 bytes

```
function(S,P,`!`=utf8ToInt)"[<-"(diag(15),cbind(rep(!"",!"	"),!"
"),1)[-64+!P,-64+!S]

```

Try it online!

Builds the following matrix and extracts `m[S,P]` =\> 1 if TRUE, else 0.

```
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
 [1,]    1    1    0    0    0    0    0    0    0     0     0     0     0     0     0
 [2,]    0    1    0    0    0    0    0    0    0     0     0     0     0    0     0
 [3,]    0    0    1    1    1    1    0    1    0     1     1     1     0    1     1
 [4,]    0    0    0    1    0    0    0    0    0     0     0     0     0    0     0
 [5,]    0    0    0    1    1    1    0    1    0     0     1     0     0    0     1
 [6,]    0    0    0    1    1    1    0    1    0     0     1     0     0    0     1
 [7,]    0    0    0    0    0    0    1    0    0     0     0     0     0    0     0
 [8,]    0    0    0    0    0    0    0    1    0     0     0     0     0    0     0
 [9,]    0    0    0    0    0    0    0    0    1     0     0     0     0    0     0
[10,]    0    0    0    0    0    0    0    0    0     1     0     0     0    0     0
[11,]    0    0    0    0    0    0    0    0    0     0     1     0     0    0     0
[12,]    0    0    0    0    0    0    0    0    0     0     0     1     0    0     0
[13,]    0    0    0    0    0    0    0    0    0     0     0     0     1    0     0
[14,]    0    0    0    0    0    0    0    0    0     0     0     0     0    1     0
[15,]    0    0    0    0    0    0    0    0    0     0     0     0     0    0     1

```

Saved 3 bytes by compressing indexes using `intToUtf8` and replacing this function with `!`. See History for more legible version.

Saved 16 bytes thanks to @Giuseppe!

# Answer
> 2 votes
# PHP, 81 bytes

```
<?list(,$s,$p)=$argv;$A=AB;$C=$E=$F=DEFHKO;$C.=JLN;echo+($p==$s||strpos($$p,$s));

```

To run it:

```
php -n -d error_reporting=0 <filename> <socket> <plug>

```

Example:

```
php -n -d error_reporting=0 socket_plug_compatibility.php F E

```

Or Try it online!

**Notes:**

* To save some bytes, I have used strings without single/double quotations as the string wrapper. Thus, the `error_reporting=0` option is used to not output warnings.
* Input only works with uppercase letters.
* Outputs 1 for compatibility and 0 for non-compatibility.

---

# How?

Every plug is compatible with same socket as itself. There are four special plugs (A, C, E, F) which are compatible with a few more sockets as well. Four string variables with the name of the special plugs are defined to hold list of their extra compatible sockets.

It is checked if input plug and socket are same or if the socket is in the list of compatible sockets for that plug. The latter check is done with the help of PHP's variable variables.

# Answer
> 2 votes
# Javascript ES6, ~~66~~ ~~65~~ 64 chars

```
p=>s=>p==s|{A:1,C:14172,E:8788,F:8780}[p]&(1<<parseInt(s,36)-11)

```

Takes capital letters into `p` for plug and `s` for socket, returns falsy (`0`) or truthy (`1`, `2`, `4`, ..., `8192`) value.

### Test:

```
f=p=>s=>p==s|{B:1,C:14172,E:8788,F:8780}[p]&(1<<parseInt(s,36)-11)

console.log(`A, A => true
I, K => false
O, C => true
C, O => false
E, F => true
F, E => true`
.split`
`.map(x=>x.match(/(.), (.) => (\w+)/))
.every(([m,p,s,res])=>!!f(s)(p)==eval(res)))
```

# Answer
> 0 votes
# Pascal (FPC), 113 bytes

```
var p,s:char;begin read(p,s);write((p=s)or(pos(p,'CEF')>0)and(pos(s,'DEFHKO')>0)or(pos(p+s,'AB CJ CL CN')>0))end.

```

Try it online!

Test for all values

Following the `DEFHKO` train...

`pos(string1,string2)` checks for first occurence of `string1` in `string2` and returns its position in it or 0 if it doesn't exist.

---
Tags: code-golf, decision-problem, combinatorics, alphabet
---


title: Pleasanortmanteaus

text:
# Question
Title: Pleasanortmanteaus
A **portmanteau word** is a combination of two words that takes part of each word and makes them into a single new word. For example, **lion** \+ **tiger** =\> **liger**.

Let's write a program to generate portmanteaus from a pair of input words. Computers aren't the best at English, so we'll need to establish some rules to ensure that the output portmanteaus are pleasant to the eye and ear.

<sup>(Examples here are shown with a separator between the prefix and suffix for clarity: `li|ger`. However, the program's actual outputs should not have a separator: `liger`.)</sup>

* Each portmanteau will consist of a nonempty prefix of the first word concatenated to a nonempty suffix of the second word: yes to `li|ger`, no to `|iger`.
* If the prefix ends with a vowel, the suffix must start with a consonant, and vice versa: yes to `lio|ger` or `l|er`, no to `lio|iger` or `l|ger`. **You may decide whether to count `y` as a vowel or a consonant.** Your solution must pick one option and stick with it, however.
* The resulting word must not contain either of the original words in full: yes to `lio|ger`, no to `lion|iger` or `li|tiger`.
    + This rule holds even if the portion in question is formed from parts of both words: with input of `two` \+ `words`, output `tw|ords` is still illegal because it contains the substring `words`. (The only valid output for this pair would be `t|ords`.)

Your program or function must take two words and output/return **a list of all pleasant portmanteaus** that can be formed from those words in that order.

## Details

* Standard input and output methods apply. Standard loopholes are forbidden.
* Words will consist only of lowercase letters (or, if you prefer, only of uppercase letters).
* You may take the two input words as a list, tuple, two separate inputs, a single string with a non-letter delimiter, etc.
* Output format is similarly flexible; if you return or output a string, it should be delimited such that it's clear where one portmanteau word ends and the next one begins.
* There should be no delimiters inside a portmanteau word.
* It's okay if your output list includes duplicate results; it's also okay to remove duplicates.

## Test cases

```
> lion, tiger
< liger, ler, liger, lir, lioger, lior

> tiger, lion
< tion, ton, tin, tigion, tigon, tigen

> spoon, fork
< sork, spork, spork, spok, spoork, spook

> smoke, fog
< sog, smog, smog, smokog

> gallop, triumph
< giumph, gumph, gariumph, gamph, gaph, gah, galiumph, galumph, galliumph, gallumph, galloriumph, gallomph, galloh

> breakfast, lunch
< bunch, brunch, brench, brech, breh, breanch, breach, breah, breakunch, breakfunch, breakfanch, breakfach, breakfah, breakfasunch

> two, words
< tords

> harry, ginny (if y is treated as a consonant)
< hinny, hanny, hany, hay, harinny, harrinny

> harry, ginny (if y is treated as a vowel)
> hinny, hy, hanny, hany, harinny, hary, harrinny

```

## Reference solution

Here's a reference solution in Pip (treats `y` as a consonant).

---

This is : the shortest answer in each language wins!

# Answer
# 05AB1E, 28 bytes

`y` is a vowel (same byte count as consonant though).

```
нη¨sθ.s¨âʒ`нsθ‚žOsåË_}Jʒs¢Z_

```

Try it online! or as a slightly modified Test Suite
> 5 votes

# Answer
## Retina, 72 bytes

```
L$w`(?<=[aeiou]()|.())((.+),(.+))\B(?!\4)(?<!\5\3)(?([aeiou])\2|\1)
$`$'

```

Try it online!
> 4 votes

# Answer
# Pyth, 38 bytes

```
f!s}RTQm+hd_edfxFm}ed"aeiou"T*._hQ.__e

```

Input is a list of the two words, and y isn't treated as a consonant.

Try it online here, or verify all test cases at once here.

```
f!s}RTQm+hd_edfxFm}ed"aeiou"T*._hQ.__e   Implicit: Q=eval(input())
                                hQ       First input word
                              ._         All prefixes of the above
                                     e   Second input word (Q inferred)
                                  .__    Reverse, take all prefixes
                             *           Cartesian product of the above
              f                          Filter the above using:
                 m          T              Map d in the current element using:
                   ed                        The last letter of the word part
                  }  "aeiou"                 Is it contained in the vowel list?
               xF                          Take the XOR of the list
                                         (This ensures that the word parts meet at one consonant)
       m                                 Map d in the filtered set using:
        +hd_ed                             Add the first part to the reversed second part
f                                        Filter the above using:
  s}RTQ                                    Does the portmanteau contain either of the input words?
 !                                         Logical NOT (remove from list if the above is true)

```
> 3 votes

# Answer
# Java 8, ~~228~~ ~~225~~ 215 bytes

```
v->w->{String r="",t,p=" aeiou";for(int i=w.length(),j;--i>0;)for(j=1;j<v.length();)r+=(t=v.substring(0,j)+w.substring(i)).matches(v+".*|.*"+w)|p.indexOf(t.charAt(j-1))*p.indexOf(t.charAt(j++))>0?"":t+" ";return r;}

```

Takes two Strings in currying syntax and returns a String. Treats `y` as a consonant. Try it online here.

Thanks to DLosc for golfing 2 bytes.

Ungolfed:

```
v -> w -> { // lambda taking two String parameters in currying syntax
    String r = "", // result
    t, // temporary variable used for storing
       // the portmanteau candidate currently being evaluated
    p = " aeiou"; // vowels for the purposes of this function;
                  // the leading space is so that they all have a positive index
    for(int i = w.length(), j; --i > 0; ) // loop over all proper suffixes
                                          // of the second word
        for(j = 1; j < v.length(); )      // loop over all proper prefixes
                                          // of the first word
            r += // construct the portmanteau candidate
                 (t = v.substring(0, j) + w.substring(i))
                 // if it contains one of the input words ...
                 .matches(v + ".*|.*" + w)
                 // ... or the boundary is consonant-consonant
                 // or vowel-vowel (here we make use of the facts
                 // that all the vowels have a positive index, and
                 // indexOf() returns -1 in case of no match) ...
                 | p.indexOf(t.charAt(j-1)) * p.indexOf(t.charAt(j++)) > 0
                 ? "" // ... reject it ...
                 : t + " "; // ... else add it to the result
    return r; // return the result
}

```
> 3 votes

# Answer
# Japt, 32 bytes

```
å+ ïVw å+)f_xè"%v$" uÃmrÈ+YwÃkøN

```

Japt Interpreter

Saved 10 bytes thanks to Shaggy's clearer understanding of Japt's syntax.

Saved 8 bytes due to a new language feature

Saved 2 byte thanks to some suggestions from ETHproductions

The newest version of Japt introduced the Cartesian Product function, which saved quite a few bytes and allowed me to restore the ordering of inputs (so "lion" "tiger" outputs "liger" and such). "y" is still treated as a consonant.

Explanation:

```
   ï     )       Cartesian product of...
å+                prefixes of first input
    Vw å+         and suffixes of second input.

f_         Ã     Remove the ones where...
  xè"%v$"         the number of vowels at the joining point
          u       is not 1.

m     Ã          Replace each pair with...
 rÈ+Yw            the prefix and suffix joined together
       køN       then remove the ones that contain either input

```
> 3 votes

# Answer
## Python 3, ~~156~~ 150 bytes

I've considered `y` as a consonant.

```
lambda a,b:{a[:i]+b[j:]for i in range(1,len(a))for j in range(1,len(b))if((a[i-1]in'aeiou')^(b[j]in'aeiou'))*0**(a in a[:i]+b[j:]or b in a[:i]+b[j:])}

```

-6 bytes thanks to Jonathan Frech

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 124 bytes

Takes the 2 words in currying syntax `(a)(b)` and prints the results with `alert()`. Assumes ***y*** is a consonant.

```
a=>b=>[...a].map(c=>[...b].map((C,j)=>!(w=s+b.slice(j)).match(a+'|'+b)&v.test(c)-v.test(C)&&alert(w),s+=c),s='',v=/[aeiou]/)

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~179~~ ~~176~~ ~~166~~ 162 bytes

```
lambda s,t:[w for w in g(s,t)if(s in w)<1>(t in w)]
g=lambda s,t:s[:-1]and[s[:-1]+t[j:]for j in range(1,len(t))if(s[-2]in'aeiou')^(t[j]in'aeiou')]+g(s[:-1],t)or[]

```

Try it online!

3 bytes from Jonathan Frech. And 10 bytes thx to The Matt.

In my world, `y` is not a vowel. (It's a yowl!)
> 1 votes

# Answer
# Jelly, 27 bytes

```
¹Ƥp¹ÐƤ}Ø.ị"e€Øc⁻/ƲƇẎ€wÐḟƒ@,

```

Try it online!

**Yy** is a consonant. Both cases supported. Returns duplicates.

Output has been prettified over TIO. Remove `+/€` from the footer to see the actual output.
> 1 votes

# Answer
# C++ 11, ~~217~~ 202 bytes

```
[](auto v,auto w){auto r=v,t=v,p=v;r="",p="aeiou";for(int i=w.size(),j;--i;)for(j=v.size();j;)(t=v.substr(0,j)+w.substr(i)).find(v)+1|t.find(w)+1|p.find(t[j-1])<5==p.find(t[j--])<5?v:r+=t+" ";return r;}

```

Makes heavy use of `std::string#find`. Treats `y` as a consonant. Try it online here.

Ungolfed:

```
// lambda; relies on auto to keep declarations short
[] (auto v, auto w) {
    // let's declare some strings. To keep it terse, we're using auto and the type of the arguments.
    auto r = v, // result string
    t = v,      // temporary string for storing the portmanteau candidate
    p = v;      // vowels string
    // now assign them their values
    r = "",    // result starts empty
    p = "aeiou"; // vowels don't include 'y'
    for(int i = w.size(), j; --i; ) // suffixes of the second word
        for(j = v.size(); j; ) // prefixes of the first word
            // create the portmanteau candidate
            (t = v.substr(0, j) + w.substr(i))
            // if it includes one of the input words ...
            .find(v) + 1 | t.find(w) + 1
            // ... or the boundary is consonant-consonant or vowel-vowel ...
            | p.find(t[j - 1]) < 5 == p.find(t[j--]) < 5
            ? v // ... discard it ...
            : r += t + " "; // ... else add it to the result.
    return r; // return the result
}

```
> 1 votes

# Answer
# Ruby, ~~113 112 109~~ 104 bytes

`y` is a consonant

This outputs the same duplicates as the examples in the question, I must be using the same loop

```
->a,b,i=j=1{r=a[0,i]+b[j..-1];g=:aeiou;!g[a[i-1]]^g[b[j]]|r[a]|r[b]||z=[*z,r];b[j+=1]||a[i+=j=1]?redo:z}

```

Try it online!
> 0 votes

# Answer
# Emacs Lisp, 306 + 13 = 319 bytes

*+13 for `(require'seq)`*

```
(require'seq)(lambda(a b)(dotimes(i(1-(length b)))(dotimes(j(1-(length a)))(progn(setq w(substring a 0(1+ j))x(substring b(1+ i))c(concat w x))(defun V(c)(seq-contains"aeiou"(elt c 0)'char-equal))(if(not(or(string-prefix-p a c)(string-suffix-p b c)))(if(V(substring w -1))(if(not(V x))(print c))(if(V x)(print c))))))))

```

Try It Online!

Defines an anonymous lambda function. Outputs a sequence of newline-separated portmanteaus with each one surrounded by quotes. Golfing tips are welcome. The letter `y` is considered a consonant.

## Ungolfed

```
(require 'seq)
(defun Portmanteus(word1 word2)
  "Find all valid portmanteus of the two given words"
  (dotimes (i (1- (length word2)))
    (dotimes (j (1- (length word1)))
      (progn
        (setq w (substring word1 0 (1+ j)) w2 (substring word2 (1+ i)) comb (concat w w2))
        (defun isVowel (c) (seq-contains "aeiou" (elt c 0) 'char-equal))
        (if (not (or (string-prefix-p word1 comb) (string-suffix-p word2 comb)))
          (if (isVowel (substring w -1))
            (if (not (isVowel w2))
              (princ (format "%s\n" comb))
            )
            (if (isVowel w2)
              (princ (format "%s\n" comb))
            )
          )
        )
      )
    )
  )
)

```
> 0 votes

---
Tags: code-golf, string, natural-language
---


title: Imperfections dans mon français

text:
# Question
Title: Imperfections dans mon français
To conjugate a verb in *l'imparfait*, one needs to perform the following steps:

1. Find the "stem" of the word; this is achieved by omitting the `-ons` from the nous-conjugated form of the word. For example, *vivre* is *nous vivons*; removing `-ons` from *vivons* yields `viv-`.
2. Take the stem and add an appropriate ending, according to the subject. Here are the endings:

```
je         -ais
tu         -ais
il/elle    -ait

nous       -ions
vous       -iez
ils/elles  -aient

```

**Objective** Given a verb and a subject, output the imperfect form of that verb with respect to the subject. The input format can be in any format convenient to your language. Your submission can either be a program, snippet, or function. (Note that the verb does not have to be a real verb.)

You can assume that the verb is a regular verb, i.e, items like *avoir* would be treated as an `-ir` verb, not an irregular one. The only verb you have to quantify as irregular is *être*; it is conjugated as such:

```
j'étais
tu étais
il/elle était

nous étions
vous étiez
ils/elles étaient

```

Here are the conjugations for `-er`, `-re`, and `-ir` verbs in the nous forms

```
-ER => (e)ons           ; e is added after a 'g'
-RE => ons
-IR => issons

```

Anything that does not end with such does not have to be handled.

(Note that *je* merges with the next vowel, if there is one. E.g., `je acheter -> j'achetais`. `h` will be considered a vowel for our purposes.)

# Example IOs

```
input: tu vivre
output: tu vivais

input: elles nager
output: elles nageaient

input: je morter
output: je mortais     ; incorrect in real life, but correct for our purposes

input: vous finir
output: vous finissiez

input: il croire
output: il croiait

input: nous jouer
output: nous jouions

```

# Bonuses

* -5N bytes for all `N` extra irregular verb handled.
* -10% if you *also* output every conjugation of the verb in the imperfect tense.

---

This is a , so the shortest program in bytes wins.

# Answer
> 2 votes
# Processing, 342-10%(bonus) = 307.8

I have created a function. To call the function, include the pronoun as the first parameter and the verb as the second. For example, `a("je","habiter")`

Please note that my program conjugates the verb for all the pronouns, so that is how I got the 10% bonus.

```
void a(String a,String b){String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"},p={"je","tu","il","elle","nous","vous","ils","elles"};if("aehiou".contains(b.charAt(0)+""))p[0]="j'";for(String i:p)println(i+" "+b.substring(0,b.length()-2)+(b.endsWith("ger")?"e":b.endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);}

```

Readable form:

```
void a(String a,String b){
  String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"},p={"je","tu","il","elle","nous","vous","ils","elles"};
  if("aehiou".contains(b.charAt(0)+""))p[0]="j'";
  for(String i:p)
    println(i+" "+b.substring(0,b.length()-2)+(b.endsWith("ger")?"e":b.endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);
}

```

Output (for `a("je", "habiter")`)

```
j' habitais
tu habitais
il habitait
elle habitait
nous habitions
vous habitiez
ils habitaient
elles habitaient

```

# Answer
> 4 votes
# Haskell, ~~366~~ ~~362~~ 352 bytes

```
s#v=m++g++d++t
 where
 m|v=="être"="ét"|i/="rio"&&i/="erd"&&i/="eri"=r 2 v|otherwise=r 3 v
 g=if(last m=='g'&&head t/='i')then"e"else""
 d|init i=="ri"="iss"|i=="eri"="y"|otherwise=""
 t|s=="je"||s=="tu"="ais"|elem s["il","elle","on"]="ait"|s=="nous"="ions"|s=="vous"="iez"|s=="ils"||s=="elles"="aient"
 r i=reverse.drop i.reverse
 i=take 3$reverse v

```

You can compile this in ghci and use it like so `"je"#"choisir"` to get `"choisissais"`.

This code works with some irregular verbs. It can conjugate *croire* (*je croyais*, *tu croyais*…) or *prendre* as well as all its derivatives (*apprendre*, *comprendre*, etc.).

I couldn't find a short way to conjugate other verbs ending in -ire (such as *lire*, *rire*, *dire*, etc.) or in -dre (such as *craindre*, *soudre*, etc.).

# Answer
> 2 votes
# Java, ~~389~~ ~~385~~ ~~383~~ ~~382~~ ~~352.7~~ 443-10%(bonus) = 398.7 bytes

Byte count reduced thanks to @PeterTaylor and @Fatalize
Please note that my program conjugates the verb for all the pronouns, so that is how I got the 10% bonus.

```
class A{public static void main(String[]a){String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"},p={"je","tu","il","elle","nous","vous","ils","elles"},w=new java.util.Scanner(System.in).nextLine().split(" ");if("aehiou".contains(w[1].charAt(0)+""))p[0]="j'";for(String i:p)System.out.println(i+" "+w[1].substring(0,w[1].length()-2)+(w[1].endsWith("ger")?"e":w[1].endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);}}

```

Readable form (still quite messy):

```
 1| class A{
 2|   public static void main(String[]a){
 3|     String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"};
 4|     String[]p={"je","tu","il","elle","nous","vous","ils","elles"};
 5|     String[]w=new java.util.Scanner(System.in).nextLine().split(" ");
 6|     if("aehiou".contains(w[1].charAt(0)+""))p[0]="j'";
 7|     for(String i: p) {
 8|       System.out.print(i+" "+w[1].substring(0,w[1].length()-2)+(w[1].endsWith("ger")?"e":w[1].endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);
 9|     }
10|   }
11| }

```

Explanation:

```
Lines 3-4: Initialisation of arrays.
Line    5: Read a line as input and split it into words
Line    6: Shorten the `je` to `j'` in presence of a succeeding vowel or a `h`.
Line    7: Create a for-loop iterating through all of the pronouns .
Line    8: Conjugate the verb(remove the ending from the infinite form of the verb and add ending accordingly) and print the result, along with the pronoun.

```

## (Old Version) 393-10% = 352.7 bytes

Please note also that my old program does not obey with the new rule about the `je` merging into `j'`.

```
class A{public static void main(String[]a){String[]e={"ais","ais","ait","ait","ions","iez","aient","aient"},p={"je","tu","il","elle","nous","vous","ils","elles"},w=new java.util.Scanner(System.in).nextLine().split(" ");for(String i:p)System.out.println(i+" "+w[1].substring(0,w[1].length()-2)+(w[1].endsWith("ger")?"e":w[1].endsWith("ir")?"iss":"")+e[java.util.Arrays.asList(p).indexOf(i)]);}}

```

# Answer
> 1 votes
# Python 3, 258-10% = 232.2 223-10% = 200.7

Huge thanks to @WW for saving me 35 bytes!

```
def t(x,y):
 z=y[-2:];y=y[:-2];y+='e'*(y[-1]=='g');y+='iss'*(z=='ir')
 return[('j'+"e'"[y[0]in'aeiouh']+' tu il elle nous vous ils elles').split()[i]+' '+y+'ais ais ait ait ions iez aient aient'.split()[i]for i in range(8)]

```

Try it online!

---
Tags: code-golf, natural-language
---


title: Intersection Point of Two Line Segments

text:
# Question
Title: Intersection Point of Two Line Segments
Given two line segments, determine if the line segments intersect and if so, where. In the case that the two given line segments are co-linear and overlap, determine the midpoint of the overlapping segment. Lines will be specified in pairs of (x, y) coordinates.

# Examples

* \[(-1, -1), (1, 1)\], \[(-1, 1), (1, -1)\] =\> (0, 0)
* \[(-1, -1), (1, -1)\], \[(-1, 1), (1, 1)\] =\> No intersection
* \[(-2, 0), (1, 1.32)\], \[(-1, 0.44), (2, 1.76)\] =\> (0, 0.88)
* \[(-2, -2), (0, 0)\], \[(1, -1), (1, 1)\] =\> No intersection

# Rules

* Standard rules and loopholes apply
* Input and output may be in any convenient format. Please state your convention along with your solution.
    + Examples for output conventions would be `null` for no intersection and a point for an intersection; a boolean and a tuple; string output in (x, y) format or "no intersection"; x and y will be `NaN` for no intersection. Other conventions are allowed, but these may give you a good starting point.
* A minimum of 2 decimal places (or equivalent) precision is required.
* Final results should be accurate to within 0.01 when at a scale of -100 - +100. (32-bit floats will be more than accurate enough for this purpose)
* This is , so shortest code wins.

---

Related: This is not a duplicate of 2D Collision Detection because it only concerns line-line tests and requires an intersection point for intersecting line segments. This is also not a duplicate of Intersection of Two Lines because this concerns line *segments* specified with two endpoints rather than functions.

# Answer
# , 95 bytes

```
function(m,a=c(1,3),r=range){plot(0,,"n",r(m[a,]),r(m[-a,]));segments(m[1,],m[2,],m[3,],m[4,])}

```

Try it online!

Here's a graphical solution as an appetizer while I'm working on a full-blown solution. TIO link will not plot anything.
> 2 votes

# Answer
# C (gcc -lm), 225 bytes

```
#define T 20000
#define N double
N sqrt(N);N D(a,b){N x=a%T-b%T,y=a/T-b/T;return sqrt(x*x+y*y);}F,L,P;f(a,b,c,d){F=L=-1;for(P=0;++P<T*T;L=(D(a,P)+D(P,b)-D(a,b)<0.001&&D(c,P)+D(P,d)-D(c,d)<0.001)?(F=(F<0?P:F)),P:L);a=(F+L)/2;}

```

Try it online!

Very slow. Input format is endpoints packed into ints as coordinate multiplied by 100 (to an integer) and 10000 added to it (to a natural). Y coordinate is multiplied by an additional 20000 to pack it next to X coordinate. No collision is signaled by the point (-100.01,-100).

Thus the X coordinate of a point A is `((A%20000)-10000)/100.0` and the Y coordinate is `((A/20000)-10000)/100.0`.

## Rationale

Thanks to the question providing no time limit and specifying a desired precision accurately, a non-optimal solution can be used to reduce code size. Thus instead of actually computing the collision points, then doing some additional logic if the lines are coincident, this checks every single point of the given precision and sees if it is a collision.

This collision check is much shorter (code-wise) than the collision computation. In particular to check if a point collides with a line segment just check if the distance to each endpoint adds up to the length of the segment. If a point collides with both line segments individually, then it is a point where the line segments intersect.

Using this strategy the code finds the endpoints of the collision and returns their midpoint. Initially they are set to -1, so if there is no collision it returns -1 (-1+-1/2) which when translated back is a number just out of range. If there's only one collision point, it is stored in both endpoints, so it is itself returned (x+x/2). Finally, if there is an overlap the overlap must be a line, returning the average of the line's endpoints will yield the midpoint.

## Algorithm

As such, the algorithm in pseudo-code would be:

```
collision (AB,CD):
    start and end = -1
    for each point P:
        if P is in both line segments AB and CD
            if start = -1, start = P
            end = P
    return (start+end)/2

is P in line segment AB:
    return distance(A,P) + distance(P,B) = distance(A,B)

```

## Description

The annotated source is thus:

```
#define T 20000             // We use 20000 a lot
#define N double            // We use double a lot
N sqrt(N);                  // We need to prototype sqrt or it will be assumed to be int(int)
N D(a,b){                   // D defines the distance function
    N x=a%T-b%T,            // x is delta x
      y=a/T-b/T;            // y is delta y
    return sqrt(x*x+y*y);}  // standard distance formula: sqrt(dx^2+dy^2)
F,                          // F is the first point of collision
L,                          // L is the last point of collision
P;                          // P is the current test point
f(a,b,c,d){                 // f takes the 4 segment end-points
    F=L=-1;                 // Initialize both collision points to -1 (invalid)
    for(P=0;++P<T*T;        // Loop P over each point
    L=                      // Set the last collision point based on a ternary
    (D(a,P)+D(P,b)-D(a,b)   // We have to use an epsilon check due to floating point rounding errors
     <0.001                 // This accuracy is definitionally good enough
     &&                     // The previous check was for collision with AB
     D(c,P)+D(P,d)-D(c,d)   // now we have to check for collision with CD
     <0.001)?               // if both collide - we have a collision point!
      (F=(F<0?P:F)),        // if the first collision point isn't set, this is it
      P                     // set the last collision point no matter what
      :                     // they don't both collide, ignore this point
      L);                   // the expression is assigned to L, so keep L the same
    a=                      // return by assigning to the first argument
      (F+L)/2;}             // the average of the first and last points
                            // Luckily the packing of the points fits with enough space so we
                            // don't have to worry about averaging each coordinate separately

```
> 1 votes

---
Tags: code-golf, geometry
---


title: Fred's water bill

text:
# Question
Title: Fred's water bill
Fred is a quasi-friendly guy, but in reality he is mean.

Because of this, Fred lives alone in a small apartment in Los Altos, CA. Fred is so mean because he is very particular about water. He, therefore, needs your help with figuring out what his water bill is.

Your job is to write a function or program that returns his water bill given the amount of water used as input (which is always an integer).

Water consumption comes in tiers. This means that there are ranges of prices depending on the amount of water.

These are the tiers, their prices, and the amounts of water they correspond to:

```
Tier I
   First 10 Ccf: $3.8476/Ccf
Tier II
   Next 17 Ccf: $4.0932/Ccf
Tier III
   All subsequent water: $4.9118/Ccf

```

For *n* hundreds of cubic feet (Ccf), there are the following additional charges as well:

```
CPUC fee: 1.5% of above charges
LIRA quantity surcharge: $0.047*n
PBOP amoritization surcharge: $0.004*n

```

The sum of the Tier I, Tier II, Tier III, CPUC, LIRA, and PBOP fees is the total water bill. This sum you should either return or print to the console rounded to two decimal places.

Here are two examples:

```
Input: 15
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: (15-10)*4.0932 = 20.466
Tier III: 0*4.9118 = 0
Tiers sum: 58.942
CPUC: 1.5% of 58.942 = 0.88413
LIRA: 0.047*15 = 0.705
PBOP: 0.004*15 = 0.06
Total sum: 58.942 + 0.88413 + 0.705 + 0.06 = 60.59113
...
Output: 60.59

Input: 100
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: 17*4.0932 = 69.5844
Tier III: (100-10-17)*4.9118 = 358.5614
Tiers sum: 466.6218
CPUC: 1.5% of  = 6.999327
LIRA: 0.047*100 = 4.7
PBOP: 0.004*100 = 0.4
Total sum: 478.721127
...
Output: 478.72

```

This is code golf so shortest code in bytes wins!

# Answer
> 1 votes
# Pyth, ~~55~~ 41 bytes

```
.R+s*Vv.",9t¬®Ï0NwÝ"lMcUQ,T27*.051Q2

```

The code contains unprintable characters, so here's a `xxd` hexdump.

```
00000000: 2e52 2b73 2a56 762e 222c 3904 1874 c2ac  .R+s*Vv.",9..t..
00000010: c2ae c280 c293 c38f 301c 4e77 c39d 226c  ........0.Nw.."l
00000020: 4d63 5551 2c54 3237 2a2e 3035 3151 32    McUQ,T27*.051Q2

```

### Explanation

1. `."…"` is a packed string that contains `3.8476,4.0932,4.9118`.
2. `v` evaluates that to the tuple `(3.8476, 4.0932, 4.9118)`. These are the tiers' prices multiplied with CPUC added.
3. `UQ` generates the range `0``n-1`.
4. `c``,T27` splits that range at indices 10 and 27, with extra empty lists in the end if the range is too short.
5. `lM` finds the length of each part, giving the amount of water for each tier.
6. `*V` multiplies that by the tuple from step 2 to get the prices for the tiers.
7. `s` sums the results.
8. `+``*Q.051` adds the input multiplied by 0.051, i.e. LIRA + PBOP.
9. `.R``2` rounds the result to 2 decimals.

Try it online.

# Answer
> 2 votes
## Mathematica, ~~83~~ ~~76~~ 69 bytes

```
1.015{3.8476,.2456(b=Boole)[#>10],.8186b[#>27],51/1015}&~Array~#~Total~2~Round~.01&

```

Anonymous function that constructs an array of the three tiers in the first column plus the LIRA and PBOP represented as an arbitrary-precision number in the fourth column. The whole thing is multiplied by `1.015` and all elements of the array are summed and rounded to `.01`. Since `51/1015*1.015` will be the desired `0.051` the output is exactly as precise, as the specification in OP.

A shorter solution, in **76 bytes**, as I have suggested in my comment under the Perl solution

```
{3.956314,.249284(b=Boole)[#>10],.830879b[#>27]}&~Array~#~Total~2~Round~.01&

```

where `1.015` is factored into the prices from the start and then the LIRA and PBOP is added on top of the first tier.

~~**73 bytes** (but I'm reluctant to update my byte-count since this is quite close to the straightforward Perl solution):~~

**69 bytes** -- ah what the heck, golfing took some effort too.

```
.01Round[395.6314#+{24.9284,83.0879}.(UnitStep[#-1]#&/@{#-10,#-27})]&

```

**EDIT regarding floating point error**
The first three iterations of my answer are indeed exact in their decimal representation, since all coefficients involved have terminating decimal representations. However, since the coefficients are explicitly floats, stored in binary and having non-terminating binary representations, large enough inputs will start to accumulate errors in the least-significant digits of the binary representation. I would guess, when the float is so large, that it fits only 3-4 digits to the right of the decimal point, we can expect errors of around 1 cent. See below for an *exact* answer.

**72 bytes, somewhat-immune to float inaccuracies**

```
.01Round[{3956314,249284,830879}.(UnitStep[#-1]#&)/@(#-{0,10,27})/10^4]&

```

The multiplication by the leading `.01` is done at the very last step. Until that point, all calculation are done with integers. This means, that if the `.01` is omitted, there will be an *exact* result, but expressed in cents, rather than dollars. Of course, the multiplication by a float converts the entire thing to a float, and, as mentioned, it needs to be small enough to fit into 64 bits and still be accurate to `.01`.

# Answer
> 2 votes
## 05AB1E, ~~64~~ ~~58~~ 51 bytes

```
0T27¹)vy¹‚ï{0è})¥•_ÄÄ™wu24@•2'.:7ô)ø€PO¹"5.1"*+ïTn/

```

**Explained**

```
0T27¹)                                               # list of price brackets
      vy¹‚ï{0è})                                     # min of each with input
                ¥                                    # calculate deltas to get amounts within each bracket
                 •_ÄÄ™wu24@•2'.:7ô                   # list of price rates with CPUC included
                                  )ø                 # zip with amounts for each rate
                                    €PO              # multiply amounts by their rates and sum
                                       ¹"5.1"*+      # add LIRA/PBOP
                                               ïTn/  # round to 2 decimals

```

Try it online

# Answer
> 1 votes
# Perl 5, 73 bytes

The obvious solution. 72 bytes, plus 1 for `-ne` instead of `-e`.

```
printf'%.2f',$_*3.956314+($_-10)*($_>10)*.249284+($_-27)*($_>27)*.830879

```

Saved 5 bytes thanks to LLlAMnYP. Thanks!

# Answer
> 1 votes
# Oracle SQL 11.2, 151 bytes

```
SELECT ((DECODE(SIGN(:1-10),1,10,:1)*3.8476)+(DECODE(SIGN(:1-27),1,17,:1-10)*4.0932)+(DECODE(SIGN(:1-27),-1,0,:1-27)*4.9118))*1.015+:1*0.051 FROM DUAL;

```

Un-golfed

```
SELECT ((DECODE(SIGN(:1-10),1,10,:1)*3.8476)+
       (DECODE(SIGN(:1-27),1,17,:1-10)*4.0932)+
       (DECODE(SIGN(:1-27),-1,0,:1-27)*4.9118))*1.015+
       :1*0.051
FROM DUAL

```

# Answer
> 1 votes
## JavaScript ES6, 77 bytes

```
x=>(x>27?(x-27)*4.985477+109.681:(x>10?(x-10)*4.1546+39.053:x*3.9053))+.051*x

```

Un-golfed

```
f = x => {
  if (x > 27) {
    res = (x - 27) * 4.985477 + 109.681306
  } else if (x > 10) {
    res = (x - 10) * 4.154598 + 39.05314
  } else {
    res = x * 3.905314
  }
  return res + 0.051 * x
}

```

I factored in the LIRA and PBOP coefficients. The extra 1.5% gets added at the end.

Probably not the most efficient solution in terms of golfing but somewhat different from the Perl one.

Floating point error should occur with larger numbers and can be fixed by adding 1 or 2 extra bytes to each coefficient.

```
f=x=>(x>27?(x-27)*4.985477+109.681:(x>10?(x-10)*4.1546+39.053:x*3.9053))+.051*x

console.log(f(15))
console.log(f(100))
console.log(f(200000))
```

# Answer
> 1 votes
# , 52 bytes

```
approxfun(c(0,10,27,10^6),c(0,39.56,111.06,5036475))

```

Try it online!

Generates a linear approximation function, based on my previous answer's values at 0,10,27 and 10^6. The catch: the upper limit on the input is 10^6.

`approxfun` (with `ecdf`, `stepfun`, `splinefun`, etc.) is one of the many nice features of `R`.

# Answer
> 0 votes
# Pyth - ~~58~~ 51 bytes

```
.Rs+*Bs*V++m3.8476Tm4.0932 17m4.9118Qm1Q.015*.051Q2

```

Test Suite.

# Answer
> 0 votes
# VBA, 88 bytes

```
Function W(V):W=Round(.051*V+.203*(V*19.238-(V-10)*(V>10)*1.228-(V-27)*(V>27)*4.093),2)

```

The base rate and higher use differential rates have been multiplied by 5, and the CPUC fee multiplier divided by 5 (0.203).

The VB editor will add an `End Function` line, which is why the terminal line feed is included.

---
Tags: code-golf, math
---