# Question
Title: Write a short story using only valid code
What I'd like to see is your attempts at writing a kind of "story" that has a fairly easy to read meaning, but also creating a valid code fragment. For example, this (BBC) BASIC code:

```
LET customer = "sober"
REPEAT
  INPUT "more beer"
UNTIL customer = "drunk"

```

(based on http://img.rakuten.com/PIC/12184048/0/1/300/12184048.jpg for the idea)

Rules/guidelines:

* The code must be valid in the language you specified - Anybody must be able to run it without needing to create any fancy
* Strings, comments, or anything that allows free text to be added to the code, may be used, but for at most 3 words per string (and you can't put multiple strings or comments in a row)
* Your code does not have to result in any sensible output when it's executed. It can even be an infinite loop, as long as the code is valid and it represents something sensible(\*) when read in English.
* Any interpunction in your code will be ignored in the story.
* Variables do not need to be defined. The code you make here is just a code *fragment*. You will **lose 5 points** for calling an undefined variable/keyword/label/etc. though.
* for every individual built-in keyword/statement/function/etc you use, you **receive 15 points**. These include `for` and `if`, but also built-in functions such as `replace()`. Libraries do not count as built-in functions, but you're free to use them.
* for every letter, number, or underscore in your code, you **receive 1 point**.
* for every line/block of code that is unrelated(\*) to the story, or uses keywords/statements/etc with no meaning(\*) in English, you **lose 20 points**, and the involved characters will **not** count towards the 1 point per letter/number. To keep it fair to the languages that need data types like `int` when defining variables, data types are ignored completely. This means they don't receive 10 points for being a keyword, they won't receive points for the involved characters, but they also don't cause point loss.
* It is not allowed to just make something valid English by inserting a comment to "fill in the blanks".
* Since this is a , for every upvote to your answer you will **receive 25 points**.
* Make sure to specify which language your code is in, and the formula you used to count the amount of points your answer gets.
* The answer with the most points, using this system above, wins.
* Using this system, the above example code would get `4*15 + 53*1 = 113` initial points.

(\*) *over-analysation / objectification part:* to keep this as objective as possible, "sensible" or "unrelated" means the following: If the piece of code uses words that are not English, it's not valid (for example, `const` or `int` are not English words, but `foreach` or `typeof` is 2 English words merged, so that is okay). Also, even if you use valid English words such as `print` or `echo`, these will have to fit in with the story with their *original* meaning (so 'putting ink on paper' and 'reflecting sound', not 'showing on a screen'). And with 'fit in', I mean that the subject of the story must be related to it.

*I hope this last "disclaimer" meets the requirement of defining objective criteria.*

# Answer
# css (114)

I'm new to the golf scene. Not sure if CSS counts as 'code'. But here's a stab at it.

The year is still young...

```
body {width: 110%}
.pants {overflow: visible}
.newYear {transform: scale(.8)}

```

If I understand the scoring:

* every individual built-in keyword = 4 * 15
* every letter/number = 1 * 54
* every unrelated line = 0

= initial score: 114
> 42 votes

# Answer
**SQL love poem**

```
SELECT * FROM Night_Sky
WHERE Beauty LIKE "yours"

```

> 0 results returned

I'm a little unsure of the rules here, as my output is obviously important to the story, but not part of the code. So I'm ignoring it as far as scoring is concerned. I'm also counting the "\*" (star) for one point, despite it not being alphanumeric or underscore, because it is important to the story.

So my score is (4\*15)+(40\*1)=100 Potentially minus 10 for the two undefined variables, but that depends on your existing database.
> 17 votes

# Answer
# Shakespeare!

```
    The Infamous Hello World Program.

Romeo, a young man with a remarkable patience.
Juliet, a likewise young woman of remarkable grace.
Ophelia, a remarkable woman much in dispute with Hamlet.
Hamlet, the flatterer of Andersen Insulting A/S.

                    Act I: Hamlet's insults and flattery.

                    Scene I: The insulting of Romeo.

[Enter Hamlet and Romeo]

Hamlet:
 You lying stupid fatherless big smelly half-witted coward!
 You are as stupid as the difference between a handsome rich brave
 hero and thyself! Speak your mind!

 You are as brave as the sum of your fat little stuffed misused dusty
 old rotten codpiece and a beautiful fair warm peaceful sunny summer's
 day. You are as healthy as the difference between the sum of the
 sweetest reddest rose and my father and yourself! Speak your mind!

 You are as cowardly as the sum of yourself and the difference
 between a big mighty proud kingdom and a horse. Speak your mind.

 Speak your mind!

[Exit Romeo]

                    Scene II: The praising of Juliet.

[Enter Juliet]

Hamlet:
 Thou art as sweet as the sum of the sum of Romeo and his horse and his
 black cat! Speak thy mind!

[Exit Juliet]

                    Scene III: The praising of Ophelia.

[Enter Ophelia]

Hamlet:
 Thou art as lovely as the product of a large rural town and my amazing
 bottomless embroidered purse. Speak thy mind!

 Thou art as loving as the product of the bluest clearest sweetest sky
 and the sum of a squirrel and a white horse. Thou art as beautiful as
 the difference between Juliet and thyself. Speak thy mind!

[Exeunt Ophelia and Hamlet]

                    Act II: Behind Hamlet's back.

                    Scene I: Romeo and Juliet's conversation.

[Enter Romeo and Juliet]

Romeo:
 Speak your mind. You are as worried as the sum of yourself and the
 difference between my small smooth hamster and my nose. Speak your
 mind!

Juliet:
 Speak YOUR mind! You are as bad as Hamlet! You are as small as the
 difference between the square of the difference between my little pony
 and your big hairy hound and the cube of your sorry little
 codpiece. Speak your mind!

[Exit Romeo]

                    Scene II: Juliet and Ophelia's conversation.

[Enter Ophelia]

Juliet:
 Thou art as good as the quotient between Romeo and the sum of a small
 furry animal and a leech. Speak your mind!

Ophelia:
 Thou art as disgusting as the quotient between Romeo and twice the
 difference between a mistletoe and an oozing infected blister! Speak
 your mind!

[Exeunt]

```

Source(I have no clue how to write Shakespeare. Or read it for that matter). I'm also very confused as to how to score it. Also, I'm surprised nobody has posted the classic Char Lotte and Char Lie
> 10 votes

# Answer
Johnny's life story

```
kid=spawnKidFromParents(mother, father)
kid.live()
recycle()

def spawnKidFromParents(mother, father):
    kid=father.censor(mother)
    kid.name=Names.babyNames.orderBy("popularity").pop()
    return kid

```

person class (select methods only)

```
def live(self):
    try:
        while(self.health > 0):
            self.wakeUp()
            self.work()
            self.eat()
            self.sleep()
    except LossOfLifeException:
        self.closeEyes()

def wakeUp(self):
    while ( (self.laziness + self.calendar.today.importance * (1 - self.fatigue)) < random.randint(0,100)):
        pass

    self.openEyes()
    self.stand()
    self.dress()

def work(self):
    for money in range(self.wallet.EMPTY, self.wallet.MAX_CAPACITY):
        type()

def eat(self):
    while(self.hunger < self.FOOD_CAPACITY * 0.8 - self.diet):
        popcorn.pop()

def sleep(self):
    self.undress()
    self.layDown()
    self.closeEyes()
    pass

```
> 8 votes

# Answer
# Perl 3

**Not my work**, but I'm saddened that nobody has referenced **black perl** here yet...

```
BEFOREHAND: close door, each window & exit; wait until time.
    open spellbook, study, read (scan, select, tell us);
write it, print the hex while each watches,
    reverse its length, write again;
    kill spiders, pop them, chop, split, kill them.
        unlink arms, shift, wait & listen (listening, wait),
sort the flock (then, warn the "goats" & kill the "sheep");
    kill them, dump qualms, shift moralities,
    values aside, each one;
        die sheep! die to reverse the system
        you accept (reject, respect);
next step,
    kill the next sacrifice, each sacrifice,
    wait, redo ritual until "all the spirits are pleased";
    do it ("as they say").
do it(*everyone***must***participate***in***forbidden**s*e*x*).
return last victim; package body;
    exit crypt (time, times & "half a time") & close it,
    select (quickly) & warn your next victim;
AFTERWARDS: tell nobody.
    wait, wait until time;
    wait until next year, next decade;
        sleep, sleep, die yourself,
        die at last
# Larry Wall

```

This gem used to be valid code on Perl 3. Wikipedia says there are several updates for perl 5, but that's not the point really, is it?
> 7 votes

# Answer
# GW-BASIC: 1\*-5 + 7\*15 + 76\*1 = 176 points

```
LET criminal = "free"
FOR day = 1 to 100
    PRINT "evaluation"
NEXT day
IF criminal = "bad"
THEN
GOTO JAIL

```

Subtracted 5 points for undefined label `JAIL`.
> 6 votes

# Answer
# Python - 15\*28 + 1\*905 == 1325

```
Once="upon a time"
there=was="a";print"ce";he=wanted=to_marry=a=princess="but"
he="tried almost";all_princesses=but=they=were=not"real"and"";the="";print"ce"+wanted+a+'real';print"cess"
for princesss in`all_princesses`:
    the=princesss is not(`the`+`1`)

now=the;print"ce" is "sad"
he=was+"worried"+he+"would"+`not""`;ever=find=a;print"cess"
1=="evening"+a+"terrible storm occurred"
suddenly=a+princess+"appeared"+`but`+was+"soaked to"+`the`+"bone"
but=she=said=she=was=a=real=princess
`the`+"old queen";thought=we=will=soon=find=out;
but=she+said+"nothing"+but+"went to"+`the`+"bedroom where"+`the`+princess+"would sleep"and"put"+a+"pea beneath"+`20`+"mattresses";
the="";print"cess";having=slept=on=it=all=night=","+was+"asked how"+she+"slept";
while she in{"response","answered."}:
    print"ce,"+"my eyes"+were+"open"+all+night and "I"+was+"lying on"+a+"gigantic bowling ball.";

I=am="black"and"blue"+all+"over";"it" is "horrible"
this="confirmed"+she+was+a+real+princess
None==but+a+princess is "so sensitive"
print"ce" and she+"married"
for now in "good fortune"+he+"found"+a+real+princess:
    print"ce"and the+princess+"lived happily"+ever+"after"

```

My rendition of `The printcess [sic] and the pea`

Sadly, there is a syntax error on this line: `I=am="black"and"blue"+all+"over";"it" is "horrible"` and I can't seem to figure it out.
> 5 votes

# Answer
# Ruby, A LOT (44124 - 20 * 4 + 15 * 1 = 44504 points??)

"Short" story? Ha. So long that it's too long for a Stack Exchange answer! I had to remove about half of it because of the maximum character limit :(

Full code can be found here. It does not output anything. (Before, it for some reason crashed with a stack overflow, so I had to wrap it in `begin ... rescue SystemStackError`.)

Thanks, http://longestjokeintheworld.com!

```
def method_missing*a;end
class Module;def const_missing*a;end;end
(Kernel.methods+methods-[:eval,:object_id,:__send__]).each{|m|eval"def #{m}*a;end"}

begin talking using an interesting voice please to enhance the story
So theres a man crawling through the desert
Hed decided to try his SUV in_ a little bit of crosscountry travel had great fun zooming over the badlands and_ through the sand got lost hit a big rock and_ then_ he couldnt get it started again
There were no cell phone towers anywhere near so his cell phone was useless
He had no family his parents had died a few years before in_ an auto accident and_ his few friends had no idea he was out here
He stayed with the car for_ a day or_ so but his one bottle of water ran out
and_ he was getting thirsty
He thought maybe he knew the direction back now that hed paid attention to the sun and_ thought hed figured out which way was north so he decided to start walking
He figured he only had to go about some miles or_ so and_ hed be back to the small town hed gotten gas in_ last
He thinks about walking at night to avoid the heat and_ sun but based upon
how dark it actually was the night before and_ given that he has no flashlight hes afraid that hell break_ a leg or_ step on a rattlesnake
So
he puts on some sun block puts the rest in_ his pocket for_ reapplication
later brings an umbrella hed had in_ the back of the SUV with him to give
him a little shade pours the windshield wiper fluid into his water bottle
in_ case_ he gets that desperate brings his pocket knife in_ case_ he finds a cactus that looks like it might have water in_ it and_ heads out in_ the
direction he thinks is right
He walks for_ the entire day
By the end_ of the day hes really thirsty
Hes
been sweating all day and_ his lips are starting to crack
Hes reapplied the sunblock twice and_ tried to stay under the umbrella but he still feels sunburned
The windshield wiper fluid sloshing in_ the bottle in_ his pocket is really getting tempting now
He knows that its mainly water and_ some ethanol and_ coloring but he also knows that they add some kind of poison to it to keep people from drinking it
He wonders what the poison is and_
whether the poison would be worse than dying of thirst
He pushes on trying to get to that small town before dark
By the end_ of the day he starts getting worried
He figures hes been walking at least some miles an hour according to his watch for_ over some hours
That means that if_ his estimate was right that he should be close to the
town
But he doesnt recognize any of this
He had to cross a dry creek bed a mile or_ two back and_ he doesnt remember coming through it in_ the SUV
He figures that maybe he got his direction off just a little and_ that the dry creek bed was just off to one side of his path
He tells himself that hes close and_ that after dark hell start seeing the town lights over one of these hills and_ thatll be all he needs
As it gets dim enough that he starts stumbling over small rocks and_ things
he finds a spot and_ sits down to wait for_ full dark and_ the town lights
Full dark comes before he knows it
He must have dozed off
He stands back
up and_ turns all the way around
He sees nothing but stars
He wakes up the next_ morning feeling absolutely lousy
His eyes are gummy and_ his mouth and_ nose feel like theyre full of sand
He so thirsty that he cant even swallow
He barely got any sleep because it was so cold
Hed forgotten how cold it got at night in_ the desert and_ hadnt noticed it the night before because hed been in_ his car
He knows the Rule of Threes  three minutes without air three days without water three weeks without food  then_ you die
Some people can make it a little longer in_ the best situations
But the desert heat and_ having to walk and_ sweat isnt the best situation to be without water
He figures unless_ he finds water this is his last day
He rinses his mouth out with a little of the windshield wiper fluid
He waits a while_ after spitting that little bit out to see if_ his mouth goes numb or_ he feels dizzy or_ something
Has his mouth gone numb
Is it just in_
his mind
Hes not_ sure
Hell go a little farther and_ if_ he still doesnt
find water hell try drinking some of the fluid
Then he has to face his next_ harder question  which way does he go from here
Does he keep walking the same way he was yesterday assuming that he still knows which way that is or_ does he try a new direction
He has no idea what to do_
Looking at the hills and_ dunes around him he thinks he knows the direction he was heading before
Just going by a feeling he points himself somewhat to the left of that and_ starts walking
As he walks the day starts heating up
The desert too cold just a couple of hours before soon becomes an oven again
He sweats a little at first and_ then_ stops
He starts getting worried at that  when_ you stop sweating he knows that means youre in_ trouble  usually right before heat stroke
He decides that its time to try the windshield wiper fluid
He cant wait
any longer  if_ he passes out hes dead
He stops in_ the shade of a large
rock takes the bottle out opens it and_ takes a mouthful
He slowly
swallows it making it last as long as he can
It feels so good in_ his dry
and_ cracked throat that he doesnt even care about the nasty taste
He takes
another mouthful and_ makes it last too
Slowly he drinks half the bottle
He figures that since hes drinking it he might as well drink enough to
make some difference and_ keep himself from passing out
Hes quit worrying about the denaturing of the wiper fluid
If it kills him
it kills him  if_ he didnt drink it hed die anyway
Besides hes pretty
sure that whatever substance they denature the fluid with is just designed to make you sick  their way of keeping winos from buying cheap wiper fluid for_ the ethanol content
He can handle throwing up if_ it comes to that
He walks
He walks in_ the hot dry windless desert
Sand rocks hills
dunes the occasional scrawny cactus or_ dried bush
No sign of water
Sometimes hell see a little movement to one side or_ the other but whatever moved is usually gone before he can focus his eyes on it
Probably birds lizards or_ mice
Maybe snakes though they usually move more at night
Hes careful to stay away from the movements
After a while_ he begins to stagger
Hes not_ sure if_ its fatigue heat
stroke finally catching him or_ maybe he was wrong and_ the denaturing of the wiper fluid was worse than he thought
He tries to steady himself and_ keep going
After more walking he comes to a large stretch of sand
This is good
He
knows he passed over a stretch of sand in_ the SUV  he remembers doing
donuts in_ it
Or at least he thinks he remembers it  hes getting woozy
enough and_ tired enough that hes not_ sure what he remembers any more or_ if_
hes hallucinating
But he thinks he remembers it
So he heads off into it
trying to get to the other side hoping that it gets him closer to the town
He was heading for_ a town wasnt he
He thinks he was
He isnt sure any more
Hes not_ even sure how long hes been walking any more
Is it still morning
Or has it moved into afternoon and_ the sun is going down again
It must be afternoon  it seems like its been too long since he started out
He walks through the sand
After a while_ he comes to a big dune in_ the sand
This is bad
He doesnt
remember any dunes when_ driving over the sand in_ his SUV
Or at least he
doesnt think he remembers any
This is bad
But he has no other direction to go
Too late to turn back now
He figures
that hell get to the top of the dune and_ see if_ he can see anything from
there that helps him find the town
He keeps going up the dune
Halfway up he slips in_ the bad footing of the sand for_ the second or_ third
time and_ falls to his knees
He doesnt feel like getting back up  hell
just fall down again
So he keeps going up the dune on his hand and_ knees
While crawling if_ his throat werent so dry hed laugh
Hes finally
gotten to the hackneyed image of a man lost in_ the desert  crawling through
the sand on his hands and_ knees
If would be the perfect image he imagines if_ only his clothes were more ragged
The people crawling through the desert
in_ the cartoons always had ragged clothes
But his have lasted without any
rips so far
Somebody will probably find his dessicated corpse half buried in_ the sand years from now and_ his clothes will still be in_ fine shape
shake the sand out and_ a good wash and_ theyd be wearable again
He wishes his throat were wet enough to laugh
He coughs a little instead and_ it hurts
He finally makes it to the top of the sand dune
Now that hes at the top
he struggles a little but manages to stand up and_ look around
All he sees
is sand
Sand and_ more sand
Behind him about a mile away he thinks he
sees the rocky ground he left to head into this sand
Ahead of him more
dunes more sand
This isnt where he drove his SUV
This is Hell
Or close enough
Again he doesnt know what to do_
He decides to drink the rest of the wiper
fluid while_ figuring it out
He takes out the bottle and_ is removing the
cap when_ he glances to the side and_ sees something
Something in_ the sand
At the bottom of the dune off to the side he sees something strange
Its a flat area in_ the sand
He stops taking the cap of the bottle off and_ tries to look closer
The area seems to be circular
And its dark  darker than the sand
And there seems to be something in_ the middle of it but he cant tell what it is
He looks as hard as he can and_ still can tell from
here
Hes going to have to go down there and_ look
He puts the bottle back in_ his pocket and_ starts to stumble down the dune
After a few steps he realizes that hes in_ trouble  hes not_ going to be able to keep his balance
After a couple of more sliding tottering steps he falls and_ starts to roll down the dune
The sand it so hot when_ his body hits it that for_ a minute he thinks hes caught fire on the way down  like a movie car wreck flashing into flames as it goes over the cliff before it ever even hits the ground
He closes his eyes and_ mouth covers his face with his hands and_ waits to stop rolling
He stops at the bottom of the dune
After a minute or_ two he finds enough
energy to try to sit up and_ get the sand out of his face and_ clothes
When
he clears his eyes enough he looks around to make sure that the dark spot
in_ the sand it still there and_ he hadnt just imagined it
So seeing the large flat dark spot on the sand is still there he begins
to crawl towards it
Hed get up and_ walk towards it but he doesnt seem to
have the energy to get up and_ walk right now
He must be in_ the final stages
of dehydration he figures as he crawls
If this place in_ the sand doesnt
have water hell likely never make it anywhere else_
This is his last
chance
He gets closer and_ closer but still cant see whats in_ the middle of the
dark area
His eyes wont quite focus any more for_ some reason
And lifting
his head up to look takes so much effort that he gives up trying
He just
keeps crawling
Finally he reaches the area hed seen from the dune
It takes him a minute of crawling on it before he realizes that hes no longer on sand  hes now crawling on some kind of dark stone
Stone with some kind of marking on it  a pattern cut into the stone
Hes too tired to stand up and_ try to see what the pattern is  so he just keeps crawling
He crawls towards the center
where his blurry eyes still see something in_ the middle of the dark stone
area
His mind detached in_ a strange way notes that either his hands and_ knees are so burnt by the sand that they no longer feel pain or_ that this dark
stone in_ the middle of a burning desert with a pounding punishing sun
overhead doesnt seem to be hot
It almost feels cool
He considers lying
down on the nice cool surface
Cool dark stone
Not a good sign
He must be hallucinating this
Hes
probably in_ the middle of a patch of sand already lying face down and_
dying and_ just imagining this whole thing
A desert mirage
Soon the
beautiful women carrying pitchers of water will come up and_ start giving him
a drink
Then hell know hes gone
He decides against laying down on the cool stone
If hes going to die here
in_ the middle of this hallucination he at least wants to see whats in_ the
center before he goes
He keeps crawling
Its the third time that he hears the voice before he realizes what hes
hearing
He would swear that someone just said Greetings traveler
You do_
not_ look well
Do you hear me

He stops crawling
He tries to look up from where he is on his hands and_
knees but its too much effort to lift his head
So he tries something
different  he leans back and_ tries to sit up on the stone
After a few
seconds he catches his balance avoids falling on his face sits up and_
tries to focus his eyes
Blurry
He rubs his eyes with the back of his hands
and_ tries again
Better this time
Yep
He can see
Hes sitting in_ the middle of a large flat dark expanse
of stone
Directly next_ to him about three feet away is a white post or_
pole about two inches in_ diameter and_ sticking up about four or_ five feet
out of the stone at an angle
And wrapped around this white rod tail with rattle on it hovering and_
seeming to be ready to start rattling is what must be a fifteen foot long
desert diamondback rattlesnake looking directly at him
He stares at the snake in_ shock
He doesnt have the energy to get up and_
run away
He doesnt even have the energy to crawl away
This is it his
final resting place
No matter what happens hes not_ going to be able to
move from this spot
Well at least dying of a bite from this monster should be quicker than
dying of thirst
Hell face his end_ like a man
He struggles to sit up a
little straighter
The snake keeps watching him
He lifts one hand and_ waves
it in_ the snakes direction feebly
The snake watches the hand for_ a
moment then_ goes back to watching the man looking into his eyes
Hmmm
Maybe the snake had no interest in_ biting him
It hadnt rattled yet
that was a good sign
Maybe he wasnt going to die of snake bite after all
He then_ remembers that hed looked up when_ hed reached the center here
because he thought hed heard a voice
He was still very woozy  he was
likely to pass out soon the sun still beat down on him even though he was
now on cool stone
He still didnt have anything to drink
But maybe he had
actually heard a voice
This stone didnt look natural
Nor did that white
post sticking up out of the stone
Someone had to have built this
Maybe
they were still nearby
Maybe that was who talked to him
Maybe this snake
was even their pet and_ thats why it wasnt biting
He tries to clear his throat to say Hello but his throat is too dry
All
that comes out is a coughing or_ wheezing sound
There is no way hes going
to be able to talk without something to drink
He feels his pocket and_ the
bottle with the wiper fluid is still there
He shakily pulls the bottle out
almost losing his balance and_ falling on his back in_ the process
This isnt
good
He doesnt have much time left by his reckoning before he passes
out
He gets the lid off of the bottle manages to get the bottle to his lips
and_ pours some of the fluid into his mouth
He sloshes it around and_ then_
swallows it
He coughs a little
His throat feels better
Maybe he can talk
now
He tries again
Ignoring the snake he turns to look around him hoping to
spot the owner of this place and_ croaks out Hello
Is there anyone here

He hears from his side Greetings
What is it that you want

He turns his head back towards the snake
Thats where the sound had seemed
to come from
The only thing he can think of is that there must be a
speaker hidden under the snake or_ maybe built into that post
He decides
to try asking for_ help
Please he croaks again suddenly feeling dizzy Id love to not_ be
thirsty any more
Ive been a long time without water
Can you help me

Looking in_ the direction of the snake hoping to see where the voice was
coming from this time he is shocked to see the snake rear back open its
mouth and_ speak
He hears it say as the dizziness overtakes him and_ he
falls forward face first on the stone Very well
Coming up

A piercing pain shoots through his shoulder
Suddenly he is awake
He sits
up and_ grabs his shoulder wincing at the throbbing pain
Hes momentarily
disoriented as he looks around and_ then_ he remembers  the crawl across the
sand the dark area of stone the snake
He sees the snake still wrapped
around the tilted white post still looking at him
He reaches up and_ feels his shoulder where it hurts
It feels slightly wet
He pulls his fingers away and_ looks at them  blood
He feels his shoulder
again  his shirt has what feels like two holes in_ it  two puncture holes
they match up with the two aching spots of pain on his shoulder
He had been
bitten
By the snake
Itll feel better in_ a minute He looks up  its the snake talking
He
hadnt dreamed it
Suddenly he notices  hes not_ dizzy any more
And more
importantly hes not_ thirsty any more  at all
Have I died
Is this the afterlife
Why are you biting me in_ the
afterlife

Sorry about that but I had to bite you says the snake
Thats the way I
work
It all comes through the bite
Think of it as natural medicine

You bit me to help me
Why arent I thirsty any more
Did you give me a
drink before you bit me
How did I drink enough while_ unconscious to not_ be
thirsty any more
I havent had a drink for_ over two days
Well except for_
the windshield wiper fluid
hold it how in_ the world does a snake talk
Are you real
Are you some sort of Disney animation

No says the snake Im real
As real as you or_ anyone is anyway
I
didnt give you a drink
I bit you
Thats how it works  its what I do_
I
bite
I dont have hands to give you a drink even if_ I had water just
sitting around here

The man sat stunned for_ a minute
Here he was sitting in_ the middle of the
desert on some strange stone that should be hot but wasnt talking to a
snake that could talk back and_ had just bitten him
And he felt better
Not
great  he was still starving and_ exhausted but much better  he was no
longer thirsty
He had started to sweat again but only slightly
He felt
hot in_ this sun but it was starting to get lower in_ the sky and_ the cool
stone beneath him was a relief he could notice now that he was no longer
dying of thirst
I might suggest that we take care of that methanol you now have in_ your
system with the next_ request continued the snake
I can guess why you
drank it but Im not_ sure how much you drank or_ how much methanol was left
in_ the wiper fluid
That stuff is nasty
Itll make you go blind in_ a day or_
two if_ you drank enough of it

Ummm nnext request said the man
He put his hand back on his hurting
shoulder and_ backed away from the snake a little
Thats the way it works
If you like that is explained the snake
You
get three requests
Call them wishes if_ you wish The snake grinned at his
own joke and_ the man drew back a little further from the show of fangs
But there are rules the snake continued
The first request is free
The
second requires an agreement of secrecy
The third requires the binding of
responsibility The snake looks at the man seriously
By the way the snake says suddenly my name is Nathan
Old Nathan
Samuel used to call me
He gave me the name
Before that most of the Bound
used to just call me Snake
But that got old and_ Samuel wouldnt stand
for_ it
He said that anything that could talk needed a name
He was big into
names
You can call me Nate if_ you wish Again the snake grinned
Sorry
if_ I dont offer to shake but I think you can understand  my shake sounds
somewhat threatening The snake give his rattle a little shake
Umm my name is Jack said the man trying to absorb all of this
Jack
Samson
Can I ask you a question Jack says suddenly
What happened to the
poisonumm in_ your bite
Why arent I dying now
How did you do_ that
What do_ you mean by thats how you work

Thats more than one question grins Nate
But Ill still try to answer
all of them
First yes you can ask me a question The snakes grin gets
wider
Second the poison is in_ you
It changed you
You now no longer need
to drink
Thats what you asked for_
Or well technically you asked to not_
be thirsty any more  but any more is such a vague term
I decided to make
it permanent  now as long as you live you shouldnt need to drink much at
all
Your body will conserve water very efficiently
You should be able to
get enough just from the food you eat  much like a creature of the desert
Youve been changed
For the third question Nate continues you are still dying
Besides the
effects of that methanol in_ your system youre a man  and_ men are mortal
In your current state I give you no more than about another some years
Assuming you get out of this desert alive that is Nate seemed vastly
amused at his own humor and_ continued his wide grin
As for_ the fourth question Nate said looking more serious as far as Jack
could tell as Jack was just now working on his ability to read
talkingsnake emotions from snake facial features first you have to agree
to make a second request and_ become bound by the secrecy or_ I cant tell
you

Wait joked Jack isnt this where you say you could tell me but youd
have to kill me

I thought that was implied Nate continued to look serious
Ummmyeah Jack leaned back a little as he remembered again that he was
talking to a fifteen foot poisonous reptile with a reputation for_ having a
nasty temper
So what is this Bound by Secrecy stuff and_ can you really
stop the effects of the methanol Jack thought for_ a second
And what do_
you mean methanol anyway
I thought these days they use ethanol in_ wiper
fluid and_ just denature it

They may I dont really know said Nate
I havent gotten out in_ a
while_
Maybe they do_
All I know is that I smell methanol on your breath and_
on that bottle in_ your pocket
And the blue color of the liquid when_ you
pulled it out to drink some let me guess that it was wiper fluid
I assume
that they still color wiper fluid blue

Yeah they do_ said Jack
I figured replied Nate
As for_ being bound by secrecy  with the
fulfillment of your next_ request you will be bound to say nothing about me
this place or_ any of the information I will tell you after that when_ you
decide to go back out to your kind
You wont be allowed to talk about me
write about me use sign language charades or_ even act in_ a way that will
lead someone to guess correctly about me
Youll be bound to secrecy
Of
course Ill also ask you to promise not_ to give me away and_ as Im
guessing that youre a man of your word youll never test the binding
anyway so you wont notice Nate said the last part with utter confidence
Jack who had always prided himself on being a man of his word felt a
little nervous at this
Ummm hey Nate who are you
How did you know
that
Are you umm omniscient or_ something

Well Jack said Nate sadly I cant tell you that unless_ you make the
second request Nate looked away for_ a minute then_ looked back
Umm well ok said Jack what is this about a second request
What can I
ask for_
Are you allowed to tell me that

Sure said Nate brightening
Youre allowed to ask for_ changes
Changes
to yourself
Theyre like wishes but they can only affect you
Oh and_
before you ask I cant give you immortality
Or omniscience
Or
omnipresence for_ that matter
Though I might be able to make you gaseous
and_ yet remain alive and_ then_ you could spread through the atmosphere and_
sort of be omnipresent
But what good would that be  you still wouldnt be
omniscient and_ thus still could only focus on one thing at a time
Not very
useful at least in_ my opinion Nate stopped when_ he realized that Jack was
staring at him
Well anyway continued Nate Id probably suggest giving you permanent
good health
It would negate the methanol now in_ your system youd be
immune to most poisons and_ diseases and_ youd tend to live a very long
time barring accident of course

```

... story goes on for much longer ...

```
rescue SystemStackError;end

```
> 4 votes

# Answer
# Javascript:

```
2 * 'households, both alike' in (dignity={})
'In fair Verona', where = we = lay = our = scene ={}
Where = civil= 'blood',  makes= civil ||hands ||unclean
From= forth = the =fatal =loins =of = 'these two foes';
A = pair=2; of["star-cross'd lovers"]; take = 2 || their || life

```
> 4 votes

# Answer
# 6502 Assembly Language

A story about a girl named Tya.

```
    TYA
    AND #1
    TAX
MAN:
    JMP *+4
A:
    BIT #4
THEIR:
.byte "DONKEY"
    EOR .byte "."

```
> 4 votes

# Answer
# JavaScript: 7\*15 + 127\*1 = 232 points

```
company = 'big'
for (employee in company) {
    if (/quality/.test(employee) == 'bad') {
        employee = function janitor() {
            return 'less money'
        }
    } else {
        employee = function boss() {
            return 'money'
        }
    }
}

```
> 3 votes

# Answer
**PHP**

Have fun:)

```
<?php

goto:bar;

bar:
$notdrunk = 0
while ($notdrunk <= rand(5, 60)) {

    drink(beer);
    $notdrunk++;
}

if ($notdrunk >= rand(10, 59)) {

goto home;

}

home:

$vomit = true;

if ($notdrunk > 50) {

die();

}

?>

```
> 3 votes

# Answer
## Chinese

This ancient text may have originated around 2014 AD:

```
了一人说你于一嘁力

```

A translation to English:

> Knowingly, a man persuaded you in one whispering sound power...
> 3 votes

# Answer
# Python, 1\*94 + 12\*15 = 274

I counted one for `=`, but didn't count the extra `f` in `def finitely()`. Also, the function is infinitely recursive, causing the call stack to be full of True "love".

```
def finitely(one=True):
    if all([any([one])is"loving"or True]):return"love"in finitely()
    else:return"sadness"
"love"in finitely()

```

English:

Definitely one (equals) True. If all anyone is loving or True, return love infinitely, else return sadness. Love infinitely.
> 3 votes

# Answer
## Delphi

I'm new and I don't really understand the scoring. So if someone can help me with that, it would be great :)

