text:
Code Golf: Forwards sdrawkcaB sdrawkcaB Forwards Forwards sdrawkcaB
Task

The user inputs a sentence - words only. Any input other than letters or spaces, including integers and punctuation, should throw an exception: "Sentence must only use letters".
The output has a pattern, where some
words are reversed and others words are normal.
The pattern starts as
a normal word, the next two words are reversed, then the next two
words are normal and the pattern continues.
An example of where the words should be normal and where words reversed is below:

Normal - Reversed - Reversed - Normal - Normal - Reversed - Reversed - Normal ...
Input Example
She sells Sea shells on the Sea shore
Output Example
She slles aeS shells on eht aeS shore
Additional Rules

If capital letters are used, they should remain on the letter they were originally posted on.
Any multiple spaces initially posted on input should be reduced to one space. For example Programming   Puzzles and   Code Golf becomes Programming selzzuP dna Code Golf

Shortest Code Wins!!
Happy coding...

All contests require an objetive winning criterion. Code golf (shortest code wins) should work well for this. You should also clarify what counts as word bondaries. Are words always composed of letters? Are they always separated by a single space? Also, the for example part is the only pattern that is used here, yes?

Could you also include a test case that illustrates the rule from the fourth bullent point?

"input including an integer should be rejected" What does that mean? Should the function throw an error? Output = Input?

I have re-edited the description. Thanks for your feedback - anything else please just comment

That may be a good idea...

Many programming languages do not have exceptions.

@Doorknob: True, but sometimes challenges cannot be solved by all languages. Other examples are graphical output, file or web access. No need to worry.

@nimi It seems entirely unnecessary to restrict a challenge to a small subset of languages for such a trivial reason.

Yep, this problem seems over-specified.

Should newlines count as a valid character? What about tabs? Should all whitespace be valid?

In the example about multiple spaces, there are no multiple spaces, just 1 newline. Could you please explaint better?

This otherwise-good challenge is ruined by the rule Any input other than letters or spaces, including integers and punctuation, should throw an exception: "Sentence must only use letters". It means implementing a secondary task totally unrelated to the challenge of reversing words, cuts out languages that don't have exceptions, and requires hardcoding or compressing a long string that takes up a lot of the byte count.

@Vihan yes apologies, I have edited the description above so it is explained better. Just multiple spaces should be dealt with as one space.

@xnor unfortunately posting a question is a bit of a conundrum... initially I posted the request as a very simple question of reversing and not reversing. People wanted more clarity to my question, which is good because it helps answers be more accurate - however the downfall being that it comes with constraints - I must have edited this question 30 odd times now! It is unfortunately a "damned if you do, damned if you don't". I realise now it is not ideal, but unfortunately that is the question and I will not be changing it. Thanks for your input.

@Belfield Yes, I see your bind. I guess there's nothing you can do now. In the future, try posting in the Sandbox to get feedback before posting.

@Belfield a good challenge is much more difficult than a good answer. I enjoyed this one anyway, and the next wil be better.

@edc65 thanks for the appreciation - code golf has helped me with interview tests... so it's nice for me to give back to the community