```
procedure Life;
var alive, fullbladder, fullstomach: boolean;
  bladder, stomach, human: tobject;
  timer:TTimer;
  procedure sleepRecommended;begin sleep(((8*60)*60)*1000) {hours to ms} end;
  procedure checkNeeds(sender:tobject); begin if fullbladder then bladder.empty; if fullstomach then stomach.empty; end;
  procedure GoToWork;begin human.PretendToWorkAndGoOnCodeGolfInstead; end;
  procedure GoHome;begin human.celebrate; end;
begin
  timer:=ttimer.create;timer.interval := (60*60)*1000; timer.OnTimer := checkNeeds;

  while alive do
  begin
    sleepRecommended;
    timer.Enabled := true;
    human.eat;
    goToWork;
    GoHome;
    human.Eat;
  end;

```
> 1 votes

# Answer
I'm a bit late to this, but every time I use firstChild in

# Javascript

I think:

```
function Rumpelstiltskin(straw){
    straw = straw.replace(straw, "gold");
    if(!(knowName=="Rumpelstiltskin")){
         document.getElementById('millersDaughter').deleteChild(document.getElementById('millersDaughter').firstChild);//Stories are documents and characters are elements of the story.
    }else{
         return "angry";
    }
}

```

Points:

2 undefined (knowName and the html node millersDaughter)

7 built in keywords (function, if, document.getElementById('millersDaughter'), deleteChild(...),firstChild,else,return)

I don't know how to count letters, every letter, letters in strings? Tell me.

points = 95 + letters
> 1 votes

# Answer
## Windows Command Script - 720

Calculated with 210 + 34\*15

*Warning: this may or may not make any sense :)*

```
IF "%time%"=="15:00" GOTO :workplace
:workplace
START SHIFT
RECOVER TASKLIST | FIND "todo" | SORT %priority% > tasks
FOR /f %%t IN (tasks) DO (
    SET %%t=Done! | VERIFY
    IF "%TIME%"=="17:00" START BREAK
    IF "%TIME%"=="19:00" START BREAK
    IF "%TIME%"=="21:00" START BREAK
    IF "%RANDOM:~,1%"=="1" START BREAK
    IF "%TIME%"=="23:00" EXIT SHIFT
)

```
> 0 votes

# Answer
# Fortran 95

Not really a story, but a short poem. Just sharing it for fun:

```
logical :: I, u = .TRUE.
do while (I); write(*,*) aPoem, 4, u;
stop; I = .FALSE.;
end do; end ! Adieu!

```

Considering the sign `=` as the verb to be, it reads as:

```
Logical eye, you are true
Do while I write a poem for you
Stop, I am false...
End, do end! Adieu!

```
> 0 votes