TeaScript, 55 bytes 58 60 69 76 78 80 87 89
xO`a-z `?xl(#~-i&2?l:lv(),/ +/):Ld`SÀZn Û § «e Ò5s`

This is extremely short, I'm very happy with it.
The last ~20 characters may seem like gibberish but that's "Sentence must only use letters" encoded. All the characters have char codes below 256 so each are one byte
Explanation
xO`a-z `?  // If input contains only a-z and space...

   xl(#       // Loop through input
      ~-i&2?  // If (index - 1 "unary and"ed with 2) isn't 0...
          :l,     // Leave alone
          lv()    // Otherwise, reverse string
       / +/ // Loops on spaces
   )

:Ld`SÀZn Û § «e Ò5s` // Otherwise... decompress and print  the error string

Try it online
Pastebin

Thanks for posting the test - very nice. Every one is in the same boat when it comes to the error - no golfing that line

Strange, now it works in Firefox. But I also used Firefox earlier.

Best answer so far!

What? You beat Pyth?! With a JS-based language?!? How is that even possible?!?!

@ETHproductions You can always win as long as Dennis isn't competing :p

Haskell, 141 bytes
r=reverse
f x|all(`elem`(' ':['a'..'z']++['A'..'Z']))x=unwords$zipWith($)(cycle[id,r,r,id])$words x|1<2=error"Sentence must only use letters"

Almost 2/3 of the code is for error checking. Seems to be the first real world challenge.
The work is done by unwords$zipWith($)(cycle[id,reverse,reverse,id])$words x which splits the input into a list of words, zips it with the cycling list of functions [id,reverse,reverse,id,id,reverse...] and joins the result with spaces back to a single string.
Thanks to @Christian Irwan for 2 bytes.

"Sentence must only user letters" can be changed to "Sentence must only use letters" - my bad on the error!

@Belfield: fixed

Why don't r=reverse?

@ChristianIrwan: Thanks! (In an early version I had a pointfree function without a name, so using two times reverse and r=reverse had the same length, because of the missing f=. Didn't check again when moving to non pointfree).

JavaScript (ES6) 122

f=s=>/[^a-z ]/i.test(s)?"Sentence must only use letters":s.split(/ +/).map((w,i)=>~-i&2?w:[...w].reverse().join``).join` `

alert(f(prompt('?','She sells Sea shells on the Sea shore')))

When there is a newline in the input, it outputs an error, from the example I don't think this is supposed to happen

@Vɪʜᴀɴ it's tricky, The example is about multiple spaces, but then there are no multiple spaces  - just 1 newline. I think it was mangled by SO editor. IF we have to manage newlines and other generic space, the byte count increase by 2

Python, 163 160 157 145
k=raw_input()
k=["Sentence tsum ylno use letters",k][k.replace(' ','').isalpha()]
for i,x in enumerate(k.split()):print x[::-1if(i+1)/2%2else 1],

Removed 15 characters, thanks Mego!!

Yes, afraid nimi has a point...

Shoot, I missed that. I'll revise it.

@Mego, re.search returns None (which can't be used as an index) if the result isn't found, and adding "!=None" is actually one byte longer than my original method. I saved 3 bytes by merging the last two lines though. Thanks!

Retina, 103 bytes
\s+

(?<=^\S+ (\S+ )?((\S+ ){4})*)
;
+`(;\S*)(\S)
$2$1
;

i`.*[^a-z ].*
Sentence must only use letters

There should be a single space on the second line, which SE seems to be swallowing. Run the code from a single file with the -s flag.
Retina has no concept of exceptions so the output is simply replaced by Sentence must only use letters if there are non-letter non-whitespace characters in the input.

Pyth, 61 bytes
?.A}R+G\ rz0jd.e_W%%k4 3bfTczd"Sentence must only use letters

Try it online.

Bash + coreutils, 108
[ ${@//[a-zA-Z]/} ]&&echo Sentence must only use letters||for t;{
((++i/2%2))&&rev<<<$t||echo $t
}|tr \\n \

The last character of this program is a space.
Input is taken from the command line:
$ ./norrevvevnor.sh Programming Puzzles and Code$'\n' Golf
Programming selzzuP dna Code Golf $
$ ./norrevvevnor.sh Programming Puzzles and Code$'\n' Golf1
Sentence must only use letters
$

Julia, 150 134 bytes
s->ismatch(r"[^a-z ]"i,s)?error("Sentence must only use letters"):(i=3;join([(i+=1;isodd((i+1)i÷2)?reverse(w):w)for w=split(s)]," "))

Ungolfed:
function f(s::AbstractString)
    if ismatch(r"[^a-z ]"i, s)
        error("Sentence must only use letters")
    else
        i = 3
        a = [(i += 3; isodd((i + 1)i ÷ 2) ? reverse(w) : w) for w = split(s)]
        return join(a, " ")
    end
end

Saved 16 bytes thanks to Glen O!

Before anything else, might I suggest reversing the logic of the initial conditional and assigning r to be its result? That is, r=ismatch(...)||error(...) - will shave off a few characters, and reverse the conditional that uses r. Will comment again with, I suspect, some more savings

Minor correction - I had || to deal with the negation, then realised that the negation isn't necessary. Reverse it back to &&. And even better, use ?: instead to do it even better. s->(r=ismatch(r"[^a-z ]"i,s))?error("Sentence must only use letters"):join([(iseven(i)&&(r=!r);r?reverse(w):w)for(i,w)=enumerate(split(s))]," ") for 144 bytes. And I think I can do better inside join...

Here's a streamlined version of your solution, with 134 bytes: s->ismatch(r"[^a-z ]"i,s)?error("Sentence must only use letters"):(i=3;join([(i+=1;isodd((i+1)i÷2)?reverse(w):w)for w=split(s)]," "))

@GlenO Awesome suggestions, thanks!

Pyth, 72
=zflTc?:z"[^A-Za-z ]"0"Sentence tsum ylno use letters"zdjd.e?%/hk2 2_bbz

Doesn't beat the other Pyth answer, but I already invested time into writing it. It's basically a translation of my Python answer.
Try it online

Julia, 109 bytes
s->(i=0;join([isalpha(w)?(i+=1)%4>1?reverse(w):w:error("Sentence must only use letters")for w=split(s)]," "))

i=0 and (i+=1)%4>1 are used to decide whether each word gets reversed or not. isalpha applies to the words after being split using split(s) to determine whether or not there are characters that aren't letters (spaces have already been removed by this point). join restores the string after the manipulation, unless the error is thrown.

Pyth, 55 bytes
?--rz0Gd"Sentence must only use letters"jd.e_W%%k4 3bcz

Borrowed the %%k4 3 bit from Pietu1998. Saved one additional byte.
Try it online: Demonstration or Test Suite
Explanation
?--rz0Gd"..."jd.e_W%%k4 3bcz   implicit: z = input string
   rz0                         convert z to lower-case
  -   G                        remove all letters
 -     d                       remove all spaces
?                              if there is some chars left than
        "..."                    print the string "Sentence must only ..."
                               else:
                          cz     split z by spaces or multiple spaces
               .e                map each pair (k index, b string) of ^ to:
                 _       b          b or reversed of b, depending on
                  W%%k4 3           (k mod 4) mod 3
             jd                  join the result by spaces

Japt v2.0a0 -S, 41 bytes
¸¬è\L ?`SÀZn Û § «e Ò5s`:UeS²S ¸ËzEc2

Try it
¸¬è\L ?`...`:UeS²S ¸ËzEc2     :Implicit input of string U
¸                             :Split on spaces
 ¬                            :Join
  è                           :Count occurrences of
   \L                         :RegEx /[^A-Z]/gi
      ?`...`:                 :If truthy return the compressed string "Sentence must only use letters", else
             Ue               :Recursively replace in U
               S²S            :  Two spaces with one
                   ¸          :Split on spaces
                    Ë         :Map each element at 0-based index E
                     z        :  Rotate clockwise by 90 degrees multiplied by
                      Ec2     :    E rounded up to the nearest multiple of 2
                              :Implicit output, joined with spaces

Perl 5 -ap, 80 bytes
map$_=++$i%4>1?reverse:$_,@F;$_=/[^a-z ]/i?"Sentence must use only letters":"@F"

Try it online!

Jelly, 39 bytes
³Ḳ¹ƇUJ2&TƲ¦K
“*[,ṛDṾȧƤ°Ġṛ©¦»
ØẠ” ṭ³eƇ⁼£

Try it online!
Thanks to Erik the Outgolfer. He saved me from a few extra bytes and from many hours of frustration.
Here's a 46 byte solution
It actually throws a python syntax error when the input contains invalid characters.
³Ḳ¹ƇUJ2&TƲ¦K
“çỤḷṁŀDṀẠṠGmḟĖƲƑ⁽Ḳḟ»ŒV
ØẠ” ṭ³eƇ⁼£

Try it online!

Java, 215 bytes
Regex is fun
s->{if(s.split("[^a-zA-Z ]").length>1)throw new Error("Sentence must only contains letters");else{int i=1;for(String a:s.split(" "))System.out.print((i++%2<1?new StringBuffer(a).reverse():a)+(a.isEmpty()?"":" "));}}

Try it online!

Your output currently isn't correct. You now output She slles aeS shells no the aeS shore, but it should be She slles aeS shells on eht aeS shore instead (first normal; then alternating in pairs of 2 reversed or not). Two issues cause this. You now increase i even if an item is empty, and i++%2<1 should be i++%4>1 instead. Here a fixed 211 bytes version.

@KevinCruijssen this is what I get for not reading carefully enough

05AB1E, 36 bytes
ðKDáÊi“¸–ƒ—€É€Å™ê“.ªFë#áεN4%>2÷iR]ðý

Try it online.
Throws the following error when the input does not only contain [A-Za-z ]:

(RuntimeError) Could not convert Sentence must only use letters to integer.

Explanation:
ðK                   # Remove all spaces from the (implicit) input-string
  Dá                 # Create a copy, and remove everything except for letters from this copy
    Êi               # If the copy with letters removed and the original are NOT equal:
      “¸–ƒ—€É€Å™ê“   #  Push dictionary string "sentence must only use letters"
                  .ª #  With sentence capitalization
      F              #  And try to loop that many times, causing the error above
     ë               # Else:
      #              #  Split the (implicit) input-string on spaces
       á             #  Only keep letters (which will remove empty items caused by multiple
                     #  adjacent spaces in the input, which is shorter than `õK`)
        ε            #  Map each word to:
         N4%>2÷      #   Calculate ((index modulo-4) + 1) integer-divided by 2
                     #   (results in 0,1,1,2,0,1,1,2,0,1 for indices 0,1,2,3,4,5,6,7,8,9)
               i     #   If this is exactly 1:
                R    #    Reverse the current word
     ]               # Close the if-statement, map, and if-else statement
      ðý             # Join the modified word-list by spaces
                     # (and then output it implicitly as result)

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why “¸–ƒ—€É€Å™ê“ is "sentence must only use letters".

PHP, 147 bytes
foreach(explode(' ',$argn)as$a){if(!ctype_alpha($a))throw new Exception('Sentence must only use letters');$o.=(++$i%4>1?strrev($a):$a).' ';}echo$o;

Try it online!
Or if die() is acceptable as an "Exception":
PHP, 131 bytes
foreach(explode(' ',$argn)as$a){if(!ctype_alpha($a))die('Sentence must only use letters');$o.=(++$i%4>1?strrev($a):$a).' ';}echo$o;

Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Boo! A Halloween Code Golf Challenge
Write a program that takes an input string of length 2 or more characters and adds the string  ~BOO!~  (that string has a leading and ending space) in a uniformly random spot in the string that is not on either end.

Disallowed sample inputs: 2 or   (an empty input)
Disallowed sample outputs: Hello ~BOO!~  or  ~BOO!~ Hello for the input Hello
Sample input: Hello, World!
Sample outputs: Hel ~BOO!~ lo, World! or Hello, Worl ~BOO!~ d!

This is code golf, fellas. Standard rules apply. Shortest code in bytes wins.

Congratulations to Dennis for having the shortest, spookiest program! Happy Halloween!

Would a command-line argument be okay, or does it have to be stdin?

Anything that takes an input and prints that output with the modification is acceptable. I use STDIN by default because it's the only term I'm familiar with.

Pyth, 19 18 bytes
j" ~BOO!~ "cz]OtUz

Thanks to @Jakube for golfing off 1 byte!
Try it online.
How it works
                    (implicit) Store the input in z.
                Uz  Compute [0, ... len(z)-1].
               t    Remove the first element.
              O     Select an integer, pseudo-randomly.
             ]      Wrap it in an array.
           cz       Split the input string at that point.
j" ~BOO!~ "         Join the split string, using " ~BOO!~ " as separator.

GML, 91 bytes
s=get_string("","")
show_message(string_insert(" ~BOO!~ ",s,irandom(string_length(s)-2)+1);

Simple enough - get a string, insert the substring into it, output the string. Done.

Never thought I'd see GML on codegolf.

Python 3, 60 bytes
s=input();n=1+hash(s)%(len(s)-1);print(s[:n],'~BOO!~',s[n:])

Note:
The modulo of hash() will be uniformly distributed over the length of the string. If you think that's bending the rules, note that because of python's hash randomization, this is actually random: repeated executions with the same input will give different results.

CJam, 20 bytes
l_,(mr)/(" ~BOO!~ "@

Try it online
Explanation:
l       Get input.
_,      Calculate length.
(       Decrement, since the number of possible positions is 1 less than length.
mr      Generate random number between 0 and length-2
)       Increment, giving random number between 1 and length-1.
/       Split. Note that this splits repeatedly, but this will not do any harm.
        We will only really use the first split.
(       Peel off the first fragment after the split.
" ~BOO!~ "
        Push the magic string.
@       Rotate the list with the remaining fragments to the top.

Pip, 19 bytes
Takes input from the command-line. If the input has spaces or other special characters, it will need to be placed in quotes.
a^@1RR#aJ" ~BOO!~ "

Explanation:
a                    Command-line arg
 ^@                  Split at index...
   1RR#a             ...random integer >= 1 and < length(a) (Python randrange)
        J" ~BOO!~ "  Join on that string and autoprint

Do you mean that the input has to be passed as a single command-line argument, or do you actually have to pass quotes to Pip?

@Dennis The former. The quotes are to prevent shell expansion, and to prevent stuff with spaces from being treated as multiple command-line args.

Python 3, 79 bytes
from random import*;s=input();n=randint(1,len(s)-1);print(s[:n],'~BOO!~',s[n:])

Try it online
Pretty self-explanatory - read a string, pick a random integer between 1 and the length of the string, and print the string with ' ~BOO!~ ' inserted.

My solution exactly. To the letter.

@Mego Seeing a random  ~BOO!~  show up in your program is pretty spooky.

Since multiple arguments to print are printed space-separated, you can cut the spaces with print(s[:n],'~BOO!~',s[n:]).

C#, 125 bytes
using System;class X{static void Main(string[]a){Console.Write(a[0].Insert(new Random().Next(a[0].Length-2)+1," ~BOO!~ "));}}

Expanded:
using System;
class X
{
    static void Main(string[] a)
    {
        Console.Write(a[0].Insert(new Random().Next(a[0].Length - 2) + 1, " ~BOO!~ "));
    }
}

This solution assumes that the string is passed in as the first command-line parameter. This is not usual for C# (stdin is more normal), so I’ve also included a solution that uses normal stdin:
C#, 139 bytes
using System;class X{static void Main(){var x=Console.In.ReadToEnd();Console.Write(x.Insert(new Random().Next(x.Length-2)+1," ~BOO!~ "));}}

Expanded:
using System;
class X
{
    static void Main()
    {
        var x = Console.In.ReadToEnd();
        Console.Write(x.Insert(new Random().Next(x.Length - 2) + 1, " ~BOO!~ "));
    }
}

(see comments, arguments are ok) static void Main(string[] x) {Console.Write(x[0].Insert (...) x[0].Length (...) will shorten your code

Julia, 70 bytes
print((s=readline())[1:(r=rand(2:length(s)-2))]," ~BOO!~ ",s[r+1:end])

Ungolfed:
# Read a line from STDIN
s = readline()

# Define a random integer within the bounds of s
r = rand(2:length(s)-2)

# Print to STDOUT with boo in there somewhere
print(s[1:r], " ~BOO!~ ", s[r+1:end])

APL, 27 bytes
{(-⌽' ~BOO!~ ',⍵⌽⍨⊢)?¯1+⍴⍵}

APL doesn't have an insert function, so we rotate the string instead.
{                          }    ⍝ Monadic function:
                     ?¯1+⍴⍵     ⍝ Place to insert string, let's say it's X
 (                  )           ⍝ Monadic train:
               ⍵⌽⍨⊢            ⍝ Rotate input by X (⊢) to the left
    ' ~BOO!~ ',                 ⍝ Concatenate ' ~BOO!~ '
  -                             ⍝ -X
   ⌽                            ⍝ Rotate that by X to the right

Example input on TryAPL

Lua, 75 bytes
s=io.read()m=math.random(2,#s/2);return s:sub(1,m).." ~BOO!~ "..s:sub(m,#s)

Perl, 35 bytes
34 bytes code + 1 byte command line
$-=rand y///c-2;s/..{$-}\K/~BOO!~/

Usage:
perl -p entry.pl

MATLAB, 69 bytes
i=input('');a=randi(nnz(i)-1,1);disp([i(1:a) ' ~Boo!~ ' i(a+1:end)]);

Inserting a string mid string at a given index in MATLAB is costly in terms of bytes. If there was a simple way to do it, I could save a fair amount by moving to an anonymous function, but I can't find one. Ah well.
Basically it gets a random number between 1 and the length of the string minus 1. Then it displays everything up to and including that index, followed by the ~Boo!~, and then everything after the index to the end.

It also works with Octave, so you can try it out online here.

Ruby, 46 bytes
$><<gets.insert(rand(1..$_.size-2),' ~BOO!~ ')

Vitsy, 19 Bytes
Note that z and Z were edited today, but not for this challenge.
I1-R1+\i" ~OOB~ "zZ
I1-                   Get the length of the input, minus 1
   R                  Push a random number from 0 to the top item of the stack.
    1+                Add one to it - this is now a random number from 1 to input
                      length - 1.
      \i              Get that many items of input.
        " ~OOB~ "     Push ' ~BOO~ ' to the stack.
                 z    Get the rest of the input.
                  Z   Output it all.

Bash/GNU, 61 bytes
echo $1|sed "s/.\{`shuf -i1-$((${#1}-1)) -n1`\}/\0 ~BOO!~ /"

Takes input string as argument

JavaScript, 79
r=Math.random()*((x=prompt()).length-1)+1;x.substr(0,r)+" ~BOO!~ "+x.substr(r);

It's for the browser console; have fun just popping that in.

Chaîne, 23 bytes
{il1-R1+`} ~BOO!~ {<$/}

Java 8, 158 154 bytes
interface M{static void main(String[]a){int i=a[0].length()-2;System.out.println(a[0].substring(0,i=1+(i*=Math.random()))+" ~BOO!~ "+a[0].substring(i));}}

Try it here.
EDIT: Only now reading program instead of the default function/program in the challenge description.. So added the bordercode with interface and main method.
If a function would be allowed it would be (99 95 bytes)
s->{int i=s.length()-2;return s.substring(0,i=1+(i*=Math.random()))+" ~BOO!~ "+s.substring(i);}

Try it here.
Explanation:
s->{                        // Method with String as both parameter and return-type
  int i=s.length()-2;       //  The length of the input - 2
  return s.substring(0,i=1  //  Return the first part of the input from index 0 to 1
    +(i*=Math.random()))    //    + a random integer between 0 and length-2
   +" ~BOO!~ "              //   appended with the literal " ~BOO!~ "
   +s.substring(i);         //   appended with the rest of the input-String
}                           // End of method

TeaScript, 30 bytes
xh(j=N(xn-1)+1)+' ~BOO!~ '+xS(j)

Very straight forward.

CJam, 19 bytes
q_,mr)/(" ~BOO!~ "@

This will fail when mr returns 0 or 1, because neither -1 nor 0 are valid for splitting a string with /.

Then it must be )

Now it can put BOO at the end of the string, You'd also need a ( before mr. But then it's identical to this answer: http://codegolf.stackexchange.com/a/62355/8478

I use q (reads all input, including newline), he uses l (reads only 1 line)

Oh okay, then you should specify that your code expects the input to have a trailing linefeed (because it doesn't necessarily have one, in which case q and l are synonymous).

Wait, actually that doesn't solve the problem. I means that BOO could be placed after the linefeed which is yet another character too far away.

In some implementations, linefeeds can be put as part of one input

Let us continue this discussion in chat.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Halloween Golf: The 2spooky4me Challenge!
A current internet meme is to type 2spooky4me, with a second person typing 3spooky5me, following the (n)spooky(n+2)me pattern.
Your mission is to implement this pattern in your chosen language. You should write a program or function that takes a value n (from standard input, as a function argument, or closest alternative), and outputs the string (n)spooky(n+2)me (without the parentheses; to standard output, as a return value for a function, or closest alternative).
Your solution should work for all inputs, from 1 up to 2 below your language's maximum representable integer value (2^32-3 for C on a 32-bit machine, for example).
Example implementation in Python:
def spooky(n):
    return "%dspooky%dme"%(n,n+2)

spooky(2) -> "2spooky4me"
This is code-golf, so standard loopholes are forbidden, and the shortest answer in bytes wins!
Leaderboard
The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

For bonus points: Input %dspooky%dme, validate and return next in series.

True, but Dennis would still win

Will N always be at least 1?

Who is Dennis? :O

@NuWin Dennis is the way. Dennis is the light.

@NuWin Dennis is love, Dennis is life

gs2, 15 bytes
I outgolfed Dennis!
CP437:
spooky•me♣╨V↕0B

Hex dump:
73 70 6f 6f 6b 79 07 6d 65 05 d0 56 12 30 42

At the start of the program, STDIN is pushed (e.g. the string "3") and stored in variable A. The first ten bytes of the program push two strings, "spooky" and "me", to the stack. Then:

d0 pushes variable A.
56 parses it as a number.
12 30 increments it by two.
42 swaps the top two elements on the stack, leaving "3" "spooky" 5 "me".

The final stack is printed as 3spooky5me.

Holy hell, that's short. +1

GJ, but Dennis might come over here and outmod you to preserve his reputation.

What no how how did you do that

I just realized... does gs2 stand for "golf script 2"?

By the way, I've added GS2 to my family of online interpreters, Try it online!

GS2, 17 bytes
56 40 27 27 04 73 70 6F 6F 6B 79 05 42 04 6D 65 05

I CAN'T OUTGOLF DENNIS HELP

relevant

Man, it's so weird that we currently have 4 languages tied for first and 3 languages tied for second :P

Stuck, 17 bytes
i_2+"spooky";"me"

EDIT: GUESS YOU COULD SAY I'M STUCK AT 17 BYTES

Hey cool, someone actually using Stuck :D

@Shebang I actually really like Stuck. Although it would be nice if it had some better methods for manipulating arrays.

GolfScript, 17 bytes
~.2+"spooky"\"me"

Try it online on Web GolfScript.
How it works
~.2+"spooky"\"me"
~                 # Evaluate the input.
 .2+              # Push a copy and add 2.
    "spooky"      # Push that string.
            \     # Swap it with the computed sum.
             "me" # Push that string.

Chef, 414 bytes
S.

Ingredients.
g i
2 g t
115 l s
112 l p
111 l o
107 l k
121 l y
109 l m
101 l e

Method.
Take i from refrigerator.Put e into mixing bowl.Put m into mixing bowl.Put i into mixing bowl.Add t.Put y into mixing bowl.Put k into mixing bowl.Put o into mixing bowl.Put o into mixing bowl.Put p into mixing bowl.Put s into mixing bowl.Put i into mixing bowl.Pour contents of mixing bowl into the baking dish.

Serves 1.

A recipe for disaster. Do not try this at home.

Mm. That's some spooky tastes you got there.

Pyth - 17 bytes
s[Q"spooky"hhQ"me

Try it online here.

Pip, 18 bytes
Looks like I'm in the second tier of golfing languages here. :^P
[a"spooky"a+2"me"]

Try it online!
Takes the number as a command-line argument and puts the appropriate elements in an array, which is joined together and autoprinted at the end of the program.

Five and a half years later, here's a much more interesting 18-byte solution:
"0spooky2me"RXD_+a

Try it online!
In the string 0spooky2me, Replace each digit (built-in regex variable XD) with itself plus the command-line argument (_+a).

The built-in regex variable is XD lol XD

CJam, 18 bytes
ri_2+"spooky"\"me"

Try it online.

TeaScript, 18 bytes
x+`spooky${x+2}me`

Unfortunately this string can't be compressed so this is basically as short as it will get

Welcome to the 18th byte! :P

dc, 20 bytes
?dn[spooky]P2+n[me]P

Japt, 17 16 bytes
U+"spooky{U+2}me

Japt (Javascript shortened) is a language of my invention. It is newer than this challenge; thus, this answer is non-competing. Unlike my other seven unpublished languages, this one has an actual interpreter that is currently being developed and is already partially working.
I wanted to post this because I like how it's the same length as all the existing first-place second-place answers. Here's how it works:
U+"spooky{U+2}me"    implicit: [U,V,W,X,Y,Z] = eval(input)
U+                   input +
  "spooky     me"     this string
         {U+2}         with input+2 inserted here
                     implicit: output last expression

And there you have it. The spec for all functionality used here was finalized on Oct 29th; nothing was changed to make this answer any shorter. Here's the interpreter, as promised.

I'm sure this was pre-shoco, but I think you could've done {U}2me instead of {U+2}me :P

05AB1E, 14 10 bytes
DÌs’ÿæªÿme

Try it online.
Explanation
DÌs’ÿæªÿme

D                get input n and duplicate it
 Ì               increment by 2
  s              Swap. Stack is now [n+2, n].
   ’ÿæªÿme       Compressed string that expands to "ÿspookyÿme". The first ÿ is then replaced by n and the second by n+2.

This seems to work with D removed for 9 bytes

Julia, 23 bytes
n->"$(n)spooky$(n+2)me"

This creates an unnamed lambda function that accepts an integer and returns a string. The output is constructed using Julia's string interpolation.

Gol><>, 21 bytes
I:n"emykoops"6Ro{2+nH

I guess I'm... tied with Perl? Try it online.
I:n            Input n, output n
"emykoops"     Push chars
6Ro            Output top 6 chars (spooky)
{2+n           Output n+2
H              Output stack and halt (me)

Vitsy, 21 Bytes
Note: the Z command was made after this challenge began, but was not made for this challenge.
VVN"ykoops"ZV2+N"em"Z
V                      Grab the top item of the stack (the input) and make it a
                       global variable.
 V                     Call it up - push the global variable to the top of the stack.
  N                    Output it as a number.
   "ykoops"            Push 'spooky' to the stack.
           Z           Output it all.
            V2+N       Call the global variable again, add two, then output as num.
                "em"Z  Push 'me' to the stack and output it all.

More spoopy variation using multiple stacks (27 Bytes):
&"ykoops"&"em"?DN?Z??2+N??Z

&                           Make a new stack and move to it.
 "ykoops"                   Push 'spooky' to the current stack.
         &"em"              Do the last to things with 'me'.
              ?             Move over a stack.
               DN           Output the input.
                 ?Z         Move over a stack (the one with 'spooky') and print it.
                   ??       Move back to the original stack.
                     2+N    Add 2 to the input and output it as a number.
                        ??Z Move to the stack with 'me' in it and print it.

Try it online!

Just wondering, why are strings inverted?

It's pushing chars to the stack one by one.

Jelly
13 bytes
+0,2ż“×¥X“ŀ`»

I CAN'T OUTGOLF QUARTATA HELP
Try it online!
How it works
+0,2ż“×¥X“ŀ`»  Main link. Input: n

+0,2           Add [0, 2] to n, resulting in [n, n + 2].
     “×¥X“ŀ`»  Yield ['spooky, 'me'] by indexing into a dictionary.
    ż          Zip the results to left and right with each other.
               This yields [[n, 'spooky'], [n + 2, 'me']], which is flattened
               before printing.

One does not simply outgolf... quartata?

I can't seem to outgolf quartata, but, since the answer is non-competing, I can give some help. `+2ṭż“×¥X“ŀ`»`

Javascript(ES6) 23 21 Bytes
A simple function that will be crushed by golfing lanqs:
_=>_+`spooky${_+2}me`

_=>`${_}spooky${_+2}me`

Special thanks to ETHproductions for saving 2 bytes

NOICE! You might be able to shorten the template strings, but I can't think of any way to do so

Two bytes saved: _=>_+`spooky${_+2}me`

Thank you, but now the fix seems so obvious I feel stupid. I think this is the shortest possible way to do this in Javascript, I could be wrong( I hope I'm wrong)

Ruby, 25 bytes
->n{"#{n}spooky#{n+2}me"}

This creates an unnamed lambda that accepts an integer and returns a string. The string is constructed using Ruby's string interpolation.

APL, 25 22 bytes
⍕,'spooky','me',⍨∘⍕2+⊢

This creates an unnamed monadic function train that accepts an integer on the left and returns a string.
Numeric values are converted to strings using ⍕. The array of strings is joined into a single string using ∊.
Try it online
Saved 3 bytes thanks to Thomas Kwa!

PHP, 55 47 46 42 34 bytes
<?=($a=$argv[1]).spooky.($a+2).me;

Accepts the number as command line input.
Credits :)
Thanks to manatwork for saving 4 bytes!
Thanks to insertusernamehere for saving 8 bytes!

function a($a){echo$a,"spooky",$a+2,"me";}

You could save 4 bytes by removing the "s.  You could even save 4 more bytes by taking a command line argument and discard the function, like this: <?=($a=$argv[1]).spooky.($a+2).me;.

Chaîne, 15 bytes
noncompeting, language postdates question
{i~}:-,}:{2+}me
{i~}            | input duplicate write
    :   :       | access dictionary with inner base-93 key
     -,}        | entry for "spooky"
         {2+}   | push 2, add previous two, write
             me | write me

Implicit output.

The output is `spookyme 4 2" (newline separated)

@fschmengler I must have messed something up whilst updating the interpreter. Please stand by.

@fschmengler Alright, bugs have been fixed. It should work now.

Perl 5, 20 19 bytes
$\=spooky.($_+2).me

The code requires the -p switch. Thanks to @Xcali for golfing off 1 byte!
Try it online!

Lua for windows, 41 bytes
n=io.read()print(n.."spooky"..n+2 .."me")

test with lua for windows
it takes the input through io.read then stored in variable n then on the same line prints the variable n then "spooky" then n+2 finally it prints "me"

Remove whitespace and save bytes
n=io.read()print(n.."spooky"..n+2.."me")

@DigitalVeer - Without the whitespace 2. will be treated as a number.

p.lua: print(.....'spooky'.. ...+2 ..'me')  How to run: lua51.exe p.lua 2 Size = 35 bytes.

Mathematica, 45 27 bytes
Print[#,"spooky",#+2,"me"]&

g=ToString[#]<>"spooky"<>ToString[#+2]<>"me"&
Thanks to Martin Büttner for the significant improvement (and the warm welcome).

Welcome to PPCG! Unnamed functions are fine, so you don't need the g= and I think Print[#,"spooky",#+2,"me"]& should work as well. :)

What about Row@{#,spooky,#+2,me}&?  The output is visually similar if the variables are not defined.

Simplex v.0.7, 20 bytes
Simplex simply isn't feeling golfy today. >_<
i@R"spooky"&IIR"me"g
i@                   ~~ take input and copy to register
  R"spooky"          ~~ write that string to the strip (increment byte after every character)
           &II       ~~ write the register (incremented twice) to the strip
              R"me"  ~~ write that string to the strip
                   g ~~ output the strip

You still beat Vitsy. o-o

@VoteToClose Don't feel too bad. Last Simplex version would've been ~25+ characters. Either way, 20 or 21 bytes doesn't come close to 17 ;-;

Dennis wins again.

@VoteToClose What did you expect? He's a mod XD

We need to add this to the meme list.

@VoteToClose You need to do it. For the meme-ness

C, 58 bytes
main(a,b)char**b;{printf("%sspooky%dme",*++b,atoi(*b)+2);}

atoi() may be unnecessary.

Fails on my gcc, because it depends on evaluation order. 2. Save a byte with int**b.

Minkolang 0.10, 49 bytes
I have no way to convert integers to strings (yet!), so this is much longer.
"me"nd2+(dl%"0"+$rl:d)"spooky"2g(dl%"0"+$rl:d)$O.

Try it here.
Explanation
(dl%"0"+$rl:d) does the job of converting an int to a string. If this were replaced by a single character (like Z), then my solution would be just 23 bytes.
"me"nd2+Z"spooky"2gZ$O.

nd takes an integer from input and duplicates it. 2+ adds 2 and 2g later gets the initial input and puts it on top of stack. $O. outputs the whole stack as integers and stops.

Surely it's shorter to just output the numbers as numbers?

Outputting as number automatically adds a space to the output. So it'd be "2 spooky4 me".

Rotor, 15 bytes
&"spooky"~2+"me

Language was created after the challenge. Does not work in the online interpreter (uses input eval.)

Dam son. You outgolfed Dennis. Finally. Hooray!

Rotor is dead to me don't try to resurrect it please.

Nice job, even in Rotor!! You should reward it with life.

Cookie, 16 bytes
Note that the recent changes to the Github page were not made for this challenge, Cookie is still in development.
wŕspooky[r+2]me"

Explanation:
wŕspooky[r+2]me"
w                 start write command
 ŕ                take input
  spooky          write spooky
        [r+2]     compute input + 2
             me   write me
               "  close write command.

Factor, 30 bytes
[ dup 2 + [I ${}spooky${}meI]]

TIO doesn't have the interpolate vocab, so have a screenshot:

Vim, 18 17 bytes
C<C-r>"spooky<C-r>"<esc><C-a><C-a>ame

Try it online!
Explanation
C

Delete the input number (storing it in the register) and enter insert mode.
<C-r>"spooky<C-r>"

Insert the number from the register, followed by spooky, followed by the number from the register again.
<esc><C-a><C-a>

Leave insert mode and increment the number under the cursor twice.
ame

Insert me after the number.

Python, 31 bytes
lambda n:"%dspooky%dme"%(n,n+2)

Ask and you shall receive.

Python 3.6+ lambda n:f'{n}spooky{n+2}me' for 28 bytes.

Java, 39 35 bytes
n->"".format("%dspooky%dme",n,n+2);

A lambda expression that takes an int and returns a string.

Mouse, 25 bytes
?N:N.!"spooky"2N.+!"me"$

Ungolfed:
? N:         ~ Read an integer N from STDIN
N. !         ~ Write N to STDOUT
"spooky"     ~ String literals go straight to STDOUT
2 N. + !     ~ Print N+2
"me"
$            ~ End of program

Gema, 21 characters
*=*spooky@add{$0;2}me

Sample run:
bash-4.3$ echo -n 42 | gema '*=*spooky@add{$0;2}me'
42spooky44me

jq, 21 characters
(20 characters code + 1 character command line option.)
"\(.)spooky\(.+2)me"

Sample run:
bash-4.3$ jq -r '"\(.)spooky\(.+2)me"' <<< 42
42spooky44me

On-line test (Passing -r through URL is not supported – check Raw Output yourself.)

PowerShell, 31 30 29 bytes
param($x)"$x`spooky$($x+2)me"

Try it online!
Takes input $x, constructs and leaves a string on the pipeline with implicit output. The string is formed from $x spooky $x+2 me, with the trick being the ` that allows the variable name to be escaped to be just $x instead of $xspooky.
-1 byte thanks to Veskah.

param($x)"$x\spooky$($x+2)me"` is one shorter

Bash, 24 bytes
echo $1spooky$(($1+2))me

Takes input as command line argument

There is also an old syntax for arithmetic evaluation: $[…]. It is deprecated, but that usually not holds us back from using it.

pl, 12 bytes
_spooky_2┼me

Try it online.
Non-competing since pl was invented after this challenge.

Scala, 30 bytes
(n:Int)=>s"${n}spooky${n+2}me"

Jolf, 15 bytes
Try it here! I forgot about inline string interpolation until after @quartata posted his solution.
"¦jspooky¦+2jme

Explanation
"¦jspooky¦+2jme
"               string containing
 ¦j              the input,
   spooky        "spooky"
         ¦+2j    2 + the input,
             me  and "me"
                implicitly printed.

Java 8, 24 bytes
n->n+"spooky"+(n+2)+"me"
That moment when Java is actually competitive... (and by competitive I mean top 40 :P)
Try it online!

Pyramid Scheme, 624 bytes
   ^      ^      ^      ^     ^      ^      ^      ^      ^
  / \    / \    / \    / \   / \    / \    / \    / \    / \
 /set\  /out\  /out\  /out\ /out\  /out\  /out\  /out\  /out\
^-----^^-----^ -----^ -----^----- ^----- ^-----^ -----^ -----^
-    ^--    / \    / \    / \    / \    / \   /+\    / \    / \
    /#\    /chr\  /chr\  /chr\  /chr\  /chr\ ^---^  /chr\  /chr\
   ^---   ^----- ^----- ^----- ^----- ^-----/2\  - ^----- ^-----
  /l\    / \    / \    / \    / \    / \    ---   / \    / \
 /ine\  /115\  /112\  /111\  /107\  /121\        /109\  /101\
 -----  -----  -----  -----  -----  -----        -----  -----

Try it online!
Very straightforward. Gets an integer from input and saves it to the blank variable. Prints it. Prints "spooky". Prints blank+2. Prints "me". Follows the same pattern as Hello, World, for the most part.

Wren, 31 bytes
Not special, just uses some formatting
Fn.new{|n|"%(n)spooky%(n+2)me"}

Try it online!

MarioLANG, 221 bytes
;>+>+>+>+>.>)
:"+"+"+"+"-"-
)++++++++.-:-
+++++++++--+-"
+++++++++.-+-.
+++++++++-.(--
+++++++++-+.--
+++++++++-++--
+++++++++.++--
++++++++++++--
++++++++++++--
++++++++++++--
++++++++++++--
+!+!+!+!+!+!.!
=#=#=#=#=#=#=#

Try it online!

Canvas, 13 bytes
╶spooky╶├me）∑

Try it here!

Aussie++, 60 bytes
THE HARD YAKKA FOR f IS(n)<BAIL ""+n +"spooky"+(n +2)+"me";>

Tested in commit e0091bc.
For some reason, the space in n + is required. The empty string at the beginning seems unnecessary but isn't, see this issue.

Regenerate, 19 bytes
$~1spooky${$~1+2}me

Attempt This Online!
Explanation
$~1spooky${$~1+2}me
$~1                  First command-line input
   spooky            spooky
         ${     }    Treat the result of this expression as a string:
           $~1         First command-line input
              +2       Plus 2
                 me  me

Go, 70 bytes
import."fmt"
func f(n int)string{return Sprintf("%dspooky%dme",n,n+2)}

Attempt This Online!

Groovy, 24 22 bytes
{it+"spooky${it+2}me"}

At string's ends is shorter to concatenate: {it+"spooky${it+2}me"}.

C# 33 bytes
string s(n)=>$"{n}spooky{n+2}me";

Carrot (version ^3), 14 bytes
#spooky(#+2)me

Explanation:
Carets ^ have now been made optional if you do not want to use commands. The # is the variable representing the input. Every instance of # is replaced with the value of input. Going to the parentheses, the expression inside the parentheses is evaluated and a number is returned.
Test it online here. Please note that this is not permalinked.

Did you write this before the challenge, and do you have proof?

@ThomasKwa I started writing this on the 1st of November. And proof is in Carrot's website

I might actually start using Carrot. XD

Retina, 17 bytes
This assumes that the integer n may be expressed in unary in the output. Each line would go in its own file, with one byte added per additional file.
1+
$_spooky$_11me

If the input is 11, the output is 11spooky1111me.
For non-unary output (but still unary input), use this (27 bytes):
1+
$_spooky$_11me
(\d)+
$#1

Try it online

Is unary the standard way of expressing numbers in retina?

Burlesque, 21 bytes
J2?+Cl"~spooky~me"jf~

Needs fixed stack layout. Not usable except as a stand-alone program. Otherwise use one of the versions below that are more generic.
Alternative versions:
"~spooky~me"jbxJ2?+_+f~ [24 bytes]
J"spooky"?+j2?+"me"?+?+ [24 bytes, too]

O, 20 bytes
j.o"spooky"o))o"me"o
Kinda long Try it online

j          Get input as Number
.          Clone the number to add to later
o          Print the number
"spooky"o  Print spooky
))o        Increment the input by two and print
"me"o      Print me

JS (ES5) 41
Oh, ES6...
function(a){alert(a+"spooky"+(a+2)+"me")}

Coffeescript, 23 bytes
(n)->n+"spooky#{n+2}me"

Anonymous function that takes int n and returns <n>spooky<n+2>me.

Nice! You could save two bytes with (n)->n+"spooky#{n+2}me".

@ETHproductions Didn't think of that! Thanks!

C++11, 142 130 108 bytes
Self-imposed challenge: no C headers
#include<sstream>
#include<string>
[](int x){std::stringstream q;q<<x<<"spooky"<<x+2<<"me";return q.str();}

Thanks to Mego for saving a few bytes with the return logic everything.

Good tip. I'll make the changes accordingly.

That's terrifying, and also really neat.

Ooh. That's good.

><>, 25 (+2) = 27 bytes
:n'emykoops'oooooo{2+noo;

Starting with a value (n) on top of the stack from -v (2 byte penalty). Explanation:
:            Duplicates top item on stack
 n           Pops and outputs top value on stack as number -> n
  'emykoops' Pushes each character onto the stack
   o         x5 Pops and outputs top value on stack as character -> "spooky"
    {        Shift stack leftwards making input value top value
     2       Pushes 2 on the stack
      +      Pops top 2 elements, sums them and pushes result
       n     Pops and outputs top value on stack as number -> n+2
        o    x2 Pops and outputs top value on stack as character -> "me"
         ;   Ends execution

Seriously, 20 bytes
"me",;⌐@"spooky"@kεj

Since this challenge partially inspired this language, I figured I should go ahead and add a solution. Try it online!

A golfing language partially based on this challenge got 20 whole bytes?

@Cyoce I still haven't implemented the parts of the language that were inspired by this challenge (raw strings mode).

F#, 33 bytes
fun n->printf"%ispooky%ime"n<|n+2

Squirrel, 25 bytes
@(n)n+"spooky"+(n+2)+"me"

Applesoft BASIC, 28 bytes
0input n:?n;"spooky";n+2;"me

The question mark expands to PRINT and the missing final double quotation mark is implied.
Tested with Joshua Bell's online emulator.

D, 71 bytes
import std.string;string s(int i){return format("%sspooky%sme",i,i+2);}

More verbose than Java...

Jolf, 16 bytes
"%spooky%me"J+2J

Try it online.

R, 38 bytes
n=scan();sprintf("%dspooky%dme",n,n+2)

or (same length)
sprintf("%dspooky%dme",n<<-scan(),n+2)

Example:
n=scan();sprintf("%dspooky%dme",n,n+2)
1: 999
999spooky1001me

paste0(n<-scan(),"spooky",n+2,"me") for 35 :-)

Pylongolf, 20 bytes
_:AA"spooky"A2+"me"~

_ asks for input and :A puts it into the variable A.
A"spooky" pushes A, and spooky then A2+ adds the input + 2.
After that we push "me" into the stack and print it with ~.

LOLCODE, 100 99 bytes
HAI 1.3
I HAS A J
GIMMEH J
VISIBLE J!
VISIBLE "spooky"!
VISIBLE SUM OF J AN 2!
VISIBLE "me"
KTHXBYE

Try it online!

Stacked, 21 bytes
[:2+,'spooky'#`'me'+]

Try it online!
Function returning the string.
Explanation
[:2+,'spooky'#`'me'+]
[                   ]  function                stack: (y)
 :                     duplicate               stack: (y y)
  2+                   add 2                   stack: (y y+2)
    ,                  pair                    stack: ((y y+2))
     'spooky'#`        join by "spooky"        stack: ("{y}spooky{y+2}")
               'me'+   append the string "me"  stack: ("{y}spooky{y+2}me")

Kotlin, 24 bytes
{"${it}spooky${it+2}me"}

Try it online!

Forth (gforth), 39 bytes
: f 0 2dup .r ." spooky"2 m+ .r ." me";

Try it online!
Code Explanation
: f            \ start a new word definition
  0 2dup       \ add 0 to the top of the stack and duplicate the top two stack values
  .r           \ print the input with no following space
  ." spooky"   \ print "spooky"
  2 m+ .r      \ add 2 to the input and print with no following space
  ." me"       \ print "me"
;              \ end the word definition

Stax, 12 bytes
ïöeO¬‼3ì╡☻↔G

Run and debug it
Uses an unterminated template literal to embed instructions in an output string.

Assembly (MIPS, SPIM), 221 bytes
.data
a: .asciiz "spooky"
c: .asciiz "me"
.text
.globl main
main:
li $2 5
syscall
la $9 a
la $10 a
move $8 $2
l:
move $4 $8
li $2 1
syscall
li $2 4
move $4 $9
syscall
bne $10 $9 e
la $9 c
addi $8 2
j l
e:
li $2 10
syscall

Try it online!
Couldn't get SPIM and TIO to play nice with argc/argv, so had to take it via input. String formatting in Assembly isn't pleasant.

Keg, -no 13 bytes
:&spooky&2+me

This was way too spooky. It's not even October!
Pushes the evaluated input and stores it in the register, pushes the sequence spooky, adds two to the value in the register and then pushes the sequence me.
Uses the latest version of the interpreter which hasn't been updated on TIO thus far.

tq, 16 bytes
?"spooky"?+2"me"

Explanation
# Define an array with 4 items
?                # First item: input
 "spooky"        # Second item: "spooky"
         ?+2     # Third item: input + 2
            "me" # Fourth item: "me"

# Print without a separator
```

I may start trying to make it a golfing language as well. I am thinking about adding increment-by-2 and length-2 strings.

W d, 14 bytes
♠╚z[·7♦÷U# 1╘╖

Explanation
Uncompressed:
"a"spooky"a2+"me"

""                 % Push an empty string for the first operand to render
  a                % The 1st operand
   "spooky"        % Push "spooky"
           a2+     % The 1st operand + 2
              "me" % Push me

BRASCA, 27 bytes
ig:an`ykoops`[o]A}}n`em`[o]

Try it online!
Explanation
<implicit input>             - Push STDIN on the stack
ig                           - Turn the codepoints of 0-9 into 0-9, and concatenate stack
  :a                         - Store a copy into register A
    n                        - Print the original (this disables implicit output)
     `ykoops`[o]             - Push and print "spooky"
                A}}          - Get the copy from register A and increment twice
                   n         - Print the incremented copy.
                    `em`[o]  - Push and print "me"

Zsh, 21 20 bytes
<<<$1spooky$[$1+2]me

try it online!

What's the \ for?

Huh. I thought the shell needed it. Thanks

Swift, 26 bytes
{n in"\(n)spooky\(n+2)me"}

TIO link

Python 3, 28 bytes
lambda n:f'{n}spooky{n+2}me'

Try it online!

Rust, 37 33 bytes
Thanks @xigoi for tip on removing i32 type signature for n
|n|{print!("{}spooky{}me",n,n+2)}

Try it Online!

You don't need the :i32.

cool i added it

QBasic, 52 bytes
INPUT n
?MID$(STR$(n),2)"spooky"MID$(STR$(n+2),2)"me

Try it at Archive.org.
Explanation
QBasic's annoying number-to-string formatting is on full display here. Printing a number directly adds a leading and trailing space, so that's out. PRINT USING seems tailored for fixed-width columns and doesn't do well with numbers of different lengths. STR$(n) is a little better: it only adds a leading space, which we can remove by taking a substring starting at the second character with MID$.
INPUT n                                       Get a number from the user
?                                             Print
 MID$(STR$(n),2)                              The number w/o leading space
                "spooky"                      That string
                        MID$(STR$(n+2),2)     The number + 2 w/o leading space
                                         "me  That string (close-quote implied)

Fig, \$17\log_{256}(96)\approx\$ 13.993 bytes
%"%spooky%me"$w}}

Try it online!
Sadly, "%spooky%me" is incompressible in Fig.
%"%spooky%me"$w}}
               }} # Increment twice
              w   # Wrap it in a list with the original number
             $    # Reverse the list
%"%spooky%me"     # Replace all '%' in "%spooky%me" with the elements in ^

Rattle, 23 bytes
\&spooky&me|Ig0bb1+2bb2

Try it Online!
Explanation
           |                 everything before this is input
\                            as input, take an input string
 &spooky                     ...and "spooky" (hard-coded)
        &me                  ...and "me" (hard-coded)
            I                split input list and store in consecutive memory slots
             g0              get the first element
               b             add this to the print buffer
                b1           add the element in memory slot 1 ("spooky")
                  +2         add 2 to the top of the stack
                    b        add the top of the stack to the print buffer
                     b2      add "me" to the print buffer (buffer output implicitly)

Whitespace, 142 bytes
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][T  N
S T _Print_as_integer][S S S T  T   T   N
_Push_7_y][S S T    T   T   T   N
_Push_-7_k][S S T   T   T   N
_Push_-3_o][S N
S _Duplicate__o][S S T  T   S N
_Push_-2_p][S S S T N
_Push_1_s][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_top][N
T   S S N
_Jump_to_Label_DONE_if_0][S S S T   T   T   S S T   S N
_Push_constant_114][T   S S S _Add][T   N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_DONE][T   T   T   _Retrieve_input][S S S T    S N
_Push_2][T  S S S _Add][T   N
S T _Print_as_integer][S S S T  T   S T T   S T N
_Push_109_m][T  N
S S _Print_as_character][S S S T    T   S S T   S T N
_Push_101_e][T  N
S S _Print_as_character]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Try it online (with raw spaces, tabs and new-lines only).
Explanation in pseudo-code:
Push 0
Integer n = STDIN as number
Print n as integer to STDOUT
Push codepoint-integers c for "ykoops", each lowered by 114
Start LOOP:
  If top == 0: Go to function DONE
  Add 114 to the top c
  Print c as character to STDOUT
  Go to next iteration of LOOP

function DONE:
  Print n as integer to STDOUT
  Print "me" as characters to STDOUT
  (stop the program implicitly with an error: no exit defined)

The constant 114 is generated by this Java program, based on this Whitespace tip of mine.

Arturo, 25 bytes
$[n]->~"|n|spooky|n+2|me"

Try it

Thunno J, \$ 19 \log_{256}(96) \approx \$ 16 bytes
(actually 15.64 bytes but the leaderboard doesn't take floats)
D2+"spooky"s"me"ZMr

Attempt This Online!
Explanation:
D2+"spooky"s"me"ZMr   # Implicit input
D2+                   # Duplicate and add 2
   "spooky"s          # Push "spooky" and swap
            "me"      # Push "me"
                ZMr   # Push the stack, reversed
                      # J flag joins by ""
                      # Implicit output

Thunno 2 j, 10 bytes
ƙ`me+‘ọṣ‘$

Attempt This Online!
Explanation
ƙ`me+‘ọṣ‘$  # Implicit input
ƙ           # Increment the input twice
 `me+       # Append the string "me"
     ‘ọṣ‘   # Push compressed string "spooky"
         $  # Push the input again
            # Implicit output of joined stack

Uiua, 17 bytes
$"_spooky_me"∶+2.

Try it!

Clojure, 26 bytes
#(str %"spooky"(+ 2%)"me")

First post. It's a function, as required. I think I took as many liberties with the tokenizer as possible, but I don't know. Here it is in action in the REPL:
user=> #(str %"spooky"(+ 2%)"me")
#<user$eval1176$fn__1177 user$eval1176$fn__1177@2d2d2f69>
user=> (*1 55)
"55spooky57me"

Dart, 27 Bytes
t(n)=>'${n}spooky${n+2}me';

Unremarkable but competitive.

Welcome to Programming Puzzles & Code Golf!

Factor, 79 bytes
: f ( x -- ) dup 2 + [ number>string ] bi@ "spooky" swap "me" 4array concat . ;

First stab at it, just did it the obvious way.

MATLAB, 33 bytes
@(x)fprintf('%dspooky%dme',x,x+2)

Pretty self explanatory. Tried a few ways and this was the shortest I could find.
You should be able to run this with the Octave online interpreter.

O, 20 characters
Q"spooky"Q2+"me"+++p

Sample run:
bash-4.3$ o.sh 'Q"spooky"Q2+"me"+++p' <<< 42
42spooky44me

Fourier, 32 bytes
I~zo115a-3avaa-4a121az+2o109a-8a

Still using @isaacg's golfing algorithm ;)

Haskell, 38 bytes
a n=show(n)++"spooky"++show(n+2)++"me"

Defines a function named a that takes a Num n. Returns <n>spooky<n+2>me.

You can save a byte by writing show n instead of show(n).

Lua, 41 Bytes
There's this other lua answer, but it doesn't work anymore since lua 5.3. It will now print 2spooky4.0me Here comes a code working under all versions of lua, and who's still in 41 Bytes:
print(("%dspooky%dme"):format(...,...+2))

,,,, 18 bytes
:↓2+"spooky"↓↓"me"

Acc!!, 99 bytes
N
Write _
Write 115
Write 112
Write 111
Write 111
Write 107
Write 121
Write _+2
Write 109
Write 101

Try it online!

Implicit, 20 17 16 bytes
ì¯spooky]ì..ìme"

Try it online!
ì¯spooky]ì..ìme"
ì                 « implicit integer input, convert to string     »;
 ¯                « copy input to memory                          »;
  spooky          « push the ASCII character codes for each letter in `spooky` individually »;
        ]         « copy memory to stack                          »;
         ì        « convert string to integer                     »;
          ..      « increment twice                               »;
            ì     « and back to string                            »;
             me   « push character codes for `me`                 »;
               "  « stringify the entire stack                    »;

Python ≥ 3.6, 28 bytes
lambda x:f'{x}spooky{x+2}me'

Try it online!
Makes use of formatted string literals, a feature that was introduced in Python 3.6.

SmileBASIC, 26 bytes
INPUT N?N;"spooky";N+2;"me

T-SQL, 40 bytes
SELECT CONCAT(n,'spooky',n+2,'me')FROM t

Input taken via a pre-existing table t with integer column n, per our input standards.
CONCAT does an implicit type conversion, otherwise I'd have to do something like CONVERT(n,varchar(9)).

OCL, 52 46 bytes
Function a b Print b+"spooky"+(b + 2)+"me" End

This one is pretty straight forward, I just wanted to show off an obscure language.
Edit: I found out you can omit the spaces between the pluses when doing concatenation, but not addition. Weird.

MATL, 18 bytes
'spooky'yUQQV'me'v

Try it on MATL Online

Pip, 23 bytes
(a:q)."spooky".a+2."me"

Try it online!

Stax, 14 bytes
ü╫2┐╚╘Wö»§W╟╛╨

Run and debug it at staxlang.xyz!
Unpacked (16 bytes)
.me;2+`tNCrf`,Wp
.me                 Literal "me"
   ;2+              Peek from input stack, push to stack, and add 2
      `tNCrf`       Literal "spooky"
             ,      Pop from input stack; push to stack
              Wp    Pop and print everything from the stack with no additional newlines

Excel, 22 bytes
=A1&"spooky"&A1+2&"me"

Runic Enchantments, 18 bytes
i:2+"me"S9´334E{@

Try it online!
Saves 1 byte by using 9´334E to pull "spooky" out of the word dictionary. 8b*E for "me" is the same length.

Japt, 14 bytes
`èï`ri@°+T°

Try it
Japt, 13 bytes
+`spooky{+2}´

Try it

AWK, 21 bytes
$0=$0"spooky"$0+2"me"

Try it online!
Substitutes the input for (input)spooky(input+2)me. As the new value of $0 is not zero nor null, prints $0.

Lua, 39 bytes
w=io.write w(...)w'spooky'w(...+2)w'me'

Test
> lua -v & echo -------- & lua ./spooky.lua 2
Lua 5.4.0  Copyright (C) 1994-2020 Lua.org, PUC-Rio
--------
2spooky4me

JAVA, 60 bytes
class p {String main(int n) {return n+"spooky"+(n+2)+"me";}}

Works fine on blueJ but not on TIO idk why?

It might be because your main function does not seem standard, it should be public static void main(String[] args) { ... } and parse args[] accordingly before calculating : int n = Integer.parseInt(args[0]);. You could lose the spaces before the opening braces and save some bytes

ARE JVM for blueJ and TIO different?

Vyxal Ṫ, 12 bytes
:⇧‛me«½↵*←«∇

Try it Online!
2spooky4joe
Explained
:⇧‛me«½↵*←«∇
:⇧             # Without popping, push input + 2 - this leaves the stack as [input, input + 2]
  ‛me          # push the string "me"
     «½↵*←«    # and the string "spooky"
           ∇   # rotate the top three items and output the sum of the stack

I don't think this code works anymore (maybe it worked on previous versions?), but replacing the ~ with a : fixes it: Try it Online!

tinylisp, 72 bytes
(load library
(q((N)(strcat(string N)(join2(q spooky)(q me)(string(a N 2

Anonymous function that takes a number and returns a name (tinylisp's equivalent of a string). Try it online!
Ungolfed/explanation
(load library)         ; Needed for strcat, join2, and ungolfed aliases

(lambda (N)            ; Anonymous function with one argument
  (strcat              ; Concatenate these two names as a single string:
    (string N)         ; Convert the input number to a string, and
    (join2             ; Join these strings together:
      (q spooky)       ;   "spooky" and
      (q me)           ;   "me", with the following separator:
      (string          ;   Convert to a string
        (add2 N 2))))) ;   the input number plus 2

Python, 39 bytes
x=int(input());print(f"{x}spooky{x+2}me)

Don't remove the int(). That will cause an error.
Tested on Python 3.10.1 (v3.10.1:2cd268a3a9, Dec  6 2021, 14:28:59) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin

You are missing a quote mark before the last closing bracket.

BQN, 30 28 bytes
•Fmt∾"spooky"∾"me"∾˜·•Fmt+⟜2

Anonymous tacit function. Try it at BQN online
Explanation
Reading right-to-left:

+⟜2 adds 2 to the argument
•Fmt converts that number to a string
· helps with parsing
"me"∾˜ concatenates me to the end of the string
"spooky"∾ concatenates spooky to the beginning of the string
•Fmt∾ concatenates the argument, stringified, to the beginning of the string

MathGolf, 11 bytes
k╕o3╣Rk⌠ûme

Try it online.
Explanation:
k           # Push the input-integer
 ╕o3        # Push compressed string "spoo"
    ╣R      # Push compressed string "ky"
      k     # Push the input-integer again
       ⌠    # Increase it by 2
        ûme # Push string "me"
            # (after which the entire stack joined together is output implicitly)

k...k⌠ could alternatively have been └)...@ for the same byte-count: try it online.
└           # Increase the (implicit) input-integer by 1 without popping
 )          # Pop and increase it by 1 again
       @    # Reverse triple-swap the top three values on the stack

J, 24 bytes
'me',~":,'spooky',":@+&2

Attempt This Online!
If you've seen the BQN or APL golfs then you've seen this one.

><> (Fish), 26 bytes
:n'ykoops'oooooo2+n'em'oo;

Try it


text:
The arrow maze escape
Question
You have a 50 by 50 character array. Each cell has an arrow pointing in any one of four directions. No cell is empty. On entering a cell, you must exit it in the direction specified by the arrow. The arrow may also point in the same direction you came from, resulting in a dead end.
You may start from any cell on the outermost border of the maze and find a path that takes you in the maze, and causes you to exit at some other cell. Input will be given as an array containing <, >, ^ and v. Output will be a single digit (Boolean, integer or character, anything will do) as 0 (indicating that the task is impossible) or 1 (indicating that you have achieved the task).
Example (actual array will be bigger than this)
^ v < >
> < v <
v > v ^

Output will be 1 as you can enter from the < on the right, which will cause you to exit from the bottom v by the path "< v v"
The task is to write the shortest possible code that will receive the maze as input, and determine where there exists a path in it as specified in the rules and output a single digit 0 or 1
Outputing TRUE and FALSE instead of actual digits is also allowed.

It would be nice to have some actual test cases to work with

Is the input a one dimensional array or a two dimensional? And can you only enter on the right by a < or can you also enter by a ^ ?

@bobbel Input can be given as a 1 or a 2 dimensional array, whichever is required for a shorter code. Even arrows can be entered as 1 2 3 4 instead of < > ^ v if that can shorten the code. And yes,  you can enter via the ^ also.

@ LiamNoronha It's not that hard to randomly generate test cases.

You mention the possible output in several parts of the challenge, but I'm still not quite sure what exactly is permitted. My answer currently prints 1 if there exists a path and 0 if not. Could it also print 0 if there exists a path and 1 if not?

@Dennis No, it should print TRUE or 1 if there exists a path.

Oh, I may return the Boolean, integer or character 0. Now I get it.

The likelihood that a random, 50 by 50, array will not have a solution is just about 0.  It would be better if you required that the solution have at least a certain number of steps or that the user specified the solution path.

Could I enter the bottom through a v?

@DanTheMan Nope.

This should have been called "An arrow escape"... Still pondering a solution.

CJam, 89 81 bytes
q~"><v^":A2/{f{\*}z}/sA[1W52-52]er:T,,{[52md]51f%0e=1=},:E{[2704{__T=+}*]\-E&},,g

Try it online in the CJam interpreter.
How it works
q~        e# Read and evaluate all input. This pushes an array of strings.
"><v^":A  e# Push that string and save it in A.
2/        e# Split it into ["><" "v^"].
{         e# For each chunk:
  f{      e#   For each input string, push the string and the chunk; then:
    \*    e#     Join the chunk, using the string as separator.
  }       e#
  z       e#   Transpose rows and columns.
}/        e#
s         e# Flatten the resulting array of strings.
A         e# Push "><v^".
[1W52-52] e# Push [1 -1 52 -52].
er        e# Perform transliteration.
:T        e# Save the result in T.
,,        e# Push [0 ... 2703].
{         e# Filter; for each integer I in [0 ... 2703]:
  [52md]  e#   Push [I/52 I%52].
  51f%    e#   Take both integers modulo 51 to map 51 to 0.
  0e=     e#   Count the number of resulting zeroes.
  1=      e#   Check if the count is 1.
},        e# If it is, keep I.
:E        e# Save the filtered array in E.
{         e# For each integer I in E:
  [2704{  e#   Do 2704 times:
    __    e#     Push two copies of the integer on the stack.
    T=    e#     Select the corresponding element from T.
    +     e#     Add it to the first copy.
  }*]     e#   Collect all results in an array.
  \-      e#   Remove I from that array.
  E&      e#   Intersect with E.
},        e# If the intersection is non-empty, keep the integer.
,g        e# Push the sign of the length of the filtered array.


text:
Epcot World Reorder
Intoroduction
If you've ever been to Epcot at Disney World, you've probably been to the world showcase: a lake surrounded by various country-themed locations. One thing that's always bothered me about it is that the countries don't appear in the order you would run into them around the world. There are officially eleven of them, and the order is (going clockwise around the circle):
Mexico
Norway
China
Germany
Italy
United States
Japan
Morocco
France
United Kingdom
Canada

Challenge
Write a function or program that takes the list of countries (as a list, separated string, or other convenient form) in the order given above, and return/output them in an order that you would run into them if you were head around the world (either east-west or west-east) from a start point of your choosing. For specificity, lets define the capital of each country as it's "position", and order longitudinally. Output format should be the same as the input format.
Standard code golf rules apply. Shortest code wins, with exception to the bonus below. The winner will be determined by the code with the lowest score that accomplishes the criteria, and will be selected in a minimum of seven days.
Bonus
If your code can take in arbitrary country names (beyond just the eleven listed above) and order them as well, subtract 33% from your score. If you invoke this bonus, you must start from the Prime Meridian, but which direction you go from there is up to you. Because the total number of "sovereign states" is a disputed thing, I'll settle for at least 190 of them.
Example
Input
['Mexico', 'Norway', 'China', 'Germany', 'Italy', 'Unites States', 'Japan', 'Morocco', 'France', 'United Kingdom', 'Canada']

Output
['Mexico', 'United States', 'Canada', 'Morocco', 'United Kingdom','France', 'Norway', 'Italy', 'Germany', 'China', 'Japan']

If you can only go east or west, and only the longitude of the capital counts, then the output can only be a reversed/rotated version of the example output, correct?

@Calvin'sHobbies That is correct, unless you're going for the bonus, which limits it further.

CJam (18 bytes)
This is an anonymous function which takes input as an array of strings and returns it as an array of strings.
{36061983185Bb\f=}

Online demo
A slightly more general version, which takes any subset of the 11 countries in any order and sorts them correctly, is 26 bytes:
{{71b226%75585218525Bb=}$}

For the 30% bonus to give a better score, it would be necessary to encode the data for 190 countries in at most 37 bytes (including the code to use it); that's about 1.5 bits per country. But 190! is about 2^1169.3, requiring 147 bytes, so the 30% bonus is obviously not at all interesting without cheating by using external data sources.

Indeed, I didn't want to make the bonus too high, because I figured then something like mathmatica would just win outright. But I wanted the possible incentive for people to write the harder program at the very least for the challenge of it. Nice work.

Mathematica, 50 bytes
f=SortBy[CountryData[#,"CapitalLocation"][[1,2]]&]

Example:
In[12]:= f@{"Mexico", "Norway", "China", "Germany", "Italy",
  "United States", "Japan", "Morocco", "France", "United Kingdom",
  "Canada"}

Out[12]= {Mexico,United States,Canada,Morocco,United Kingdom,France,Norway,Italy,Germany,China,Japan}

Mathematica has built-in functions for every kind of data like this...

With bonus:
Mathematica, 58 bytes − 33% = 38.86 bytes
f=SortBy[CountryData[#,"CapitalLocation"][[1,2]]~Mod~360&]

I had a feeling Mathematica would have something for this, but wasn't sure how concise it would be. Well done!


text:
Imitate an ordering
Given two lists of numbers, a source and a pattern, reorder the source to match the relative ordering of the pattern. Any two entries of the reordered source should compare the same way as the entries at those same positions of the pattern.
For example, the input
s = [-5, 9, 4, 13, 11, -6, 0]
p = [7, -4, 1, -8, 4, -3, 12]

should produce the result
    [11, -5, 4, -6, 9, 0, 13]

Comparing the first and last positions, the result has 11<13, which matches 7<12 in the pattern.
Input: Two equal-length non-empty lists of integers. Each list will have no repeats. It's up to you whether the source or pattern is given first.
Output: A list that rearranges the source numbers to have the same relative ordering as the pattern numbers.
Leaderboard:

var QUESTION_ID=62587,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/62587/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Must it be a function/program, or is an expression/snippet enough?

@NBZ Unless the challenge overrides it, the default is that only function and programs are allowed. Unnamed functions are allowed though.

CJam, 12 10 bytes
{_$f#\$f=}

This is an anonymous function, which takes s p on the stack and leaves the result on the stack. Online demo
With thanks to Martin Büttner for 2 bytes.
Dissection
{         e# Define an anonymous function
  _$f#    e# Use a copy of the pattern to map each element to its sort index
  \$      e# Sort the source
  f=      e# Map each sort index to the corresponding source element
}

{_$@$er} is two bytes shorter.

@Dennis, that's different enough to be a separate answer

If you think so, I'll post it as an answer.

J, 9 bytes
/:^:2~/:~

This is a dyadic verb that takes p and s as left and right arguments. Try it online with J.js.
Test run
   7 _4 1 _8 4 _3 12 (/:^:2~/:~) _5 9 4 13 11 _6 0
11 _5 4 _6 9 0 13

How this works
Say we defined assigned the left and right input from the example via
p =: 7 _4 1 _8 4 _3 12
s =: _5 9 4 13 11 _6 0

Then:

The train /:^:2~/:~ is a hook of the verbs /:^:2~ and /:~, so calling
p (/:^:2~/:~) s

executes
p /:^:2~ /:~ s

The adverb ~ in /:~ is reflexive, since /: is used monadically. Thus, calling
/:~ s

executes
s /: s

The adverb ~ in /:^:2~ is passive, since the verb /:^:2 is used dyadically. Thus, calling
p /:^:2~ y

executes
y /:^:2 p

The adverb ^: is power. Thus, calling
y /:^:2 p

executes
y /: y /: p

Putting it all together, calling
p (/:^:2~/:~) s

executes
(s /: s) /: (s /: s) /: p

How that works
Dyadic /: is grade up using, i.e., x /:y returns the elements of x, sorted according to the corresponding values of y.

s /: s simply sorts the elements of s.
(s /: s) /: p sorts the (sorted) elements of s according to the corresponding values of p.
Grading up twice essentially computes the ordinals of its right argument.
Thus, (s /: s) /: (s /: s) /: p sorts the (sorted) elements of s, imitating the order of the elements of p.

Mathematica, 32 27 bytes
Sort@#~Permute~Ordering@#2&

Example usage:
Sort@#~Permute~Ordering@#2 &[{-5, 9, 4, 13, 11, -6, 0}, {7, -4, 1, -8, 4, -3, 12}]
(* {11, -5, 4, -6, 9, 0, 13} *)

Previous attempt:
Sort[#][[Ordering@Ordering@#2]]&

@DavidCarraher Fixed!

+1   I discovered this very same solution 4 minutes after you!  You can save a couple of bytes: o = Ordering; (Sort@#)[[o@o@#2]] &

Lovely new solution via Permute! Very useful use of permutations.

J, 17 bytes
(A.^:_1/:~)~A.@/:

This evaluates to a dyadic (meaning binary) verb. It can be evoked as follows:
  _5 9 4 13 11 _6 0 ((A.^:_1/:~)~A.@/:) 7 _4 1 _8 4 _3 12
11 _5 4 _6 9 0 13

Explanation
This may not be the shortest possible J solution, but it's a novel approach.
                   Left input is x, right input is y.
            A.@/:  The index of the permutation P that sorts y. /: gives the
                   permutation itself, and A. gives its index in the sorted
                   list of all its permutations.
       /:~         x sorted in ascending order. We are applying the x-sorting
                   permutation to x itself.
(A.^:_1   )~       The inverse of the permutation P applied to the sorted
                   version of x. Since P maps y to its sorted version, its
                   inverse maps the sorted version to y, and thus sorted x to
                   the correct output.

Pyth, 10 bytes
@LSvzxLSQQ

Try it online: Demonstration
Explanation
@LSvzxLSQQ implicit: z = first input line as string
                     Q = second input line evaluated
       SQ  sorted(Q)
     xLSQQ find the index for each element of Q in sorted(Q)
  Svz      sorted(evaluated z)
@LSvz      take the element in ^ for each index

XQSQSvz is three bytes shorter.

@Dennis Dang. Why didn't I thougth of this? Do you want to post it?

If you consider it sufficiently different from your approach, sure.

Pyth, 7 bytes
XQSQSvz

This is a full program that expects string representations of s and p on two lines. Try it online.
How it works
           Store the first line of input (rep. of s) in z.
           Evaluate the second line of input and store the result (p) in Q.
  SQ       Sort the elements of p.
    Svz    Evaluate the repr. of s and sort its elements.
XQ         Perform transliteration on p.
           This replaces the lowest element of p with the lowest element of s, etc.

Mathematica 56 43 30    29 bytes
o=Ordering;Sort[#][[o@o@#2]]&

Ordering@#2 returns the order of numbers in the pattern.
Ordering@Ordering@#2 gives the positions that the sorted elements in the source should occupy.
Sort[#][[o@o@#2]]& returns the source in the required positions, namely, those that have the same relative ordering as the pattern list.
Testing
o=Ordering;Sort[#][[o@o@#2]]&[{-5, 9, 4, 13, 11, -6, 0}, {7, -4, 1, -8, 4, -3, 12}]

{11, -5, 4, -6, 9, 0, 13}

Python 2, 51
lambda s,p,a=sorted:[a(s)[a(p).index(x)]for x in p]

I'm confused: why are there three parameters?

@PeterTaylor The third parameter has a default value, so it can be called with only 2.

@PeterTaylor Adding a separate line a=sorted would have the same effect.

Aaaaaah! I was misparsing, and thought that the body began at the =.

CJam, 8 bytes
{_$@$er}

This is an anonymous functions that expects s and p (topmost) on the stack and pushes the reordered s in return. Try it online in the CJam interpreter.
How it works
_      e# Push a copy of p.
 $     e# Sort it.
  @    e# Rotate s on top of p and the sorted p.
   $   e# Sort s.
    er e# Perform transliteration.
       e# This replaces the lowest element of p with the lowest element of s, etc.

J, 13 bytes
/:@/:@[{/:~@]

I'm still having trouble wrapping my head around J's verb composition, so I feel like some of those @ and [] might be unnecessary. If some more experienced J user could let me know if this can be compressed, that would be great. :)
The verb can be used as follows:
   7 _4 1 _8 4 _3 12 (/:@/:@[{/:~@]) _5 9 4 13 11 _6 0
11 _5 4 _6 9 0 13

Explanation
/:@/:@[{/:~@] NB. Left input is the pattern, right input is the source.
        /:~@] NB. Sort the source.
/:@/:@[       NB. Compute the ordering of the ordering of the pattern.
       {      NB. Use those as indices into the sorted source.

You can use dyadic /: to get rid of { and a @, for 11 bytes: /:~@]/:/:@[

@Dennis Thanks, Zgarb has found another 11-byte solution in the meantime which only needs two /:, but I haven't got round to updating the answer yet (({~/:)&/:{[).

Python 2, 48
lambda*l:map(dict(zip(*map(sorted,l))).get,l[0])

A big glob of functions. This uses the element translation approach of many other answers using a dictionary.
The starred input *l expects the patterns and source in that order, and turns them into a list l.
Mapping sorted sorts both lists, and dict(zip(_)) turns a pair of lists into a dictionary with keys from the first list matched with values in the second, in ascending order. So, the result is that that i-th largest element of the pattern is matched with the i-th largest element of the source.
Finally, we transform the pattern (l[0]) via this dictionary by mapping its .get method.

Bash + coreutils, 55
nl $2|sort -nk2|paste <(sort -n $1) -|sort -nk2|cut -f1

Input is taken as two filenames, for the source and pattern respectively:
$ ./imitord.sh source.txt pattern.txt
11
-5
4
-6
9
0
13
$

R, 38 bytes
function(s,p)sort(s)[match(p,sort(p))]

This is a nice approach. Wouldn't have thought to use match.

Ruby, 51 bytes
->s,p{s.map{|x|s.sort[p.sort.index(p[s.index x])]}}

APL, 17 12 bytes
{⍺[⍋⍺][⍋⍋⍵]}

Thanks to @Dennis, this is now very elegant.
Here's a nice 14-byte solution that doesn't use double indexing:
{⍺[(⍋⍋⍺)⍳⍋⍋⍵]}

Unfortunately, we can't index arrays from within trains in APL.

TeaScript, 15 bytes
ys¡m™x[yi(l)])

This takes input as an array. The interpreter is currently down because I'm putting up the fancy new interpreter
Explanation
y      // Second input
 s¡    // Sort it = s()
m™     // Map over it = m(#
  x[      // Num in first input at index...
    yi(l) // Current char's index in y
  ]
)

Either I'm badly misunderstanding the explanation, or this doesn't work... I coded it up in Pip according to what I think it does, and got 13 9 -6 4 11 -5 0 for the sample input. ??

Haskell, 65 bytes
import Data.List
s#p=[sort s!!i|b<-p,(i,e)<-zip[0..]$sort p,b==e]

Usage example: [-5,9,4,13,11,-6,0] # [7,-4,1,-8,4,-3,12] -> [11,-5,4,-6,9,0,13].
How it works:
           b<-p                              -- for every b in p
               ,(i,e)<-zip[0..]$sort p       -- walk through the sorted list of p
                                             -- paired with it's index ->
                                             -- (index,element) or (i,e)
                                      ,b==e  -- for those cases where b equals e
 sort s!!i                                   -- take the i-th element from the
                                             -- sorted list s

R, 37 bytes
function(s,p,o=order)s[o(s)][o(o(p))]

Jelly, 6 bytes, language postdates challenge
Œ¿œ?Ṣ}

Try it online!
This takes the pattern, followed by the source, as two separate arguments.
Explanation
Œ¿œ?Ṣ}
Œ¿      Generate an integer that describes the order of {the first input}
  œ?    Use that integer to reorder
    Ṣ}  the sorted version of the second {input}

Haskell, 56 bytes
import Data.List
p%s=[sort s!!(length$filter(<x)p)|x<-p]

Defines a binary function %. Each entry in p is transformed to the entry of s with the same order statistic, i.e. relative rank in its list. The order statistic of x in p is found by counting the elements smaller than it (sort p!!x produces an annoying Maybe). The result is indexed into sort s.
A zip/lookup solution is the same length, except it gives Just numbers.
import Data.List
p%s=[lookup x$zip(sort p)(sort s)|x<-p]


text:
A flat guessing game
There is a game I like to play. It happens on a grid of finite size (but it's wrapped, like a sphere). On that grid, a random (integer-only) point is selected. Then, I, the user, am prompted for a coordinate input. If my input matches the random point exactly, I am told that I have won. Otherwise, I am told the point-wise distance between my input and the random point. For example, if I guessed (2,2) and the random point was at (4,3), then the distance would be sqrt[(3-2)^2 + (4-2)^2] = sqrt[5].
The game continues until the player arrives at the correct location of the point.

Objective Create a functional version of the game described above. You must create a full program to do so. Here's what your program should do:

Request two inputs: the height and the width of the board. The origin is at the top-left of the board. These inputs will not exceed 1024.
Select a random point on that board; this will be the point to be guessed.
Accept input simulating a turn. The input will be either a space-separated pair of integers or two separate integer inputs. In response to this input, the program will do one of two things: If the input matches the random point selected, output a message signalling the user's victory. I would suggest "You won!".Otherwise, output the distance between the user's input point and the random point. In either case, you must increment the turn counter.
Once the user has achieved victory, display the number of turns the user took. The program then exits.

Bonuses
Bonuses are applied in the order that they appear in this list

-150 bytes if your program takes an input integer D that describes the dimension in which the game takes place. E.g., if D = 3, then you create a random point of 3 integers, take 3 integer inputs, and output the distance between those points.
-50% (or +50% if score < 0)if you provide a graphical representation of the board (ASCII or Picture) that shows where the user has previously guessed on the grid of given dimensions and the turn counter. (If you go for the first bonus, then this bonus only applies to the 2D and 1D modes. If you add a 3D graphical output, you get an additional -50%.)
-60 bytes if you can provide a gamemode (selected by an input in the beginning; that is, when given 0, perform the regular gamemode; when given 1, perform this gamemode) in which the point moves 1 unit in a random orthogonal direction per turn

More on wrapping
Wrapping occurs only when, in the third bonus, the moving point moves across any of the boundaries; in this case, the moving point is warped to the respective point, like so:
...              ...
..R (move right) R..
...              ...

This wrapping behaviour does not effect the user's guess, asides from the fact that point has changed direction.

Leaderboard
The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

<link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

LanguageUserScore

Leaderboard

AuthorLanguageSize

{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link

{{LANGUAGE}}{{NAME}}{{SIZE}}Link

Can we assume the user's guess will be within the bounds of the board?

@Mego Yes, you can.

In the multi-dimensional case, can we assume that the program takes any number of integer inputs, e.g. 3 3 2 5. In that case, D=4 and the size of the grid is 3x3x2x5?

@flodel yes, that's a good idea. Feel free

So D does not need to be explicitly input; it can be deduced from the board dimensions?

@Mego Yes it can

Minor nitpick: you probably mean it wraps like a torus not a sphere. It's impossible to wrap a 2D grid onto a sphere without creating discontinuities.

Also if the board wraps then there might be a shorter path between guess and target by crossing an edge.

May we use index origin 0 so top left is (0,0)?

@NBZ Yes, you can.

For the 3rd bonus, is it only one step in ONE dimension, or is it 0 or 1 step  in each dimension? Or are both possibilities ok?

@NBZ 1 unit it a single direction.

Also, you suggest a message, but are we allowed any message? In that case, a shorter message scores better. How about a single number (the number of turns used) indicating a win?

@NBZ Any message will do. ;)

I'm still not sure what the topology is. To help clear things up, if the board is 10x10, the random point is (9,4), and I guess (2,2), is the distance sqrt(13) or sqrt(53)? (Note for future: if you're doing anything weird, don't include randomness because it makes it almost impossible to supply test cases). 2. In the third bonus, should the distance be computed and output before or after the point moves?

CJam, -113 -139 -152 -157 -159 bytes
l~]:B:mr{_ea:i~mr0a*W2mr#+*.+B:,.=_[l~].-:mh_p}g],(

The program is 51 bytes long and qualifies for the -150 bytes and -60 bytes bonuses.
The game mode and number of dimensions are read as a command-line argument, the size in each dimension from STDIN. Since the victory message is arbitrary, the program will print 0.0 (distance to goal) to indicate that the game is over.
Test runs
$ cjam game.cjam 0 3; echo
2 2 2
1 1 1
1.4142135623730951
1 1 0
1.7320508075688774
1 0 1
1.0
0 0 1
0.0
4
$ cjam game.cjam 1 3; echo
2 2 2
0 0 0
1.0
0 0 0
0.0
2

How it works
l~]       e# Read a line from STDIN, evaluate it and collect the result.
:B        e# Save the resulting array in B. The result is [B1 ... Bd],
          e# where Bk is the board size in dimension k.
:mr       e# Pseudo-randomly select a non-negative integer below Bk,
          e# for each k between 1 and d.
{         e# Do:
  _       e#   Copy the item on the stack. The original becomes a dummy value
          e#   that will be used to count the number of turns.
  ea      e#   Push the array of command-line arguments.
  :i~     e#   Cast each to integer and dump them on the stack.
          e#   This pushes m (game mode) and d (number of dimensions).
  mr      e#   Pseudo-randomly select a non-negative integer below d.
  0a*     e#   Push an array of that many zeroes.
  W2mr#   e#   Elevate -1 to 0 or 1 (selected pseudo-randomly).
  +       e#   Append the result (1 or -1) to the array of zeroes.
  *       e#   Repeat the array m times.
  .+      e#   Perform vectorized addition to move the point.
  B:,.=   e#   Take the k-th coordinate modulo Bk.
  _[l~]   e#   Push a copy and an evaluated line from STDIN.
  .-:mh   e#   Compute their Euclidean distance.
  _p      e#   Print a copy.
}g        e# While the distance is non-zero, repeat the loop.
],(       e# Get the size of the stack and subtract 1.
          e# This pushes the number of turns.

And Dennis has outgolfed everybody. Again.

You accidentally updated the score to 152 instead of -152, putting you last on the leaderboard

Pyth, 91 (-150 -60) = -119
VvwaYOvw;JY#IqQ1=dOlY XYd@S[0 @Jd +@Yd?O2_1 1)1)=T[)VYaT^-Nvw2)=ZhZ=b@sT2Iqb0Bb;p"Won in "Z

Old solution: (54-150=-96)
JYVQaYOvw;#=J[)VYaJ^-Nvw2)=ZhZ=b@sJ2Iqb0Bb;p"Won in "Z

All input takes place on a new line.

First integer represents the game mode (either 1 or 0)
First Second integer D represents the dimensions of play.
Next D inputs represent the field size
Every D inputs from this point on are guesses

Sample play (hints do not appear in the actual program):
  #Hint: Gamemode (1 or 0)
1
  #Hint: Dimensions
3
  #Hint: X-size
4
  #Hint: Y-size
4
  #Hint: Z-size
4
  #Hint: Guesses
  #Hint:[3, 2, 1]
3
2
2
1.0
  #Hint:[3, 2, 1]
3
2
1
1.0
  #Hint:[2, 2, 1]
2
2
1
1.0
  #Hint:[3, 2, 1]
3
2
1
Won in 4

Shouldn't the second move win?

@JNF the point can move in gamemode 1 (-60 bytes bonus)

Holy moly, that is some long pyth code. Not really golfed though. For instance I see two spaces, that can be removed. Also: You can use J=YmOvwvw instead of VvwaYOvw;JY, which is 2 bytes shorter. I haven't looked over the other code, but I guess you can also shorten a few things there.

@Jakube,I was assuming the hint tells us where the point currently is

Python 2, 210 - 150 = 60
from random import*
q,r,o=map,raw_input,int
a=q(randrange,q(o,r().split(' ')))
m=q(o,r().split(' '))
t=1
while m!=a:print sum([(c-d)**2for c,d in zip(m,a)])**.5;m=q(o,r().split(' '));t+=1
print'You won in %d'%t

First challenge only so far. Try it online

Pip, 43 42 bytes - 150 = -108
Takes the board dimensions as command-line arguments (with D implied from the number of args). Takes guesses as space-separated numbers on stdin.
YRR_MgWd:++i&RT$+(y-(q^s))**2Pd"Won in ".i

This code takes heavy advantage of Pip's array-programming features. The array of cmdline args is stored in g. We generate the point to be guessed by mapping the randrange operator RR over g, and yank the resulting list into the y variable. Then comes the main while loop, where the condition is as follows:
d:++i&RT$+(y-(q^s))**2

  ++i&                  Increment i, the guess counter; the result is always > 0, so the
                          short-circuiting & operator evaluates the next expression:
              q         Read a line from stdin
               ^s       Split on spaces
           y-(   )      Subtract from our chosen point itemwise
          (       )**2  Square, itemwise
        $+              Fold on +, summing the list of squares
      RT                Square root
d:                      Assign this distance to d

If the distance was nonzero, the inside of the loop prints it. If it was zero, we've hit the target point; the loop halts, and the program outputs the win message and number of turns.
Example run:
C:\Users\dlosc> pip.py -f guessing.pip 10 5 6 4
5 2 3 2
3.1622776601683795
6 2 3 2
4.123105625617661
3 2 3 2
1.4142135623730951
3 1 3 2
2.23606797749979
3 2 2 2
1.7320508075688772
2 2 3 2
1
2 2 3 1
1.4142135623730951
2 3 3 2
Won in 8

R, 134 - 150 = -16 bytes
function(...){G=sapply(list(...),sample,1)
C=0
repeat{g=scan()
C=C+1
if(any(G!=g))cat(sqrt(sum((G-g)^2)))else{cat("Won in",C);break}}}

Haskell, 240 - 150 = 90
import System.Random
r x=randomRIO(0,x-1)
m=map read.words
g=getLine
main=do g;(fmap m g::IO[Int])>>=mapM r>>=b 1
b c v=do i<-fmap(sqrt.fromIntegral.sum.map(^2).zipWith(-)v.m)g;if i==0 then putStrLn$"Won in "++show c else do print i;b(c+1)v

Dyalog APL, 77 71 - 210 = -139
S F M
P←?S
{P←S|P+(?D)⌽D↑M×¯1 1[?2]
C+←1
P≢G←⎕:0⊣⎕←.5*⍨+/2*⍨P-G
C}⍣≢C←0

Ok:
Note that this runs in index origin 0 (⎕IO←0) which is default in many APLs.
Takes boolean mode as right argument (M), and dimension sizes as left argument (S).
Number of dimensions is D, which must be set (e.g. D←3) before calling, as per OP).
P←?S goal gets random point in range 1 though each of the dimension bounds
{ … }⍣≢C←0 repeat the function until the result is different from C, which initially gets 0
?2 random number 0 or 1
¯1 1[ … ] index from list of two numbers
M× multiply by mode; makes 0 if mode is 0
D↑ pad with 0s to match number of dimensions
(?D)⌽ rotate list randomly (0 through number of dimensions-1)
P+ adjust current goal
S| world-size modulus
P← save new goal point
C+←1 increment counter
P≢G←⎕: input guess, and if it is different from goal point then...
P-G distances in each dimension
2*⍨ squared
+/ sum them
.5*⍨ square-root
⎕← print that
0⊣ return 0 (i.e identical to initial value, so repeat)
C ... else, return the number of guesses (which, being different from 0, stops the looping and returns the last value)

@Dennis Actually, I broke it when I made it a function, so now it is a program again. I saved as many bytes as "programmity" cost me by switching to index origin 0, which OP allows.

OK. Out of curiosity: Which dialect is this? I have no idea what the first line is suppose to do...

@Dennis Dyalog. This is a traditional function, the first line is line [0], i.e. the function header, but it looks unusual because it has left-arg fn-name right-arg, but no result.