# Answer
# Google Sheets, 72 `\w` characters + 5 * 15 reserved functions = 147

Make named ranges anywhere:

* Call one "Birth"
* Call one "Death"

`=IF(OR(ISBETWEEN("meaning",Birth,Death),NOT(ISBETWEEN("meaning",Birth,Death))),"One dies anyway")` or

```
=IF(
  OR(
    ISBETWEEN("meaning",Birth,Death),
    NOT(ISBETWEEN("meaning",Birth,Death))
  ),"One dies anyway"
)

```

> If `"meaning"` between *Birth* and *Death*, or not `"meaning"` between *Birth* and *Death*, `One dies anyway`.

I also like this one:

`="My grandpa's deck "&IF(COUNTIF(GrandpasDeck,"the unstoppable Exodia")=1,"has no","has")&" pathetic cards"`
> 0 votes

---
Tags: popularity-contest, word-puzzle
---


# Question
Title: Compare positions of integers in this sequence
A001057 is one way to represent an integer as a natural number. It lists them according to the following pattern:

```
0, 1, -1, 2, -2, 3, -3, 4, -4, ...

```

In this challenge, you'll take two distinct integers as input and return which is at a higher index in this enumeration.

Take `-2` and `1` as an example: `-2` comes after `1`, so it would be returned.

You may also choose to instead return the smaller integer, or one of two consistent values (such as `0` or `1`) to indicate which is higher or lower. Truthy/falsy values as output are not allowed.

**Test cases:**

```
 0   1       1
 1   0       1
 0  -1      -1
-1   0      -1
-1   1      -1
 1  -1      -1
 1  -2      -2
 1   2       2
-1  -2      -2
-1   2       2

```

# Answer
> 11 votes
# Python, 20 bytes

```
lambda x,y:x*x>y*y-y

```

Try it online!

Checks whether \\$x^2\>y^2-y \\$.

Outputs `True/False` for whether `x` comes after `y` in the listing. Note that we're not asked handle the case `x==y`.

To see that this works, note that each of the `x*x` value in the table is greater than all the `y*y-y` values to the left of it, but none to the right of it.

```
       0  1  -1  2  -2  3  -3   4  -4 ...
x*x:   0  1   1  4   4  9   9  16  16 ...
y*y-y: 0  0   2  2   6  6  12  12  20 ...

```

The idea is that the entries come in pairs `+n, -n` (except 0 once), so comparing squares works to check if one input has a bigger absolute value than the other. Then, changing \\$y^2\\$ to \\$y^2-y\\$ in the second entry, makes `+n` "lose" to `-n`, but is a small enough shift compared to the difference between consecutive squares that it doesn't mess up comparisons between different squares.

# Answer
> 6 votes
# , 8 bytes

```
>&(-3^|)

```

Try it online!

Or verbose: `(x - 3 ^ abs(x)) > (y - 3 ^ abs(y))`. This maps the inputs to the following sequence to compare them in:

```
 0  1 _1  2  _2   3  _3   4  _4    5   _5
_1 _2 _4 _7 _11 _24 _30 _77 _85 _238 _248

```

If sorted input as output is allowed, then 7 byte `/:*.@%:` is another fun way to sort `/:` the input list: `*.` generates `(length, angle)` pairs of the square root `%:` of `x` (which results in complex numbers for negative values):

```
 0       0      0
 1       1      0
_1       1 1.5708
 2 1.41421      0
_2 1.41421 1.5708
 3 1.73205      0
_3 1.73205 1.5708

```

# Answer
> 5 votes
# Husk, 7 bytes

```
F>m€Θİ±

```

Try it online!

Returns `1` if the second is larger than the first, `0` otherwise

# Answer
> 5 votes
# Desmos, 21 bytes

```

f(x,y)=\{xx-x<yy,0\}

```

(Newline is required)

*Edit: Just noticed that xnor's answer is very similar to mines, but I found this independently.*

Function is \\$f(x,y)\\$, and it returns \\$0\\$ if \\$x\\$ has a higher index, otherwise returns \\$1\\$.

This seems to work, but I just randomly stumbled upon it, so I can't explain how it works.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 4 votes
# Vyxal, 5 bytes

```
²?Ḣ+⇧

```

Try it Online!

Takes input as a list and returns \[1,0\] for first being bigger, \[0,1\] for second being bigger.

```
²     # [x^2, y^2]
 ?Ḣ   # [y]
   +  # [x^2+y, y^2]
    ⇧ # Grade up

```

# Answer
> 3 votes
# Jelly, 5 bytes

```
²Ḥ_ṠỤ

```

Try It Online!

-1 byte thanks to ovs
-1 byte thanks to Unrelated String

Returns `[1, 2]` if the first integer comes first and `[2, 1]` for the second integer.

```
²Ḥ_ṠỤ    Main Link; accepts a list
²        x ** 2
 Ḥ       2 * (x ** 2)
   _Ṡ    2 * (x ** 2) - sign(x)
     Ụ   Grade up

```

```
 0 => 0
 1 => 1
-1 => 3
 2 => 7
-2 => 9
 3 => 17
-3 => 19
...

```

# Answer
> 3 votes
# Python 3, ~~29~~ 26 bytes

Returns `True` if `a` is a at a higher index than `b`, `False` otherwise.

```
lambda a,b:a*a+(a<0)/2>b*b

```

Try it online!

# Answer
> 2 votes
# Vyxal, 7 bytes

```
ȧ4*?±-⇧

```

Try it Online!

Oh yes, jelly port. Very fun.

`⟨0|1⟩` for second integer being yes, `⟨1|0⟩` for first integer being yes.

## Explained

```
ȧ4*?±-⇧
ȧ4*     # 4 * abs(input) [vectorised] # call this x
   ?±   # sign_of(input) [vectorised - <0 = -1, =0 = 0, >0 = 1] # call this y
     -  # x - y [vectorised element-wise] # call this z
      ⇧ # indexes of z in an order such that they would arrange z to be sorted ascending

```

# Answer
> 2 votes
# Jelly, 4 bytes

```
Ḥc2Ụ

```

Try it online!

Alternative grade-up solution. Uses `(2n)C2 = n(2n-1)` as the grade key function. This function maps `0, 1, -1, 2, -2, 3, -3, ...` to `0, 1, 3, 6, 10, 15, 21, ...`, i.e. the triangular numbers.

This allows a shorter APL solution:

# APL(Dyalog Unicode), 5 bytes SBCS

```
⍋2!+⍨

```

Try it on APLgolf!

# Answer
> 2 votes
# Japt, 5 bytes

Outputs `true` for the first number being higher or `false` for the second.

```
²+V>²

```

Try it

# Answer
> 2 votes
# COW, 183 bytes

```
oomMMMmoOMMMmoOoomMMMmoOMMMmOomOoMMMmoOmoOmoOMMMMMMmoOMMMmOomOoMMMmoOmoOmoOMMMMMMmoOMMMmOoMOOmOomOomOomOomOomOoMOOMOomoOmoOMOOMoOmoOmoOMOOMoOmoOmoOMOoMMMOOOmooOOOmooOOOmooMMMmoomoOOOM

```

Try it online!

Returns the smaller integer. It increases and decreases both, the first to reach **0** (with precedence to the decreasing one) is the smaller.

```
[0]: n to be decreased   [1]: n   [2]: m to be increased   [3]: m   [4]: n to be increased   [5]: n   [6]: m to be decreased   [7]: m

i=>=>i=>=<<=>>>==>=<<=>>>==>=<    | set up memory cells as above
[                                 | loop until a cell reaches 0
    <<<<<<[->>[+>>[+>>-=*]*]*]=   | [0]-- [2]++ [4]++ [6]--
]>o                               | print the redundant copy of the smaller

moo ]    mOo <    MOo -    OOO *    OOM i
MOO [    moO >    MoO +    MMM =    oom o

```

# Answer
> 1 votes
# Python 2, 30 bytes

```
lambda x,y:(x*x,x<0)>(y*y,y<0)
```

Attempt This Online!

This is one of those irritating ones that can't be shortened with a loop because the loop is only over 2 items.

The `abs(x)` -\> `x*x` trick was taken from ovs' answer.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 19 bytes

```
Most@*SortBy[-# #&]

```

Try it online!

-23 bytes from @att

# Answer
> 1 votes
# APL (Dyalog Unicode), 6 bytes

A port of hyper-neutrino's Jelly answer. Outputs are swapped.

```
⍋×-4×|

```

Try it online! `g` gets the *"higher"* number according to the output.

# Answer
> 1 votes
# C (gcc), 20 bytes

```
f(a,b){a=a*a>b*b-b;}

```

Try it online!

Port of xnor's Python answer.

# Answer
> 1 votes
# Scala, 37 bytes

```
_.maxBy(x=>if(x>0)x*2-1 else x.abs*2)

```

Try it online!

Very simple, simply takes a list containing the two number, maps each to its index in the sequence, and finds the max according to that.

# Answer
> 1 votes
# Jelly, ~~5~~ 4 bytes

```
²+ḊỤ

```

Try it online!

~~Terrible~~ port of xnor's Python solution, also stealing from hyper-neutrino's Jelly solution ovs's output format (`[1, 2]` if `y` is greater, `[2, 1]` if `x` is greater). Takes input as a list `[x, y]`.

```
²       [x^2, y^2]
 +      plus
  Ḋ     [y]:
²+Ḋ     [x^2 + y, y^2].
   Ụ    Grade up.

```

# Answer
> 0 votes
# Charcoal, 10 bytes

```
Ｉ⌊Φθ⁼↔ι⌈↔θ

```

Try it online! Link is to verbose version of code. Takes input as a list of two (actually arbitrary many) integers (which need not be distinct). Explanation: Outputs the element with the greatest absolute value, or the less of two elements tied for absolute value. Explanation:

```
   θ        Input list
  Φ         Filter where
      ι     Current element
     ↔      Absolute value
    ⁼       Equals
         θ  Input list
        ↔   Vectorised absolute value
       ⌈    Take the maximum
 ⌊          Take the minimum
Ｉ           Cast to string
            Implicitly print

```

Actually a port of @xnor's Python answer would probably be only 9 bytes but that would be boring.

# Answer
> 0 votes
# K (oK), 14 bytes

```
f:{x*x>-y+y*y}

```

Try it online!

---
Tags: code-golf, math, decision-problem, integer
---


title: Make it prime with the smallest suffix

text:
# Question
Title: Make it prime with the smallest suffix
Given a positive integer as input, output the smallest positive integer such that appending its digits (in base 10) to the end of the input number will form a prime number.

## Examples

```
1     -->   1
2     -->   3
8     -->   3
9     -->   7
11    -->   3
20    -->  11
43    -->   1
134   -->  11
3492  -->  11
3493  -->   9
65595 -->  19

```

## Rules and Scoring

* This is code golf, so shortest code wins
* Standard rules and loopholes apply
* Use any convenient I/O format
* The largest concatenated number (which is larger than both the input and output) your solution supports must be at least \\$2^{53} - 1\\$. (This is the largest odd integer that can be represented with double precision floats)
* Leading zeros should not be added to numbers before appending them to the input number
* Primality tests must be exact

# Answer
> 10 votes
# Jelly, 7 bytes

```
1ṭVẒɗ1#

```

Try it online!

## How it works

```
1ṭVẒɗ1# - Main link. Takes n on the left
    ɗ   - Define a dyad f(k, n) from the previous 3 links:
 ṭ      -   Tack; Yield [n, k]
  V     -   Eval; Smash together into a single integer
   Ẓ    -   Is prime?
1    1# - Starting from k = 1, find the first k such that f(k, n) is true

```

# Answer
> 7 votes
# JavaScript (ES6),  ~~51~~  50 bytes

*Saved 1 byte thanks to @l4m2*

Expects the input number as a string.

```
f=(n,k)=>eval('for(d=x=n+k;x%--d;)d')<3?k:f(n,-~k)

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 5 bytes

05AB1E treating strings and integers equal helps again.

```
∞.Δ«p

```

Try it online! or Try all cases

```
∞      # in the list of positive integers
 .Δ    # find the first one
   «   # that, when concatenated to the input,
    p  # is a prime number

```

# Answer
> 4 votes
# Husk, ~~9~~ 8 bytes

Saved 1 byte thanks to Leo

```
ḟöṗr+⁰s1

```

Try it online!

Explanation:

```
ḟöṗr+⁰s
ḟ         Find first number at least
       1  1 such that
      s   when it's converted to a string,
    +⁰    and appended to the input
   r      and read as an integer,
  ṗ       the result is prime

```

# Answer
> 4 votes
# Brachylog, 5 bytes

```
;.cṗ>

```

Try it online!

`,.ṗ>` seems like it should work, but `,` seems to be somewhat bugged with unbound variables. It's a bit hard to tell why.

```
;.c      The input's concatenation with the output
   ṗ     is a prime number
    >    greater than the output.

```

Uses `>` rather than  so as to force the output to be an integer--otherwise, it would be an empty list for prime inputs.

# Answer
> 4 votes
# , ~~64~~ ~~62~~ ~~61~~ 60 bytes

```
function(n){while(sum(!(x=n*10^nchar(+F)+F)%%1:x)>2)F=F+1;F}

```

Try it online!

*-1 byte thanks to @Dominic's idea and then another one (in both versions).*

### , ~~60~~ 59 bytes

```
function(n){while(sum(!(x=n*10^nchar(F)+F)%%1:x)>2)F=F+1;F}

```

Try it online!

Slower version from @Dominic.

Abuses the fact that `n*10^5` will never be prime (but checks it in the first iteration, that's why it's so slow).

# Answer
> 3 votes
# Japt, 8 bytes

```
ÈsiU j}a

```

Try it

```
ÈsiU j}a     :Implicit input of integer U
È            :Function taking an integer as an argument
 s           :  Convert to string
  iU         :  Prepend U and convert back
     j       :  Is prime?
      }      :End function
       a     :Get the first integer >=0 that returns true

```

# Answer
> 3 votes
# Stax, 8 bytes

```
É3º╩(\╝░

```

Run and debug it

## Explanation

```
wi;i\$e|p!
w          while
   |p! end result is not prime, do:
 i          push index
  ;i        push input and index again
\$      stringify
      e     convert to int
           final index is implicitly output

```

# Answer
> 2 votes
# Python 3, 82 bytes

```
def x(n,i=1):k=int(f"{n}{i}");return all(k%j for j in range(2,k))and i or x(n,i+1)

```

Try it online!

-30 bytes thanks to @Manish Kundu, @MarcMush and @ophact

# Answer
> 2 votes
# , 22 bytes

```
>:@]^:(0 p:,&.":)^:_&1

```

Try it online!

Increment counter `>:@]` while `^:_` original number catted with counter `,&.":` is not prime `0 p:`, with counter starting at 1 `&1`.

# Answer
> 2 votes
# Pyth, 6 bytes

```
fP_s+z

```

Test suite

Fairly different approach to the existing Pyth answer.

Explanation:

```
fP_s+z  | Full code
fP_s+zT | with implicit variables
--------+-----------------------------------
f       | first positive integer T such that
    +zT | input and T concatenated
   s    | as an integer
 P_     | is prime

```

# Answer
> 2 votes
# Ruby, 58 bytes

```
->n,r=1{(2...x=([n,r]*'').to_i).any?{|c|x%c<1}?f[n,r+1]:r}

```

Try it online!

# Answer
> 2 votes
# Lyxal, 7 bytes

```
≬?pæṅJṅ

```

Try it Online!

Uses magic. -1 thanks to @vyxal.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 48 bytes

```
(k=0;While[!PrimeQ[10^⌊Log10@++k+1⌋#+k]];k)&

```

Increasing k until n\*floor(10^(Log10(k)+1)+k) is prime
Try it online!

# Answer
> 1 votes
# Pyth, 13 bytes

```
W!P_s+z=+Z1;Z

```

Try it online!

# Explanation

```
Z     # Set to 0 by default
z     # Input, taken as a string
=Z+Z1 # Increment Z by 1 and assign Z to it
s+z   # Concatenate z with and convert to integer
W!P_  # While it is not prime
;Z    # Print Z after the while loop finishes

```

*thanks Citty for -1 byte*

# Answer
> 1 votes
# JavaScript, 65 bytes

```
f=(n,x=1)=>[...Array((i=n+x)-2)].every((_,e)=>i%(e+2))?x:f(n,x+1)

```

Feel like this is way too long for some reason. I'm not very good at primality testing, so that takes up the vast majority of my code. Basically checks if every number between 2 and `n+[x]` \[the number with x appended at the end\] yields a nonzero remainder when it divides `i` \[`n+[x]`\]. If so, return `x`, otherwise call `f` again.

*-4 bytes thanks to @Arnauld.*

*saved 2 more bytes by taking the input number as a string.*

# Answer
> 1 votes
# Julia 0.4, 39 bytes

with julia 0.4 for `isprime` and `parse`

```
>(x,n=1)=isprime(parse("$x$n"))?n:x>n+1

```

Try it online!

# Answer
> 1 votes
# Python 3.8, 80 bytes

```
f=lambda n,a=0:math.perm(p:=int(n+str(a)))**2%-~p<1and f(n,a+1)or-~a
import math

```

Try it online!

Inputs \\$n\\$ as a string and returns the smallest positive integer that makes a prime when appended to \\$n\\$.

# Answer
> 1 votes
# Retina, 53 bytes

```
.+
_;$&;_10**
+`((.+;).+);(__+)\3+$
_$1;$($1$.2)*
\G_

```

Try it online! Link includes less slower test cases. Explanation:

```
.+
_;$&;_10**

```

Create a working area with the suffix in unary (initially 1), the input prefix, and the current resulting integer in unary (initially one more than ten times the input).

```
((.+;).+);(__+)\3+$

```

Match the suffix and prefix, the prefix, and a factor of the resulting integer.

```
_$1;$($1$.2)*

```

Increment the suffix, keeping the prefix, and calculate the new integer. `$1` actually contains the unary suffix as well as the prefix, but Retina's `*` operator only considers the numeric portion of the parameter. Additionally, the separator is included in the capture of the suffix, thus automatically incrementing it when its length is taken.

```
+`

```

Repeatedly increment the suffix until a prime number is found.

```
\G_

```

Convert the suffix to decimal.

# Answer
> 1 votes
# Perl 5, 54 bytes

```
sub{$i=pop;$n=1;$n++while(1x"$i$n")=~/^(11+?)\1+$/;$n}

```

Try it online!

# Perl 5, 65 bytes

A slightly different approach, but 11 bytes longer:

```
sub f{($i,$t)=@_;!$t||(grep"$i$t"%$_<1,2..$i.$t-1)?f($i,$t+1):$t}

```

Try it online!

# Answer
> 1 votes
# Python 2, 73 bytes

```
def f(n,x=1):k=int(n+`x`);return all(k%i for i in range(2,k))or-~f(n,x+1)

```

Takes input as a string (e.g. `f("65595")`)

Thanks to `ovs`

# Answer
> 0 votes
# Raku, 28 bytes

```
{first ($_~*).is-prime,1..*}

```

Try it online!

---
Tags: code-golf, primes
---


title: Ordered, linear, affine, or relevant?

text:
# Question
Title: Ordered, linear, affine, or relevant?
## Background

Supplementary reading 1, Supplementary reading 2

Linear lambda calculus is a limited form of lambda calculus, where every bound variable must be used exactly once. For example, `\a b c d e -> a b (d c) e` is a valid term in linear lambda calculus. When embedded as a logic system, this enforces each input to be consumed exactly once. The equivalents in logic/type/language theory are called linear logic, linear type, and linear language respectively.

Ordered lambda calculus is a more limited version: it requires the variables to be used in the order they are introduced. `\a b c d e -> a (b c) (d e)` is such an example.

Affine and relevant lambda calculi are relaxed versions of linear lambda calculus.

* Affine: each variable must be used at most once. `\a b c d e -> a (d c) e`
* Relevant: each variable must be used at least once. `\a b c d -> a (c b) (d c)`

If omitting and duplicating a variable are both allowed, we get plain lambda calculus.

These have interesting relationship with BCKW combinator calculus:

* Ordered lambda calculus can be represented using just B and I combinators. (I is needed to represent `\a -> a`.)
```
\a b c d e -> a (b c) (d e)
\a b c d -> B (a (b c)) d
\a b c -> B (a (b c))
\a b -> B B (B a b)
\a -> B (B B) (B a)
B (B (B B)) B

```
* Linear lambda calculus can be represented using B and C combinators. (I is equal to BCC, and is used only for simplicity.)
```
\a b c d e -> a b (d c) e
\a b c d -> a b (d c)
\a b c -> B (a b) (C I c)
\a b -> B (B (a b)) (C I)
\a -> C (B B (B B a)) (C I)
C (B C (B (B B) (B B))) (C I)

```
* Affine lambda calculus can be represented using BCK. K allows to delete unused variables.
```
\a b c d e -> a (d c) e
\a b c d -> a (d c)
\a b c -> B a (C I c)
\a b -> B (B a) (C I)
\a -> K (B (B a) (C I))
B K (C (B B B) (C I))

```
* Relevant lambda calculus can be represented using BCW. W allows to duplicate variables.
```
\a b c d -> a (c b) (d c)
\a b c -> B (a (c b)) (C I c)
\a b -> W (\c1 c2 -> B (a (c1 b)) (C I c2))
\a b -> W (\c1 -> B (B (a (c1 b))) (C I))
\a b -> W (C (B B (B B (B a (C I b)))) (C I))
...

```
* BCKW forms a complete basis for the plain lambda calculus.

## Challenge

Given a lambda term in the format below, classify it into one of five categories (ordered, linear, affine, relevant, none of these). The output should be the most restrictive one the input belongs to.

The input is a lambda term that takes one or more terms as input and combines them in some way, just like all the examples used above. To simplify, we can eliminate the list of input variables, and simply use the number of variables and the "function body", where each variable used is encoded as its index in the list of arguments. `\a b c d e -> a b (d c) e` is encoded to `5, "1 2 (4 3) 5"`. (Note that it is different from de Bruijn indexes.)

The function body can be taken as a string or a nested structure of integers. The "variable index" can be 0- or 1-based, and you need to handle indexes of 10 or higher.

For output, you can choose five consistent values to represent each of the five categories.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
length, "body" (lambda term it represents) => answer

1, "1" (\a -> a) => Ordered
2, "1 2" (\a b -> a b) => Ordered
2, "2 1" (\a b -> b a) => Linear
2, "1" (\a b -> a) => Affine
2, "2 (1 2)" (\a b -> b (a b)) => Relevant
2, "1 1" (\a b -> a a) => None
3, "1 3 (2 3)" (\a b c -> a c (b c)) => Relevant
4, "1 3 (2 3)" (\a b c d -> a c (b c)) => None
10, "1 (2 (3 4) 5) 6 7 8 (9 10)" => Ordered
10, "5 (2 (6 10) 1) 3 7 8 (9 4)" => Linear
10, "5 (2 (6 10) 1) (9 4)" => Affine
10, "1 5 (2 (3 6 10) 1) 3 7 8 (10 9 4)" => Relevant
10, "1 (2 (4 10) 1) 5 (9 4)" => None

```

# Answer
> 2 votes
# Jelly, ~~18~~ 15 bytes

```
F⁻ȧċⱮɗR}Ṃ;ṀƊ«Ø½

```

Try it online!

A dyadic link taking a nested list of integers on the left and the number of parameters on the right. Returns the following:

```
[0,0] - Ordered
[0,1] - Affine
[0,2] - None
[1,1] - Linear
[1,2] - Relevant

```

The TIO footer adds textual representations of each answer as well.

## Explanation

```
F    ɗR}        | Using the flattened list of integers as the left argument and a range of 1..n as the right argument:
 ⁻              | - Not equal
  ȧ             | - Logical and
   ċⱮ           | - The count of each of 1..n in the flattened list
        Ṃ;ṀƊ    | Min concatenated to max
            «Ø½ | Min of [1,2] and this (vectorises, so 1 is matched to the min and 2 to the max)

```

Note this is similar (though not identical) to my R answer, if that helps in understanding it.

# Answer
> 1 votes
# JavaScript, 71 bytes

```
a=>g=i=>i&&(h=j=>~a.flat(1/0).indexOf(i,-j),h(p=h())?5:p?i<-p:3)|g(i-1)

```

Try it online!

Input a nested integer array (1-indexed), and the number of operand. Assume the input is always valid. Output a number.

* 0 - Ordered
* 1 - Linear
* 3 - Affine
* 5 - Relevant
* 7 - None

# Answer
> 0 votes
# \>= 4.1, 81 bytes

```
\(x,n)identical(u<-unlist(x,T),r<-1:n+0)+pmin(1:2,range(sapply(r,\(y)sum(u==y))))

```

Try it online!

A function that takes a nested list of integers `x` and the number of parameters `n`. Returns a length 2 vector:

```
[0,1] - Affine
[0,2] - None
[1,1] - Linear
[1,2] - Relevant
[2,2] - Ordered

```

# Answer
> 0 votes
# Charcoal, 38 bytes

```
≔Ｉ⪪ΦＳ›@ι θ≔ＥＮ№θιη¿⁼θＥηκO¿⁼¹⌈η§AL⌊η¿⌊ηR

```

Try it online! Link is to verbose version of code. Takes the string (with `[]` delimiters) as the first input and the number of 0-indexed variables as the second input. Explanation:

```
≔Ｉ⪪ΦＳ›@ι θ

```

Input the string, filter out the `[]`s, split on spaces, and cast to integer.

```
≔ＥＮ№θιη

```

Count the number of occurrences of each variable.

```
¿⁼θＥηκO

```

If the flattened list of terms equals the list of variables then output `O`, otherwise...

```
¿⁼¹⌈η§AL⌊η

```

... if there is at most one of each variable then output `L` if there is (at least) one of each variable or `A` if there is at least one missing variable, otherwise...

```
¿⌊ηR

```

... if there is at least one of each variable then output `R` otherwise output nothing.

---
Tags: code-golf, classification, functional-programming, combinatory-logic, lambda-calculus
---


title: How to golf a fork in Haskell?

text:
# Question
Title: How to golf a fork in Haskell?
I'm trying to make a pointfree function `f` that can act like APL's dyadic forks/Husk's `§`, so `f g h i a b` equals `g (h a) (i b)`, where `g` is a binary function, `h` and `i` are unary functions, and `a` and `b` are integers (I'm only dealing with integers and not other types right now). I converted the function to pointfree in the following steps, but it's 26 bytes with a lot of parentheses and periods and even a `flip`, so I'd like to know how to golf it.

```
f g h i a b=g(h a)(i b)
f g h i=(.i).g.h
f g h=(.g.h).(.)
f g=(.(.)).(flip(.)).(g.)
f=((.(.)).).((flip(.)).).(.)

```

Try it online!

# Answer
# 18 bytes

```
(flip.).(.).((.).)

```

Try it online!

Since your function has no argument repetition and no argument deletion, it essentially becomes a BC calculus golf (in Haskell terms, a golf using just `B=(.)` and `C=flip`). I will use B and C combinators and convert to Haskell code later.

```
\g h i a b -> g (h a) (i b)
\g h i a -> B (g (h a)) i
\g h i -> C (\a -> B (g (h a))) i
\g h -> C (\a -> B (g (h a)))

-- choice 1
\g h -> C (B B (B g h))
-- choice 1.1
\g -> B C (B (B B) (B g))
B C.B (B B).B
(flip.).(((.).).).(.)  -- 21 bytes
-- choice 1.2
\g -> B (B C (B B)) (B g)
B (B C (B B)).B
((flip.((.).)).).(.)  -- 20 bytes; pointfree.io

-- choice 2
\g h -> C (B (B B g) h)
\g -> B C (B (B B g))
B C.B.B B
(flip.).(.).((.).)  -- 18 bytes; shortest

```

As a bonus, if you can swap `i` and `a` in the definition of `f`, it becomes an ordered LC and allows a very short form using just `(.)`:

```
\g h a i b -> g (h a) (i b)
\g h a i -> B (g (h a)) i
\g h a -> B (g (h a))
\g h -> B (B B g) h
\g -> B (B B g)
B B (B B)
(.).((.).)  -- 10 bytes

```
> 15 votes

---
Tags: code-golf, tips, haskell
---


# Question
Title: Is there a shorter way to express this haskell idiom?
Every so often I have a function of type `a -> b` and a function of type `b -> b -> c` and I would like a function of type `a -> a -> c`. For example if I wanted to check the second element of each two tuples were equal

```
snd :: (a , b) -> b
(==) :: Eq a => a -> a -> Bool

```

And I want something of type

```
Eq b => (a, b) -> (c, b) -> Bool

```

The best way I have found to do this so far is

```
f g z=(.g).z.g

```

Which is ok, but it feels unneccessarily complex for something that is this simple. The pointfree representation is even worse:

```
flip=<<((.).).(.).flip(.)

```

Additionally it feels like this idiom should be representable with some sort of abstraction (it feels a lot like `(<*>)`). I attempted to find a replacement by abstracting our functions to functors, the result is not very enlightening

```
flip=<<(fmap.).fmap.flip fmap ::
  Functor f => f a -> (a -> a -> b) -> f (f b)

```

Is there a shorter way to express this idea? Particularly the pointfree version?

# Answer
> 3 votes
Stumbled upon this question in the related questions list of How to golf a fork in Haskell?. Now that I have a better understanding of combinator golf, I gave it a try.

Primer: Haskell supports a few combinators including the standard S, B, C, K, I:

```
-- I
id = \x -> x
-- K
pure = \x y -> x  -- 1 byte shorter than `const`
-- S
(<*>) = \x y z -> x z (y z)
-- B
(.) = \x y z -> x (y z)
-- C
flip = \x y z -> x z y
-- Variations of S
(>>=) = \x y z -> y (x z) z
(=<<) = \x y z -> x (y z) z
liftA2 = \f g h x -> f (g x) (h x)  -- part of latest Prelude

```

Now, there are two possible forms to convert to pointfree:

```
v1 :: (b -> b -> c) -> (a -> b) -> (a -> a -> c)
v1 f g x y = f (g x) (g y)
v2 :: (a -> b) -> (b -> b -> c) -> (a -> a -> c)
v2 f g x y = g (f x) (f y)

```

The following are all the various reductions I tried (along with typechecking):

```
import Control.Applicative

type On a b c = (b -> b -> c) -> (a -> b) -> a -> a -> c
fref :: On a b c
fref g h x y=g(h x)(h y)
f1 :: On a b c
f1=(flip flip<*>).(.).((.).)
f2 :: On a b c
f2 z g=(.g).z.g
f3 :: On a b c
f3=(flip=<<).(.).((.).)
f4 :: On a b c
f4=liftA2(.)(flip(.)).(.)
f5 :: On a b c
f5=((.).(flip(.))<*>).(.)

type On2 a b c = (a -> b) -> (b -> b -> c) -> a -> a -> c
fref' :: On2 a b c
fref' g h x y=h(g x)(g y)
f1' :: On2 a b c
f1' g=((.g).).(.g)
f2' :: On2 a b c
f2'=liftA2(.)((.).flip(.))(flip(.))
f3' :: On2 a b c
f3' g z=(.g).z.g
f4' :: On2 a b c
f4'=(.).(.).flip(.)<*>flip(.)
f5' :: On2 a b c
f5'=(.).(.).q<*>q;q=flip(.)
f6' :: On2 a b c
f6' g=(.g).((.g).)
f7' :: On2 a b c
f7'=r<*>r;r=(.).flip(.)
f8' :: On2 a b c
f8'=s<*>s;s x=(.)(.x)

```

Try it online!

Unfortunately, the shortest unnamed lambda version is the same as OP's of

```
\z g->(.g).z.g

```

at 14 bytes, supporting both versions (just swap `g` and `z` in the argument list for the alternative version).

The shortest pointfree solution I could find was

```
(flip=<<).(.).((.).)

```

at 20 bytes (which has the type of `v1`), which is 5 bytes shorter than OP's. For `v2`, I got two different 25 byters.

The reduction steps to reach this one:

```
\f g a b -> f (g a) (g b)
\f g a -> B (f (g a)) g
\f g -> C (\a -> B (f (g a))) g
\f g -> C (B (B B f) g) g
\f g -> (=<<) C (B (B B f)) g
\f -> (=<<) C (B (B B f))
((=<<)C).B.BB
(flip=<<).(.).((.).)

```

# Answer
> 2 votes
I think eta-reduction is severely overrated. I see a lot more attempts at eta-reduction in the wild than I think is reasonable.

So it is in this case: eta-reducing this function is not helpful, I think. It's much more readable and elegant in its full form:

```
f :: (a -> a -> c) -> (a -> b) -> b -> b -> c
f g h a b = g (h a) (h b)

```

---

On a related note, such function exists in the standard libraries. It's called `on`, and the idea is to use it in infix form, so that it almost reads like English:

```
eqAmounts = (==) `on` amount
cmpNames = compare `on` name

```

---
Tags: code-golf, tips, haskell
---


# Question
Title: Find the first word starting with each letter
Given a string, find the first word starting with each letter (case insensitive).

### Sample

Using `Ferulas flourish in gorgeous gardens.` as input:

```
"Ferulas flourish in gorgeous gardens."
 ^^^^^^^          ^^ ^^^^^^^^
 |                |  |
 |                |  --> is the first word starting with `g`
 |                --> is the first word starting with `i`
 --> is the first word starting with `f`

```

Then, the output for this sample should be the matched words joined by one single space:

```
"Ferulas in gorgeous"

```

### Challenge

Both input and output must be a string representation, or the closest alternative in your language.

Program or function allowed.

You can consider a word being at least one of: `lowercase or uppercase letters, digits, underscore`.

This is , shortest answer in bytes wins.

### Another samples:

```
input: "Take all first words for each letter... this is a test"
output: "Take all first words each letter is"

```

---

```
input: "Look ^_^ .... There are 3 little dogs :)"
output: "Look _ There are 3 dogs"

```

---

```
input: "...maybe some day 1 plus 2 plus 20 could result in 3"
output: "maybe some day 1 plus 2 could result in 3"

```

# Answer
# Retina, 28 bytes:

```
M!i`\b(\w)(?<!\b\1.+)\w*
¶

```
* `M!` \- Match each work and print all words separated by newlines.
* `i` \- Ignore case.
* `\b(\w)` \- Capture first letter of each word
* `(?<!\b\1.+)` \- After matching the letter, check if there wasn't a previous word starting with the same letter. `\1.+` ensures at least two characters, so we are skipping the current word.
* `\w*` \- match the rest of the word.
The above matches only words - all other characters are removed.
* `¶\n`  \- Replace newlines with spaces.

Try it online!
> 17 votes

# Answer
## Retina, 45 bytes

```
i`\b((\w)\w*)\b(?<=\b\2\w*\b.+)

\W+

^ | $

```

Simply uses a single regex to remove later words starting with the same `\w` character (case insensitive with the `i` option), converts runs of `\W` to a single space, then removes any leading/trailing space from the result.

Try it online!

Edit: See @Kobi's answer for a shorter version using `M!``
> 9 votes

# Answer
# JavaScript (ES6), ~~73~~ 71 bytes

```
s=>s.match(u=/\w+/g).filter(w=>u[n=parseInt(w[0],36)]?0:u[n]=1).join` `

```

*Saved 2 bytes thanks to @edc65!*

## Test

```
var solution = s=>s.match(u=/\w+/g).filter(w=>u[n=parseInt(w[0],36)]?0:u[n]=1).join` `;
var testCases = [
  "Ferulas flourish in gorgeous gardens.",
  "Take all first words for each letter... this is a test",
  "Look ^_^ .... There are 3 little dogs :)",
  "...maybe some day 1 plus 2 plus 20 could result in 3"
];
document.write("<pre>"+testCases.map(t=>t+"\n"+solution(t)).join("\n\n")+"</pre>");
```
> 9 votes

# Answer
# Pyth, 23 bytes

```
J:z"\w+"1jdxDJhM.grhk0J

```

Try it online: Demonstration or Test Suite

`J:z"\w+"1` finds all the words in the input using the regex `\w+` and stores them in `J`.

`.grhk0J` groups the words by their lowercase first letter, `hM` takes the first from each group, `xDJ` sorts these words by their index in the input string, and `jd` puts spaces between them.
> 7 votes

# Answer
# Perl 6, 39 bytes

```
{.words.grep({!%.{.substr(0,1).lc}++})}

```
> 4 votes

# Answer
# MATL, 23 bytes

```
'\w+'XXtck1Z)t!=XRa~)Zc

```

This borrows Jakube's idea of using a regexp for removing unwanted characters and splitting at the same time.

Input is a string enclosed by single quotes.

**Try it online!**

### Explanation

```
'\w+'XX  % find words that match this regexp. Gives a cell array
t        % duplicate
c        % convert into 2D char array, right-padded with spaces
k        % make lowercase
1Z)      % get first column (starting letter of each word)
t!=      % duplicate, transpose, test for equality: all combinations
XR       % set diagonal and below to 0
a~       % true for columns that contain all zeros
)        % use as a logical index (filter) of words to keep from the original cell array
Zc       % join those words by spaces

```
> 3 votes

# Answer
# C, ~~142~~ ~~132~~ 122 bytes

10 bytes lighter thanks to @tucuxi!

```
b[200],k;main(c){for(;~c;isalnum(c)|c==95?k&2?:(k|=!b[c|32]++?k&1?putchar(32):0,7:2),k&4?putchar(c):0:(k&=1))c=getchar();}

```

~~Prints a trailing space after the last output word.~~
> 3 votes

# Answer
# Vim 57 keystrokes

```
:s/[^a-zA-Z_ ]//g<cr>A <cr>ylwv$:s/\%V\c<c-v><c-r>"\h* //eg<c-v><cr>@q<esc>0"qDk@q

```

Explanation:

```
:s/[^a-zA-Z_ ]//g                                 #Remove all invalid chars.
A <cr>                                            #Enter insert mode, and enter
                                                  #a space and a newline at the end
ylwv$:s/\\c%V<c-v><c-r>"\h* //eg<c-v><cr>@q<esc>  #Enter all of this text on the
                                                  #next line

0                                                 #Go to the beginning of the line
"qD                                               #Delete this line into register
                                                  #"q"
k@q                                               #Run "q" as a macro

#Macro
ylw                                               #Yank a single letter
   v$                                             #Visual selection to end of line
     :s/                                          #Substitute regex
       \%V\c                                      #Only apply to the selection and
                                                  #ignore case
            <c-v><c-r>"                           #Enter the yanked letter
                       \h*                        #All "Head of word" chars
                                                  #And a space
                           //                     #Replace with an empty string
                             eg                   #Continue the macro if not found
                                                  #Apply to all matches
                               <c-v><cr>          #Enter a <CR> literal
                                        @q<esc>   #Recursively call the macro

```

I'm really dissapointed by how long this one is. The "Invalid" chars (everything but `a-z`, `A-Z`, `_` and space) really threw me off. I'm sure there's a better way to do this:

```
:s/[^a-zA-Z_ ]//g

```

Since `\h` matches all of that expect for the space, but I can't figure out how to put the metachar in a range. If anyone has tips, I'd love to hear em.
> 2 votes

# Answer
# Julia, ~~165~~ ~~155~~ ~~151~~ ~~129~~ 102 bytes

```
g(s,d=[])=join(filter(i->i!=0,[(c=lcfirst(w)[1])∈d?0:(d=[d;c];w)for w=split(s,r"\W",keep=1<0)])," ")

```

This is a function that accepts a string and returns a string.

Ungolfed:

```
function g(s, d=[])
    # Split the string into an array on unwanted characters, then for
    # each word, if the first letter has been encountered, populate
    # this element of the array with 0, otherwise note the first letter
    # and use the word. This results in an array of words and zeros.
    x = [(c = lcfirst(w)[1]) ∈ d ? 0 : (d = [d; c]; w) for w = split(s, r"\W", keep=1<0)]

    # Remove the zeros, keeping only the words. Note that this works
    # even if the word is the string "0" since 0 != "0".
    z = filter(i -> i != 0, x)

    # Join into a string and return
    return join(z, " ")
end

```

Saved 53 bytes with help from Sp3000!
> 2 votes

# Answer
# 05AB1E, 40 bytes

Code:

```
94L32+çJžj-DU-ð¡""Kvy¬Xsl©åï>iX®«Uy}\}ðý

```

Try it online!

Explanation:

We first generate all characters which should be deleted from the input string using `94L32+ç` (Try here). We join this string using `J` and remove `[a-zA-Z0-9_]` which is stored in žj (Try here). We remove all the characters that are in the second string from the first string, which will leave us:

```
!"#$%&'()*+,-./:;<=>?@[\]^`{|}~

```

That can also be tested here. We `D`uplicate this and store in to `X` with the `U`-command. We then remove all the characters that are in this string from the input. We then split on whitespaces using `ð¡` and remove all empty strings (using `""K`). We now have this.

This is the *clean* version of the input, which we will work with. We map over each element using `v`. This uses `y` as the string variable. We take the first character of the string using `¬` and push `X`, which contains a string with all *forbidden* characters (`!"#$%&'()*+,-./:;<=>?@[\]^`{|}~`). We check if the `l`owercase version of the first character, (which will also be `©`opied to the register), is in this string using `å`. Covered by this part: `ï>i`, if the first letter doesn't exist in the string of forbidden characters (`X`), we append this letter to the list of forbidden characters (done with `X®«U`) and we push `y` on top of the stack.

Finally, when the strings are filtered, we join the stack by spaces with `ðý`.
> 2 votes

# Answer
# Jelly, ~~32~~ 31 bytes

```
ØB;”_
e€¢¬œṗf€¢¹ÐfµZḢŒlQi@€$ịj⁶

```

Try it online!
> 2 votes

# Answer
# **C# (LINQPAD) - 136 128 bytes**

```
var w=Util.ReadLine().Split(' ');string.Join(" ",w.Select(s=>w.First(f=>Regex.IsMatch(""+f[0],"(?i)"+s[0]))).Distinct()).Dump();

```
> 2 votes

# Answer
# **PHP**

Inspired by the use of regex in most of the answers, I originally tried to do this without using regex at all just to show off a neat variation, but the sticking point of not having clean strings as input ruined that idea. Sad.

**With function wrapper, 89 bytes**

```
function f($s){foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;}

```

**Without function wrapper (needing $s pre-declared), 73 bytes**

```
foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;

```

Explanation:

```
foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;
        preg_split('/\w/',$s)                                             Break input on all non-word characters
foreach(                     as$w)                                        Loop through each 'word'
                                     lcfirst($w)[0]                       Take the first letter of the lowercase version of the word
                                  $c[              ]++?:                  Increment an array element with a key of that letter after checking if it's false-y (0)
                                                        $v.=" $w";        Add the word if the letter wasn't found (if the previous condition evaluated to false)
                                                                  echo$v; Print the new string to screen.

```

My only regret is that I couldn't find a faster way of checking/converting letter case.
> 2 votes

# Answer
# Python, 103 bytes

```
import re
lambda s,d=[]:[w for w in re.findall("\w+",s)if(d.append(w.lower()[0])or d[-1])not in d[:-1]]

```
> 2 votes

# Answer
# Ruby, 40 bytes

```
->s{s.scan(/\w+/).uniq{|x|x.ord|32}*' '}

```

Try it online!

`String#ord` returns the codepoint of the first character in a string and bitwise or with `32` maps uppercase codepoints to the lowercase ones and `95 (_)` to `127`, while keeping everything else the same.
> 2 votes

# Answer
## Lua, 172 Bytes

It ended up way longer that I wanted...

```
t={}(...):gsub("[%w_]+",function(w)b=nil for i=1,#t
do b=t[i]:sub(1,1):lower()==w:sub(1,1):lower()and 1 or b
end t[#t+1]=not b and w or nil end)print(table.concat(t," "))

```

### Ungolfed

```
t={}                           -- initialise the accepted words list
(...):gsub("[%w_]+",function(w)-- iterate over each group of alphanumericals and underscores
  b=nil                        -- initialise b (boolean->do we have this letter or not)
  for i=1,#t                   -- iterate over t
  do
    b=t[i]:sub(1,1):lower()    -- compare the first char of t's i word
       ==w:sub(1,1):lower()    -- and the first char of the current word
           and 1               -- if they are equals, set b to 1
           or b                -- else, don't change it
  end
  t[#t+1]=not b and w or nil   -- insert w into t if b isn't set
end)

print(table.concat(t," "))     -- print the content of t separated by spaces

```
> 1 votes

# Answer
## Ruby 76 Bytes

```
s;f={};s.scan(/(([\w])[\w]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.*' '

```

### Or with method definition 88 bytes

```
def m s;f={};(s.scan(/((\w)\w*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=1; h)}-[p]).*' ';end

```

Ungolfed and with unit test:

```
def m_long(s)
  #found  - Hash with already found initials
  f={}
  #h=hit, i=initial, j=i[0].downcase
  s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|
    f[j=i.upcase] ? nil : (f[j] = true; h)
  }.compact.join(' ')
end
#true == !p
#~ def m(s)
  #~ f={};s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.join' '
#~ end
def m s;f={};s.scan(/(([\w\d])[\w\d]*)/).map{|h,i|f[j=i.upcase]?nil:(f[j]=!p; h)}.compact.join' ';end

#~ s = "Ferulas flourish in gorgeous gardens."
#~ p s.split

require 'minitest/autorun'
class FirstLetterTest < Minitest::Test
  def test_1
    assert_equal("Ferulas in gorgeous",m("Ferulas flourish in gorgeous gardens."))
    assert_equal("Ferulas in gorgeous",m_long("Ferulas flourish in gorgeous gardens."))
  end
  def test_2
    assert_equal("Take all first words each letter is",m("Take all first words for each letter... this is a test"))
    assert_equal("Take all first words each letter is",m_long("Take all first words for each letter... this is a test"))
  end
  def test_3
    assert_equal("Look _ There are 3 dogs",m("Look ^_^ .... There are 3 little dogs :)"))
    assert_equal("Look _ There are 3 dogs",m_long("Look ^_^ .... There are 3 little dogs :)"))
  end
  def test_4
    assert_equal("maybe some day 1 plus 2 could result in 3",m("...maybe some day 1 plus 2 plus 20 could result in 3"))
    assert_equal("maybe some day 1 plus 2 could result in 3",m_long("...maybe some day 1 plus 2 plus 20 could result in 3"))
  end
end

```
> 1 votes

# Answer
## Seriously, 43 bytes

```
6╙¬▀'_+,;)-@s`;0@Eùk`M┬i;╗;lrZ`i@╜í=`M@░' j

```

Try it online!

The lack of regex capabilities made this much more difficult than it needed to be.

Explanation:

```
6╙¬▀'_+,;)-@s`;0@Eùk`M┬i;╗;lrZ`i@╜í=`M@░' j
6╙¬▀                                         push digits in base 62 (uppercase and lowercase letters and numbers)
    '_+                                      prepend underscore
       ,;)                                   push two copies of input, move one to bottom of stack
          -                                  get all characters in input that are not letters, numbers, or underscores
           @s                                split input on all occurrences of non-word characters
             `;0@Eùk`M                       for each word: push the first letter (lowercased)
                      ┬i                     transpose and flatten (TOS is list of first letters, then list of words)
                        ;╗                   push a copy of the first letters list to register 0
                          ;lrZ               zip the list of first letters with their positions in the list
                              `i@╜í=`M       for each first letter: push 1 if that is the first time the letter has been encountered (first index of the letter matches its own index) else 0
                                      @░     filter words (take words where corresponding element in the previous list is truthy)
                                        ' j  join on spaces

```
> 1 votes

# Answer
# grep and awk, 68 56 bytes

The script:

```
echo `grep -o '\w*'|awk '!x[tolower(substr($0,1,1))]++'`

```

Explanation:

* `grep -o` matches the legal words, printing each on its own line.
* `awk` takes the first letter of each line with `substr`, makes it lowercase, and then increments a hashtable entry with that key. If the value was unset before the increment, the line is printed.
* `echo ...` turns the lines back into words

I previously tried to create a solution without `awk`, using `uniq`, `sort`, `grep` and `bash` but fell just short. History in the edits.

Thanks to Dennis for some improvements I missed.
> 1 votes

# Answer
# Japt v2.0a0 `-S`, ~~19~~ 16 bytes

```
f/\w+/
üÈÎvÃmÎnU

```

Try it or run all test cases

```
f/\w+/\nüÈÎvÃmÎnU     :Implicit input of string U                  > "Ferulas flourish in gorgeous gardens."
f/\w+/                :Match /\w+/g                                > ["Ferulas","flourish","in","gorgeous","gardens"]
      \n              :Reassign to U
        ü             :Group and sort by
         È            :Passing each through the following function
          Î           :  First character                           >   ["F","f","i","g","g"]
           v          :  Lowercase                                 >   ["f","f","i","g","g"]
            Ã         :End function                                > [["Ferulas","flourish"],["gorgeous","gardens"],["in"]]
             m        :Map
              Î       :  First element                             > ["Ferulas","gorgeous","in"]
               nU     :Sort by index in U                          > ["Ferulas","in","gorgeous"]
                      :Implicit output joined with spaces          > "Ferulas in gorgeous"

```
> 1 votes

# Answer
# Perl 5 `-n`, ~~44~~ 37 bytes

```
/./&&!$k{lc$&}++&&print$_,$"for/\w+/g

```

Try it online!
> 1 votes

# Answer
# K (ngn/k), 55 bytes

```
{" "/w@.*'" "_=_*'w:" "\c(c:`c$&2!&48,27\3988544219)?x}

```

Try it online!

* `(c:`c$&2!&48,27\3988544219)` a compressed version of `"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"`, stored in `c`
* `c(...)?x` replace all non-alphanumeric/underscore characters with spaces
* `w:" "\` split the converted input on spaces, storing in `w`
* `=_*'w` build a dictionary mapping the distinct (lowercased) leading characters to their words' position(s) within the input sentence
* `" "_` remove/ignore spaces
* `w@.*'` retrieve the first word beginning with each distinct character...
* `" "/` ...joining them together with spaces (to be implicitly returned)
> 1 votes

# Answer
# Vyxal `S`, 16 bytes

```
kr‛ _+↔⇩⌈:vhÞU*'

```

Try it Online!

Explanation:

```
kr‛ _+↔           # Remove any non A-Z,a-z,0-9,_, or space chars
       ⇩          # Lowercase
        ⌈         # Split on spaces
         :        # Duplicate
          vh      # Get the first letter of each
            ÞU    # Nub Sieve (Unique mask)
              *   # Multiply mask with list of words
               '  # Remove all empty strings
                  # 'S' flag - join top of stack with spaces and print

```
> 1 votes

# Answer
# Python 3.5, 138 bytes:

```
import re;lambda o,t=[]:''.join([y[0]for y in[(u+' ',t.append(u[0].lower()))for u in re.sub('\W+',' ',o).split()if u[0].lower()not in t]])

```

Basically, what's happening is..

1. Using a simple regular expression, the program replaces all the characters, except lowercase or uppercase letters, digits, or underscores in the given string with spaces, and then splits the string at those spaces.
2. Then, using list comprehension, create a list that iterates through all the words in the split string, and add the first letters of each word to list "t".
3. In the process, if the current word's first letter is NOT already in the list "t", then that word and a trailing space are added to the current list being created. Otherwise, the list continues on appending the first letters of each word to list "t".
4. Finally, when all words in the split have been iterated through, the words in the new list are joined into a string and returned.
> 0 votes

# Answer
**PHP 120bytes**

```
function a($s){foreach(preg_split('/\W/',$s)as$w)if(!$o[ucfirst($w[0])]){$o[ucfirst($w[0])]=$w;}return implode(" ",$o);}

```

This generates a bunch of warnings but that's fine.
> 0 votes

# Answer
# Javascript ES6, ~~108~~ 107 chars

### 107 chars, result string is trimmed

```
r=s=>s.split``.reverse().join``
f=s=>r(r(s).replace(/\b\w*(\w)\b(?=.*\1\b)/gi,'')).replace(/\W+/g,' ').trim()

```

Test:

```
["Take all first words for each letter... this is a test",
"Look ^_^ .... There are 3 little dogs :)",
"...maybe some day 1 plus 2 plus 20 could result in 3"
].map(f) + '' == [
"Take all first words each letter is",
"Look _ There are 3 dogs",
"maybe some day 1 plus 2 could result in 3"
]

```
> 0 votes

# Answer
# Tcl, 150 bytes

```
proc F {s D\ {}} {lmap w [split $s] {regsub -all \[^\\w] $w "" f
if {![dict e $D [set k [string tol [string in $f 0]]]]} {dict se D $k $f}}
dict v $D}

```

Try it online!
> 0 votes

# Answer
# Python 3, 131 bytes

```
lambda s:' '.join(sorted({w[0].lower():w for w in''.join(c*(c.isalnum()or c in'_ ')for c in s).split()[::-1]}.values(),key=s.find))

```

Try it online!

Solution without regex.
> 0 votes

# Answer
# Husk, 22 bytes

```
wÖ€₁¹m←ko_←₁
mf§|='_□w

```

Try it online!

The '\_' requirement is a bit annoying, otherwise a pretty interesting challenge.

## Explanation

```
function ₁: filter nonalphanumerics and split
mf§|='_□w
        w split on spaces
mf        map and filter each letter in the words by:
       □  is it alphanumeric?
  §|      or:
    ='_   is it an underscore?

main function:
wÖ€₁¹m←ko_←₁
           ₁ format the input
       ko    key the words on:
         _←  first letter, lowercased
     m←      map each to first word
 Ö           order by:
  €₁¹        their index in the formatted input
w            join back with spaces

```
> 0 votes

# Answer
# Python, 93 bytes

```
import re
s=""
for w in re.findall("\w+",input()):
 if(a:=w[0].lower())not in s:s+=a;print(w)

```
> 0 votes

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


title: Round like a Zero

text:
# Question
Title: Round like a Zero
# Goal

Given an input number, round it off to the nearest number with one significant figure.

# Requirements

## Input

* A floating point number.
* Assume the input number results in an output within the data type's limits (ie. ignore overflow errors.)
* 0 is an invalid input.
* Numbers that cannot be accurately represented in the floating point data type (eg. `"0.35"` being stored as `0.3499999`) do not have to be supported.

## Output

* The nearest number that consists of one non-zero digit and any number of zero digits.
* The result must support negative numbers and fractional numbers.
* When the input lies exactly between two possible outputs, round away from zero.

### Presentation

The focus is on the calculation rather than the presentation. The output may be a floating point data type. It may be text either in full or in scientific notation. If you find a loophole where presenting a certain way reduces your byte count, kudos to you!

### Examples

```
9
-3000
.2
0.2
-.2
7e12
5e-15
1e0

```

# Test Cases

```
Input     Output
1         1
10        10
17        20
99        100
54321     50000
56789     60000
-123      -100
-789      -800
0.23      0.2
0.25      0.3
-0.25     -0.3
4.56e23   5e23
4.56e-23  5e-23

```

# Scoring

The code with the least byte-count after one week wins.

# Answer
> 6 votes
# MATL, 3 bytes

```
1&V

```

Try it online! Or verify all test cases.

Test case `0.25` fails for the compiler running in Octave on TIO, but works in Matlab on Windows:

The different behaviour is caused by Octave's/Matlab's `sprintf` function using either "banker's rounding" or ".5 away from zero" rounding, depending on platform. More information and tests can be found here.

---

For **6 bytes**,

```
1t3$Yo

```

works both on Octave and on Matlab. Verify all test cases.

# Answer
> 12 votes
# C# (.NET Core), ~~19~~ 12 bytes

```
n=>$"{n:G1}"

```

Try it online!

Examples:

```
Input     Output
----------------
 54321     5E+04
-56789    -6E+04
 99        1E+02
 0.23      0.2
 0.25      0.3
-0.25     -0.3
 4.56e23   5E+23
 4.56e-23  5E-23

```

With the new versions of C# we also got shorter ways to achieve this, as Calculuswhiz wisely noted in the comments.

# Answer
> 9 votes
## Javascript, 19 bytes

```
x=>x.toPrecision(1)

```

# Answer
> 4 votes
# Retina, ~~63~~ 62 bytes

```
1`[1-9]
$*#
#\.?[5-9]
#$&
T`d`0`#[\d.]+
0(\.?)#{10}
1$1
#+
$.0

```

Try it online!

# Answer
> 2 votes
# PHP, 45 bytes

```
<?=round($x=$argv[1],-floor(log10(abs($x))));

```

Try it online!

Same method as my python 2 answer.

Also seems to correctly handle `0.35`, which puts it a peg above the JS answer too :D

# Answer
> 2 votes
# T-SQL, 27 bytes

```
SELECT FORMAT(i,'G1')FROM t

```

Using the same .Net formatting code as Carlos Alejo's C# answer. Input is from *float* column **i** in pre-existing table **t**, per our IO standards

Test cases:

```
Input         Output
------------ --------
1             1
10            1E+01
17            2E+01
99            1E+02
54321         5E+04
56789         6E+04
-123         -1E+02
-789         -8E+02
0.23          0.2
0.25          0.3
-0.25        -0.3
4.56E+23      5E+23
4.56E-23      5E-23

```

(Pretty handy that I can pre-load the input table with all these values and run them at once.)

# Answer
> 2 votes
# Excel 2016, 36

* Input A1.
* A2: `=10^INT(LOG10(ABS(A1`
* Result: `=A2*ROUND(A1/A2,`

# Answer
> 1 votes
# Python 2, 62 bytes

```
lambda x:round(x,-int(floor(log10(abs(x)))))
from math import*

```

Try it online!

Not used to python golfing, but this works.

Fails on `0.35` due to floating point inaccuracies.

Thanks to Anders Kaseorg for pointing out that this works correctly in Python 2

# Answer
> 1 votes
# Guile, 23 bytes

```
(format #t"~,0e"(read))

```

Try it online!

# Answer
> 0 votes
# Perl 5, 15 bytes

```
printf"%.1g",<>

```

Try it online!

# Answer
> 0 votes
# Zsh, 14 bytes

Port of the perl answer. Try it Online!

```
printf %.1g $1

```

# Answer
> 0 votes
# Forth (gforth), 24 bytes

```
: f 1 set-precision f. ;

```

Try it online!

Input is expected on the floating point stack. Output is to stdout

I don't like making changes to the global (for this instance) precision of the floating point output functions, but it saves a lot of bytes to not have to restore the previous value at the end. Does not output in engineering or scientific notation, regardless of input.

*Note: For some reason, the tio interpreter converts `0.25` to `0.2`, while my local installation converts `0.25` to `0.3`. I'm not entirely sure why this is, but since I get the correct result locally, I'm leaving my answer as-is*

```
: f                   \ start a new word definition
  1 set-precision     \ set the floating point output words to use 1 significant digit
  f.                  \ output the top of the floating point stack
;                     \ end the word definition

```

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