text:
Code Johnny Code, Code!
Rock-and-roll founding father Chuck Berry sadly passed away today.
Consider the chorus of his famous song "Johnny B. Goode":
Go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Johnny B. Goode

(There are other ways it has been punctuated but the above will serve for the purposes of the challenge.)
Challenge
Given a nonempty, lowercase string of letters a-z, output the chorus of "Johnny B. Goode" with all the instances of Go or go replaced with the input string, capitalized in the same way.
A trailing newline may optionally follow. Nothing else in the chorus should change.

For example, if the input is code the output must be exactly
Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

optionally followed by a newline.

Note that the capitalization of all words matches the original chorus, and (despite lack of rhythm) the Go in Goode is replaced as well as the individual words Go and go.
The shortest code in bytes wins.
Test Cases
"input"
output

"go"
Go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Johnny B. Goode

"code"
Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

"a"
A, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
Johnny B. Aode

"johnny"
Johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny B. Johnnyode

"fantastic"
Fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Johnny B. Fantasticode

Missed opportunities for test cases: an, c, cath

Somebody please do a Go version.

How should the program handle multi-word strings?

Let's just observe a minute or two of silence, and wish Rest In Peace to Chuck.

@SparklePony The input only contains letters so it will only be one "word" as far as the program knows.

What about coding the card game? https://boardgamegeek.com/thread/1156670/rules-explanation-rather-simple-go-johnny-go-go-go

The code text sounds best when spoken by Google Translator in Spanish: https://translate.google.com/#es/en/Code%2C%20code%0ACode%20Johnny%20code%2C%20code%0ACode%20Johnny%20code%2C%20code%0ACode%20Johnny%20code%2C%20code%0ACode%20Johnny%20code%2C%20code%0AJohnny%20B.%20Codeode

Simple method, Original poem with [tag:kolmogorov-complexity] skills, then swap Go with input

Go, 123 bytes
Go Johnny, Go!
Try it online!
import."strings"
func(s string)string{t,e:=Title(s),", "+s+"\n";return t+e+Repeat(t+" Johnny "+s+e,4)+"Johnny B. "+t+"ode"}

The only thing missing is 90 bytes.

VIM, 54 49 Keystrokes (saved 1 keystroke from Kritixi Lithos)
yw~hC<Ctrl-R>", <Ctrl-R>0<Enter>Johnny B. <Ctrl-R>"ode<Esc>}O<Ctrl-R>", Johnny <Ctrl-R>0, <Ctrl-R>0<Esc>3.

Start with the word on a line on a file with the cursor at the first character, then this will replace it all with the text
Explanation

Copy the word into a register, then change the first letter to be capitalized and save that to a register.
Write the first line using the registers to fill in the replacements and last lines
Write the second line using the registers to fill in the replacements
Repeat the middle line 3 times

Try it online! (Thanks DJMcMayhem!)

I think you can do Y instead of yy and maybe even G instead of 2j

And you can do <CR> instead of <esc>o

Also hD works instead of diw

Thanks for the tips! I was able to work in your last one into the current version. I also saved a few more by writing the first and last line in one go, then filling in the middle.

Try it online!

Typo: <Esc}0 should be <Esc>}  It's correct in the TIO link.

05AB1E, 37 bytes
™„, ¹J¹Ð™”ÿºÇ ÿ, ÿ”4.D¹™”ºÇ B. ÿode”»

Try it online!
Explanation
™„, ¹J                                # concatenate title-cased input with ", " and input
     ¹Ð™                              # push input, input, title-cased input
        ”ÿºÇ ÿ, ÿ”                    # push the string "ÿ Johnny ÿ, ÿ" with "ÿ" replaced
                                      # by title-cased input, input, input
                  4.D                 # push 3 copies of that string
                     ¹™               # push title-cased input
                       ”ºÇ B. ÿode”   # push the string "Johnny B. ÿode" with "ÿ" replaced
                                      # by title-case input
                                   »  # join the strings by newlines

Pure Bash, 69 76 bytes
M=aaaa;echo -e ${1^}, $1 ${M//a/\\n${1^} Johnny $1, $1}\\nJohnny B. ${1^}ode

Try it online!

In your try-it-online, it doesn't do the required capitalisation. For example if you feed in code all lower case, you don't get the required capitalisation.

@TomCarpenter Fixed! :)

JavaScript, 98
s=>[S=s[0].toUpperCase()+s.slice(1),[,,,].fill(` ${s}
${S} Johnny `+s)]+`, ${s}
Johnny B. ${S}ode`

Abuses array-to-string serialization to create commas. Builds an array of the form:
["Go",
 " go\nGo Johnny go", (repeated...)]

And concatenates it to the string of the form ", go\nJohnny B. Goode":
["Go",
 " go\nGo Johnny go",
 " go\nGo Johnny go",
 " go\nGo Johnny go",
 " go\nGo Johnny go"] + ", go\nJohnny B. Goode"

V, 41, 38 bytes
ÄJé,Ùäwa johnny 5ÄGdwwcWB.W~Aode.Î~

Try it online!
The perfect challenge for V!
Explanation:
ä$                              " Duplicate the input ('go' --> 'gogo', and cursor is on the first 'o')
  a, <esc>                      " Append ', '
                                " Now the buffer holds 'go, go'
          Ù                     " Duplicate this line
           äw                   " Duplicate this word (Buffer: 'gogo, go')
             a Johnny <esc>     " Append ' Johnny ' (Buffer: 'go Johnny go, go')
                           5Ä   " Make 5 copies of this line
G                               " Go to the very last line in the buffer
 dw                             " Delete a word
   w                            " Move forward one word (past 'Johnny')
    cW                          " Change this WORD (including the comma), to
      B.<esc>                   "   'B.'
             W                  " Move forward a WORD
              ~                 " Toggle the case of the character under the cursor
               Aode.<esc>       " Apppend 'ode.'
                         ÎvU    " Capitalize the first letter of each line

Explanation please?

@ckjbgames Done!

Batch, 207 bytes
@set s= %1
@for %%l in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do @call set s=%%s: %%l=%%l%%
@set j="%s% Johnny %1, %1"
@for %%l in ("%s%, %1" %j% %j% %j% %j% "Johnny B. %s%ode")do @echo %%~l

JavaScript (ES6), 104 101 99 bytes
(i,u=i[0].toUpperCase()+i.slice(1),x=`, ${i}
${u} Johnny `+i)=>u+x+x+x+x+`, ${i}
Johnny B. ${u}ode`

Previous version:
(i,u=i[0].toUpperCase()+i.slice(1))=>u+`, ${i}
${u} Johnny ${i}`.repeat(4)+`, ${i}
Johnny B. ${u}ode`

How it works:

It's an anonymous function that takes the input as the parameter i
Defines a variable u as the input i with the first letter capitalized (Note that this assumes input is nonempty, which is OK)
Just directly construct the string to be returned from those two variables.
Repeating the string "go, \nGo Johnny go" four times instead of repeating "Go Johnny go, go" saves one byte.

Edit 1: Forgot to golf out the semicolon, haha!! Also miscounted the bytes, it was originally 102, not 104. Thanks apsillers.
Edit 2: Instead of .repeat(4), by putting that string in a variable x and doing x+x+x+x allows saving two bytes.

Test snippet

let f = (i,u=i[0].toUpperCase()+i.slice(1),x=`, ${i}
${u} Johnny `+i)=>u+x+x+x+x+`, ${i}
Johnny B. ${u}ode`;
<input id=I type="text" size=70 value="code"><button onclick="console.log(f(I.value))">Run</button>

By the way, I'm new here, I have a question: do the two newlines in my program count as bytes? If not, it's actually 102 bytes, but I think it probably counts... Right?

Yep, they each use a byte.

I only count 102 bytes here (using https://mothereff.in/byte-counter), and also there's no need to use a final semicolon, so it's really 101 bytes.

@apsillers You're right, I miscounted! And worse, haha I forgot to golf out the semicolon. Thanks.

Pyth - 52 bytes
j", "_ArBQ3V4s[H" Johnny "G", "G;%"Johnny B. %sode"H

Test Suite.

C, 156 151 bytes
i,a,b;B(char*s){a=*s++;printf("%c%s, %c%s\n",b=a-32,s,a,s);for(;++i%4;)printf("%c%s Johnny %c%s, %c%s\n",b,s,a,s,a,s);printf("Johnny B. %c%sode",b,s);}

This doesn't compile in gcc 4.4.7

@villapx I don't see why it wouldn't. It compiles fine on MinGW and works online too. Maybe some compiler flag is disabling implicit type or function declaration?

It generates some warnings, but when you add a main() that actually calls the function it works...

@moooeeeep Ok, that's what I was missing--I was under the understanding that this challenge required a complete program, but indeed, it doesn't explicitly say that in the OP.

Python 3, 88 bytes
lambda x:("{0}, {1}\n"+4*"{0} Johnny {1}, {1}\n"+"Johnny B. {0}ode").format(x.title(),x)

A simple format string, with positional arguments.

@EricDuminil I knew it was at the end of the line, but there was line wrap in the editor window... :-/

I'm counting 88 bytes

@FelipeNardiBatista: len("\n") is 1. I don't know how it should be counted for golf submissions.

@EricDuminil len("\n".__repr__()[1:-2]) is 2. I forgot the __repr__() when measuring the program's length.

It's not possible to replace "\n" with a literal newline in Python, right?

@EricDuminil Only if you wrap it with """ marks instead of " marks.

C#, 219 211 212 146 122 Bytes
Implemented multiple suggestions from comments with additional optimization
This is the Endresult:
a=>{string x=(char)(a[0]^32)+a.Remove(0,1),n=a+"\n",c=", ",r=n+x+" Johnny "+a+c;return x+c+r+r+r+r+n+$"Johnny B. {x}ode";}

Try it online!
Explantation:
a=>//Input parameter Explanation assumes "go" was passed
{
string x = (char)(a[0] ^ 32) + a.Remove(0, 1)// Input with first letter Uppercase "go"->"Go"
,
n = a + "\n",                               //"go" followed by newline
c = ", "                                    //Hard to believe: Comma followed by space
,
r = n + x + " Johnny " + a + c             //"go" follwed by newline followed by "Go Johnny go, "
;
return x + c + r + r + r + r + n + $"Johnny B. {x}ode"; };//return in the right order                              //Johnny B. Goode

Output for testcases:
Go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Go Johnny go, go
Johnny B. Goode

Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

A, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
A Johnny a, a
Johnny B. Aode

Johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny Johnny johnny, johnny
Johnny B. Johnnyode

Fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Fantastic Johnny fantastic, fantastic
Johnny B. Fantasticode

Edit: Thanks to weston for suggesting using a function

You don't need to provide a whole program, a function or better yet, lambda, will suffice.

+1 Thanks for the ^32. That's shorter than the &~32 I was using. Also, a port of my Java 7 answer seems to be shorter: string x(string a){string x=(char)(a[0]^32)+a.Remove(0,1),n=a+"\n",c=", ",r=n+x+" Johnny "+a+c;return x+c+r+r+r+r+n+"Johnny B. "+x+"ode";}} (139 bytes) Try it here.

Hope you don't mind, but I've stole from you an idea. :P For not being known as a bad guy, I'll leave here a tip: You could convert your method into a lambda expression ( string x(string a) -> (a)=>, -13 bytes ), only 1 byte behind me ;)

@auhmaan If you're compiling to a Func<string, string> you can just do a=> no need for the ().

Python, 94 bytes
lambda s:("|, #\n"+"| Johnny #, #\n"*4+"Johnny B. |ode").replace("|",s.title()).replace("#",s)

Retina, 65 bytes
Byte count assumes ISO 8859-1 encoding.
^
$',
:T01`l`L
:`,
 Johnny$',
:`$
¶$`
(\S+) (\S+ ).+$
$2B. $1ode

Try it online!

Jelly, 41 bytes
5“ Johnny “, “¶”ẋj¹Ḋṙ7ỴŒu1¦€Y“B. ”⁸Œt“ode

Try it online!

Java 8, 151 147 146 130 bytes
s->{String x=(char)(s.charAt(0)^32)+s.substring(1),n=s+"\n",r=n+x+" Johnny "+s+", ";return x+", "+r+r+r+r+n+"Johnny B. "+x+"ode";}

Explanation:
Try it here.
s->{                               // Method with String as both parameter and return-type
  String x=                        //  Temp String with:
           (char)(s.charAt(0)^32)  //   The first letter capitalized
    +s.substring(1),               //   + the rest of the String
         n=s+"\n",                 //  Temp String with input + new-line
         c=", ",                   //  Temp String with ", "
         r=n+x+" Johnny "+s+c;     //  Temp String with "input\nInput Johnny input, "
  return x+c+r+r+r+r+n+"Johnny B. "+x+"ode";
                                   //  Return output by putting together the temp Strings
}                                  // End of method

Nova, 105 bytes
a(String s)=>"#{s.capitalize()+", #s\n"+"#s.capitalize() Johnny #s, #s\n"*4}Johnny B. #s.capitalize()ode"

Because Nova (http://nova-lang.org) is extremely early beta (and buggy), there are some obvious handicaps that are in place here keeping it from using even less bytes.
For example, could have saved capitalized function call (which is called 3 times) in a local variable like this:
a(String s)=>"#{(let c=s.capitalize())+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode"

which would have taken the byte count down to 89 bytes. The reason this doesn't work now can be blamed on the argument evaluation order in the C language, because Nova is compiled to C. (The argument evaluation order will be fixed in a future update)
Even more, I could have introduced a "title" property in the String class (and I will after doing this lol) to reduce the count from the capitalization function call:
a(String s)=>"#{(let c=s.title)+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode"

and that would free up 7 bytes to a new total of 82 bytes.
Furthermore (and further off), once lambda variable type inference is added, this would be valid:
s=>"#{(let c=s.title)+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode"

The count could be brought down to 72 bytes.
By the way, this is my first code golf, so I probably have missed even more optimizations that could have been made. And this being a non-golf centric, general purpose language, I think it's pretty impressive.
The first 105 byte code works in the current Nova Beta v0.3.8 build available on http://nova-lang.org
class Test {
    static a(String s)=>"#{s.capitalize()+", #s\n"+"#s.capitalize() Johnny #s, #s\n"*4}Johnny B. #s.capitalize()ode"

    public static main(String[] args) {
        Console.log(a("expl"))
    }
}

outputs:
Expl, expl
Expl Johnny expl, expl
Expl Johnny expl, expl
Expl Johnny expl, expl
Expl Johnny expl, expl
Johnny B. Explode

Thank you for listening to my shameless advertisement for the general purpose language Nova (found at http://nova-lang.org ...get it now!!)

Brainfuck, 352 bytes
,[>+>+<<-]++++++++[>----<-]>.>>>,[.>,]++++++[>+++++++>+++++>++<<<-]>++.>++.>--<<<<[<]<.>>[.>]>>>.>++++++++[>+++++++++>+++++++<<-]>>[<<++>>-]<<[>>+>+>+>+>+<<<<<<-]>++>->-------->-->-->+++++++++>>++++[<<[<]<<<<<[<]<<.>>>[.>]>>.>>>[.>]<[<]<<.<<<[<]<.>>[.>]>.>.<<<[<]<.>>[.>]>>>.>>[>]>-]<<[<]>[.>]<[<]<<.>>>--------.<<<<++.>.<<<[<]<<.>>>[.>]>>>>>>.>----.+.

Try it online!

Get the input.
Save special characters for later.
Write the first part.
Save "Johnny" for later
Print "Go Johnny go, go" four times
Write The last part

I always like challenges in Brainfuck so it was fun. It can probably be golfed more but golfing Brainfuck is kind of long.

PHP, 86 Bytes
echo strtr("1, 0\n2222Johnny B. 1ode",[$l=$argn,$u=ucfirst($l),"$u Johnny $l, $l\n"]);

MATLAB/Octave, 133 111 bytes
@(a)regexprep(['1, 2' 10 repmat(['1 32, 2' 10],1,4) '3B. 1ode'],{'1','2','3'},{[a(1)-32 a(2:end)],a,'Johnny '})

It's a start. Can hopefully be reduced further.
Basically it's an anonymous function which takes a string input and then uses regex to create the required output.
@(a)                                                    %Anonymous Function
    regexprep(                                          %Regex Replace
        ['1, 2' 10                                      %First line is: Code, code
            repmat(['1 32, 2' 10],1,4)                  %Then four lines of: Code Johnny code, code
                               '3B. 1ode'],             %Final line: Johnny B. Codeode
         {'1','2','3'},                                 %1,2,3 are our replace strings in the lines above
         {[a(1)-32 a(2:end)],a,'Johnny '}               %We replace with '(I)nput', 'input' and 'Johnny ' respectively.
    )

An example:
@(a)regexprep(['1, 2' 10 repmat(['1 32, 2' 10],1,4) '3B. 1ode'],{'1','2','3'},{[a(1)-32 a(2:end)],a,'Johnny '});
ans('hi')
ans =

Hi, hi
Hi Johnny hi, hi
Hi Johnny hi, hi
Hi Johnny hi, hi
Hi Johnny hi, hi
Johnny B. Hiode

You can sort of Try it online!. The code doesn't quite work with Octave as all the upper case letters become ${upper($0)}, whereas in MATLAB this is converted to the actual upper case letter.
Given the input is guaranteed to only be a-z (lowercase alphabet), I can save 22 bytes by using a simple subtraction of 32 to convert the first letter in the string to capital, rather than using regex with the upper() function.
As a result, the code now works with Octave as well, so you can now Try it online!

Ruby, 89 88 86 79 bytes
My first golf submission :
->x{"^, *
#{"^ Johnny *, *
"*4}Johnny B. ^ode".gsub(?^,x.capitalize).gsub ?*,x}

Thanks a lot to @manatwork for his awesome comment : 7 bytes less!

Nice. The parenthesis around the proc parameter are not needed; you can use literal newline characters instead of character escape; single letter string literals can be written with the ? notation; the parenthesis around the last .gsub's parameters are not needed. http://pastebin.com/6C6np5Df

@manatwork: Wow, very impressive and nice of you. Thanks!

C#, 159 130 128 bytes

Golfed
i=>string.Format("{0},{1}????\n{2} B. {0}ode".Replace("?","\n{0} {2}{1},{1}"),(i[0]+"").ToUpper()+i.Substring(1)," "+i,"Johnny");

Ungolfed
i => string.Format( "{0},{1}????\n{2} B. {0}ode"
    .Replace( "?", "\n{0} {2}{1},{1}" ),

    ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ), // {0}
    " " + i,                                      // {1}
    "Johnny" );                                   // {2}

Ungolfed readable
i => string.Format( @"{0},{1}
    ????
    {2} B. {0}ode"

    // Replaces the '?' for the string format that contains the
    // repetition of "___ Johnny ___, ___".
    .Replace( "?", "\n{0} {2}{1},{1}" ),

    // {0} - Converts the first letter to upper,
    //       then joins to the rest of the string minus the first letter
    ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ),
    // {1} - The input padded with a space, to save some bytes
    " " + i,
    // {2} - The name used as parameter, to save some bytes
    "Johnny" );

Full code
using System;

namespace Namespace {
    class Program {
        static void Main( string[] args ) {
            Func<string, string> func = i =>
                string.Format( "{0},{1}????\n{2} B. {0}ode"
                    .Replace( "?", "\n{0} {2}{1},{1}" ),

                    ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ),
                    " " + i,
                    "Johnny" );

            int index = 1;

            // Cycle through the args, skipping the first ( it's the path to the .exe )

            while( index < args.Length ) {
                Console.WriteLine( func( args[index++] ) );
            }

            Console.ReadLine();
        }
    }
}

Releases

v1.2 - - 2 bytes - Swapped (i)=> for i=>, thanks to TheLetalCoder comment.
v1.1 - -29 bytes - Thanks to Sir Bitesalot last update, who remembered me I could edit the string before format.
v1.0 - 159 bytes - Initial solution.

Notes
The title has a link to a page with the code and the test cases. Just hit Go and the result will be printed below the code.

No need for the () around the argument for the Func just do i=>. You can probably also make use of interpolated strings from C# 6 and lose the string.Format although I haven't looked at the code too much to see how (should be trivial).

I can drop the (), but I doubt that I can make use of interpolated strings without boosting up the size of the code, due to the replace that happens to collapse the repetition.

Like I said I was being lazy and hand't actually tried anything myself! Was just a suggestion to look into.

Stacked, 64 bytes
:@n tc@N('%N, %n
'!'%N Johnny %n, %n
'!4*'Johnny B. 'N'ode'!)sum

Try it online!

Excel VBA, 137 121 112 89 87 84 Bytes
Anonymous VBE immediate window function that takes input of type Variant/String from cell [A1] and outputs by printing the the VBE immediate window
c=[Proper(A1)]:s=vbCr+c+[" Johnny "&A1&", "&A1]:?c", "[A1]s;s;s;s:?"Johnny B. "c"ode

-16 Bytes for converting to Immediate window function
-9 Bytes for using [PROPER(A1)]
-23 Bytes for dropping For ... loop and abusing the ? statement
-2 Bytes for replacing  " Johnny "&[A1]&", "&[A1] with [" Johnny "&A1&", "&A1]
-3 Bytes for using + over  & for String concatenation and leaving the terminal string unclosed
Example Case
[A1]="an"          ''  <- Setting [A1] (may be done manually)
                   '' (Below) Anonymous VBE function
c=[Proper(A1)]:s=vbCr+c+[" Johnny "&A1&", "&A1]:?c", "[A1]s;s;s;s:?"Johnny B. "c"ode"
 An, an            ''  <- output
 An Johnny an, an
 An Johnny an, an
 An Johnny an, an
 An Johnny an, an
 Johnny B. Anode

Is Debug.?s effectively Debug.Print? How does that work?

@BruceWayne, nice cape. VBA is supports autoformatting, which means that things like ?,i=1To and &c are digested into more verbose but readable terms like Print, i = 1 To and & c. The community has decided that the compressed version of code in languages is acceptable for responses (see https://codegolf.meta.stackexchange.com/questions/10258/how-to-count-bytes-in-languages-with-autoformatters/10259#10259 )

@BruceWayne As for ?, I believe it is a remnant from old version of Excel (4.0 and below) where Macro Sheets were used in place VBA via the VBE where it was used as a keyword for printing a string provided after it to a pre-indicated text file. The ? keyword itself is still very useful for code golfing as the Print keyword is used to write strings to a text file in current versions of VBA. Note, I am going off of memory with one so take that with a grain of salt.

Good to know! I just asked, not for CodeGolf purposes, but because I'm constantly learning VBA and this was super new to me, so I was curious.  Always like to learn neat little tricks in VBA. Cheers!

Javascript - 72 106 bytes
Edit: Oops!! I didn't pay attention to the capitalization rules! It'll be longer after a while
Edit 2: Should be following the rules now!
Could probably be golfed more
c=>(`G,g
`+`G Johnnyg,g
`.repeat(4)+`Johnny B.Gode`).replace(/g/g,' '+c.toLowerCase()).replace(/G/g,' '+c)

Used as:
c=>(`G,g
`+`G Johnnyg,g
`.repeat(4)+`Johnny B.Gode`).replace(/g/g,' '+c.toLowerCase()).replace(/G/g,' '+c)
alert(f("Code"));
alert(f("Go"));

Japt, 62 53 bytes
[1S]+U+R+`1 20, 0
`²²+`2B. 1o¸` d0U1Ug u +UÅ2"Johnny

Try it online!

62-byte solution using a substantially different technique:
Saved 3 bytes thanks to ETHproductions
W=Ug u +UÅ)+", {U}
"+`{W} Johnny {U}, {U}
`²²+`Johnny B. {W}o¸

Try it online!

Bash, 72 bytes
(modified version of R. Kapp's answer):
M=hnny;echo -e ${1^}, $1 ${M//?/\\n${1^} Jo$M $1, $1}\\nJo$M B. ${1^}ode

Try it online!

Mathematica, 83 bytes
{a=ToTitleCase@#,b=", ",#,{"
",a," Johnny ",#,b,#}~Table~4,"
Johnny B. ",a}<>"ode"&

Anonymous function. Takes a string as input and returns a string as output. Could probably be golfed further.

Swift, 151 144  bytes
import Foundation
func b(a:String){let u=a.capitalized;print(u+", "+a);for _ in 0..<4{print(u+" Johnny "+a+", "+a)};print("Johnny B. "+u+"ode")}

Previous Version:
import Foundation
func b(s:String){let u=s.capitalized;print("\(u), \(s)");for _ in 0..<4{print("\(u) Johnny \(s), \(s)")};print("Johnny B. \(u)ode");}

Ungolfed:
import Foundation
func beGoode(inputString: String) {
        let capitalizedString = inputString.capitalized
        print("\(capitalizedString), \(inputString)")
        for _ in 0..<4 {
            print("\(capitalizedString) Johnny \(inputString), \(inputString)")
        }
        print("Johnny B. \(capitalizedString)ode")
    }

Example:
b(s: "code")

Code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Code Johnny code, code
Johnny B. Codeode

Edit: Golfed down 6 bytes by using string concatenation instead of interpolation. Down 1 byte more by removing final semi-colon.

Welcome to the site!

Thanks! I thought I'd finally try my hand at a solution.

CJam, 50 bytes
r:L(eu\+:M',SLN[MS"Johnny ":OL',SLN]4*O"B. "M"ode"

Try it online!
Explanation:
r:L(eu\+:M',SLN[MS"Johnny ":OL',SLN]4*O"B. "M"ode" e# Accepts an input token.
r:L                                                e# Gets input token and stores it in L.
   (eu\+:M                                         e# Converts token to uppercase-first and stores it in M.
          ',S                                      e# Appears as ", ".
             L                                     e# Input token.
              N                                    e# Newline.
               [                                   e# Opens array.
                M                                  e# Modified token.
                 S                                 e# Space.
                  "Johnny ":O                      e# Pushes "Johnny " and stores it in O.
                             L                     e# Input token.
                              ',SLN                e# The same {',SLN} as before.
                                   ]4*             e# Closes array and repeats it 4 times.
                                      O            e# "Johnny ".
                                       "B. "       e# "B. ".
                                            M      e# Modified token.
                                             "ode" e# "ode".

Pyke, 43 bytes
l5j", "Qs3
Qld"Johnny "iQs3:D4i"B. ode"+Tj:

Try it online!
Constructs and prints the first line then inserts Johnny go before the comma and duplicates that 4 times. Finally constructs the last part.

Doesn't seem to work for input johnny. https://tio.run/nexus/pyke#@59jmqWko6AUWGzMZZSi5JWfkZdXqaCUCeRbuZhkKjnpKeSnpCpph2RZ/f@fBZYFAA

I have no idea how I didn't spot that, fixed now

Java 6, 258 242 bytes
enum j{;public static void main(String[]a){char[]b=a[0].toCharArray();b[0]^=32;System.out.printf("%1$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%3$sB. %1$sode",new String(b),a[0],"Johnny ");}}

Longest part of it is the format for printf. There are problems with input different than string from a to z(yes I know I don't need to support anything else).
Ungolfed with comments:
enum j {
    ;

    public static void main(String[] a) {
        char[] b = a[0].toCharArray();              // Copy of the input string
        b[0]^=32;                                   // First character of copy to uppercase
        System.out.printf(
                "%1$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%3$sB. %1$sode", // Format string
                new String(b),  // Capitalized string
                a[0],           // Original input string
                "Johnny ");     // "Johnny "
    }
}

EDIT: Golfed 16 bytes thanks to weston

You can use a lambda to save lots of bytes.

"Johnny" is always followed by a space.

b[0]^=32; will also uppercase without the need for (char) cast.

Kotlin, 112, 99 Bytes
fun g(s:String)=s.capitalize().let{"$it, $s\n${"$it Johnny $s, $s\n".repeat(4)}Johnny B. ${it}ode"}

Ungolfed:
fun g(s: String) = s
        .capitalize()
        .let {
            "$it, $s\n${"$it Johnny $s, $s\n".repeat(4)}Johnny B. ${it}ode"
        }

Python, 258 bytes
from jinja2 import Template
def f(go):
    t = Template("""{{ Go }}, {{ go }}
{{ Go }} Johnny {{ go }}, {{ go }}
{{ Go }} Johnny {{ go }}, {{ go }}
{{ Go }} Johnny {{ go }}, {{ go }}
{{ Go }} Johnny {{ go }}, {{ go }}
Johnny B. {{ Go }}ode""")
    return t.render(Go=go.title(), go=go)

Notice this is exactly on par with Java at this moment, and it is sooo much readable ;)

Welcome to the site! You could use string multiplication to shorten this answer.  In addition it is not necessary to declare the variable t because it is only called once.

Thanks, but I was aiming at exactly 258 bytes, to be on par with Java

Why are you trying to match another score? This is code golf, not a readability contest.

Is it even possible to have a readability contest? I mean, there is not an objective measure of readability, as far as I know.

@user7610 I think you're missing the point.

Guess what, Java's at 147 now.

This is not a language war. This is code golf.

Sure, I just placed my hole in a different way.

PHP, 84 83 bytes
Good Bye, Chuck!
<?=strtr(str_pad("1, 0",41,"
1 2 0, 0")."2 B. 1ode",[$argn,ucfirst($argn),Johnny]);

or
<?=strtr(str_pad("1,0",32,"
1 20,0")."2 B. 1ode",[" $argn",ucfirst($argn),Johnny]);

Run with echo '<input>' | php -nF <filename> or try them online.

Q, 97 bytes
{u:(upper x[0]),1_x;u,", ",x,"\n",((,/)4#enlist u," Johnny ",x,", ",x,"\n"),"Johnny B. ",u,"ode"}

Assuming input "go".

Defines uppercase input as variable u.
Merges u with input x to generate first line, "Go, go".
Copies body, "Go Johnny go, go", four times.
Merges with final line, "Johnny B. Goode".

Common Lisp, 107 bytes
(apply'format t"~:(~A~), ~a~%~4@{~:(~A~) Johnny ~a, ~a ~%~}Johnny G. ~:(~A~)ode"(fill(make-list 15)(read)))

Try it online!

Japt, 52 bytes
[V=UhUg u)',SUR[VSW="Johnny "U',SUR]¬²²W`B. {V}o¸`]¬

Try it

C (gcc), 110 bytes
n;f(char*s){for(n=6;n--;)printf(n?n^5?"%c%s Johnny %s, %s\n":"%c%s, %s\n":"Johnny B. %c%sode",*s-32,s+1,s,s);}

Try it online!

Excel, 103 bytes
-8 bytes saved by using # and ~ instead of Go and go
=SUBSTITUTE(SUBSTITUTE("#, ~
"&REPT("# Johnny ~, ~
",4)&"Johnny B. #ode","#",PROPER(A1)),"~",LOWER(A1))

SOGL V0.12, 38 bytes
,1Ƨ, Ο,@+"9:█ŗ‘⁽:A+⁴+:³a,⁽"B. ŗode”+⁰⁽

Try it Here!

Pyth, 69 67 bytes
.F++"{0}, {1}\n"*"{0} {2} {1}, {1}\n"4"{2} B. {0}ode"[rz4rz0"Johnny

Try it here!
Python 3 translation:
z=input()
print(("{0}, {1}\n"+"{0} {2} {1}, {1}\n"*4+"{2} B. {0}ode").format(z.capitalize(),z.lower(),"Johnny"))

Stax, 34 bytes
₧:hç╟╫9↓Σl(Ü°╤`╨+B╥¢└ÇI╩4╢YP-├Γ■fl

Run and debug it
Unpacked, ungolfed, and commnted, it looks like this.
:.X         title case input and store in x register        e.g. "Code"
., +        concat ", "                                     e.g. "Code, "
y+Q         concat input and print without popping          e.g. "Code, code"
x`?*u)U"`+  concat " Johnny " to x                          e.g. "Code, code" "Code Johnny "
sv+         swap top of stack, lowercase, concat            e.g. "Code Johnny code, code"
QQQQ        print 4 times without popping                   e.g. "Code Johnny code, code"
j1@p        split, print the second word without newline    e.g. "Johnny"
" B. `xode  output string template with x register embedded e.g. " B. Codeode"

Run this one

Jstx, 52 bytes
₧&Eu◄, :;4♦/u♂ Johnny♀:◄, :;► :;41u☼◘~ΘåÆëë╟┌°;♫☺åΘ:

Try it online!
Explanation
₧&          # Push literal 100
E           # Push the second stack value the absolute value of the first stack value times.
u           # Push the first stack value transformed to Title Case.
◄,          # Push literal ,
:           # Push the sum of the second and first stack values.
;           # Push the difference of the second and first stack values.
4           # Print the first stack value, then a newline.
♦           # Push literal 4
/           # Enter an iteration block over the first stack value.
u           # Push the first stack value transformed to Title Case.
♂ Johnny♀   # Push literal  Johnny
:           # Push the sum of the second and first stack values.
◄,          # Push literal ,
:           # Push the sum of the second and first stack values.
;           # Push the difference of the second and first stack values.
►           # Push literal
:           # Push the sum of the second and first stack values.
;           # Push the difference of the second and first stack values.
4           # Print the first stack value, then a newline.
1           # End an iteration block.
u           # Push the first stack value transformed to Title Case.
☼◘~ΘåÆëë╟┌° # Push literal Johnny B.
;           # Push the difference of the second and first stack values.
♫☺åΘ        # Push literal ode
:           # Push the sum of the second and first stack values.

Python 2, 156 bytes
#coding:UTF-8
import sys;a="þ, ÿ"+("\nþ Johnny ÿ, ÿ"*4)+"\nJohnny B. þode";print a.replace("þ",sys.argv[1].title()).replace("ÿ",sys.argv[1].lower())

De-golfed:
#coding:UTF-8
import sys
a = "þ, ÿ" + ("\nþ Johnny ÿ, ÿ" * 4) + "\nJohnny B. þode"
b = a.replace("þ", sys.argv[1].title())
c = b.replace("ÿ", sys.argv[1].lower())
print c

Works as long as input doesn't contain the character ÿ, but passes all test cases.
Bytes counted by this byte counter.

Welcome to the site!


text:
Keyboard Encryption
Challenge
Given a string with any characters a-z or A-Z, return an 'encrypted' string, where all characters are replaced by the character next to it (assuming a QWERTY keyboard).

Case (uppercase, lowercase) does not matter.
The input will only have characters a-z and A-Z.

Shortest code in bytes wins.

Example Input and Output
Foo Foo Bar Bar Python → Gpp Gpp Nst Nst [uyjpm
Case does not matter → vSDR fprd mpy ,sYYrT

Seems like a subset of this challenge.

Looks fairly nice to me. have a +1 :)

Well at least Jelly would be non-competing there

"The input will only have characters a-z and A-Z.": should this also say "and  "

Looks like it's more of a dupe of this

Jelly, 16 bytes
ŒlµØqż“[;,”Fṡ2Zy

Try it online!
How?
ŒlµØqż“[;,”Fṡ2Zy - Main link: string
Œl               - convert to lowercase
  µ              - monadic chain separation
   Øq            - qwerty yield: ["qwertyuiop","asdfghjkl","zxcvbnm"]
      “[;,”      - "[;,"
     ż           - zip: [["qwertyuiop","["],["asdfghjkl",";"],["zxcvbnm",","]
           F     - flatten: "qwertyuiop[asdfghjkl;zxcvbnm,"
            ṡ2   - overlapping pairs: ["qw","we","er","rt","ty","yu","ui","io","op","p[","[a","as","sd","df","fg","gh","hj","jk","kl","l;",";z","zx","xc","cv","vb","bn","nm","m,"]
              Z  - transpose: ["qwertyuiop[asdfghjkl;zxcvbnm","wertyuiop[asdfghjkl;zxcvbnm,"]
               y - translate the lowercased string with that mapping

Python 3, 91 bytes:
s='qwertyuiop[asdfghjkl;zxcvbnm,  '
print(''.join(s[s.index(c)+1]for c in input().lower()))

Can remove two bytes if there is no space in input...

source: Stack Exchange

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

sort: votes


text:
A, Buzz, C, D, E, Fizz, G
A simple FizzBuzz using strings.
Given

1 word or phrase (string)
2 unique characters

Output
The word or phrase with each occurrence of the first character replaced with fizz and each of the second character replaced with buzz
Rules

The first letter in both Fizz and Buzz must remain capitalized
For the rest of the words fizz and buzz, you must match the case of the replaced character (if no case then keep lowercase)
If given characters are not in the phrase, output the original phrase

Test Cases
Given: Hello, h, l
Output: FIZZeBuzzBuzzo

Given: test, a, b
Output: test

Given: PCG rocks!,  , !
PCGFizzrocksBuzz

Given: This
Is
SPARTA!,
, S
Output: ThiBuzzFizzIBuzzFizzBUZZPARTA!

Given: FizzBuzz, a, b
Output: FizzBUZZuzz

This is code-golf so the shortest code, in bytes, wins!
Note
Technically handling the newline case (This Is SPARTA!) is a part of the challenge. However, I will not void an answer for not including it, as it is very challenging or even impossible in some languages.

you must match the case of the replaced character and Input is not case sensitive seem to contradict each other.

@GregMartin ah thank you, i was trying to say that the 2 characters as input are case sensitive (ex. A means the same as a)

ThiBuzzFizzIBuzzFizzBUZZPARTA is missing a final exclamation mark.

Are we supposed to support inputs such as aa, a, f? What would be the expected output? BUZZizzBUZZizz, FizzFizz, or both allowed at our option?

@Amauld Based on the last test case, I'd say it should output FizzFizz.

@Arnauld FizzFizz

What characters can appear in the phrase? Any ASCII? Or just letters/typical punctuation?

Jelly, 34 bytes
Œl=€⁹Œl¤ȧ€"“¡Ṭ4“Ụp»o"/ȯ"Œu⁹Œln$T¤¦

Try it online!
How?
Œl=€⁹Œl¤ȧ€"“¡Ṭ4“Ụp»o"/ȯ"Œu⁹Œln$T¤¦ - Main link: characters, string
Œl                                 - lowercase the characters
       ¤                           - nilad followed by link(s) as a nilad:
    ⁹                              -     right argument, the string
     Œl                            -     lowercase
  =€                               - equals (vectorises) for €ach (a list of 2 lists that identify the indexes of the string matching the characters regardless of case)
           “¡Ṭ4“Ụp»                - dictionary strings ["Fizz", "Buzz"]
          "                        - zip with
        ȧ€                         -     logical and (non-vectorising) for €ach (replace the 1s with the words)
                     /             - reduce with:
                    "              -     zip with:
                   o               -         logical or (vectorises) (make one list of zeros and the words)
                                   - implicit right argument, string
                       "           - zip with:
                      ȯ            -     logical or (non-vectorising) (replace the zeros with the original characters from the string)
                                 ¦ - apply...
                        Œu         -     uppercase
                                   - ...to the indexes (the words at indexes):
                                ¤  -     nilad followed by link(s) as a nilad:
                          ⁹        -         right argument, the string
                              $    -         last two links as a monad (i.e. the string on both sides):
                           Œl      -             lowercase
                             n     -             not equals (vectorises)
                               T   -         truthy indexes (the indexes of the capital letters in the string)

+1, Thank you for using the newline case. That makes this the first entirely correct submission

Python 3, 180 174 168 160 152 bytes
from sys import*
J=''.join
L=str.lower
s,a,b=J(stdin).split(', ')
print(J('FBFBiuIUzzZZzzZZ'[L(k)==L(b)::2][k!=L(k)::2]*(L(k)in L(a+b))or k for k in s))

This is just a more golfed version of Stephen's answer, in Python 3. This chips away 42% of his bytes. Python 2 would save one byte on the print, but such is the price of progress. This handles newlines properly.
Thanks to Blckknight for saving 8 bytes on input.

What is the fileinput modules used for?

@ValyrioAccount, fileinput.input overrides the built-in input method. It enables inputs with newlines.

How about from sys import* and s,a,b=J(stdin).split(', ') to save a few characters?

Python, 109 bytes
lambda s,w:"".join([c,"Fizz","Buzz","BUZZ","FIZZ"][-~w.lower().find(c.lower())*-~(-2*c.isupper())]for c in s)

Try it online!

Takes the two characters as a single string
Edit:
Added testcase to TIO link, newline works too

GNU sed, 135 + 1(r flag) = 136 bytes
By default, a sed script is executed as many times as there are input lines. To handle multi-line input, I use a loop to append all possible remaining lines to the first, without starting a new cycle.
:r
$!N
$!br
s:, (.), (.):;\u\1FIZZ;\l\1Fizz;\u\2BUZZ;\l\2Buzz:
s:^:,:
:
s:,(.)(.*;\1)(...)(.):\3,\4\2\3\4:
s:,(.):\1,:
/,;.F/!t
s:,.*::

Try it online!
The replacement table used on line 4, needs to be in that exact order, i.e. 'Fizz' and 'Buzz' after their upper-case forms. This is because the sed regex .*, used during the table lookup, is greedy. If the current char needed to be replaced is not a letter (no case), then the lowercase string is needed (matched last).
Since sed has no data types, I use a character delimiter to iterate a string. It will mark my current position and in a loop I shift it from left to right. Fortunately, I can use , for this, since it is the input data delimiter.
Explanation:
:r                                                 # reading loop
$!N                                                # append next input line
$!br                                               # repeat till EOF
s:, (.), (.):;\u\1FIZZ;\l\1Fizz;\u\2BUZZ;\l\2Buzz: # create replacement table
s:^:,:                                             # append my string delimiter
:                                                  # main loop
s:,(.)(.*;\1)(...)(.):\3,\4\2\3\4:                 # apply char replacement, if any
s:,(.):\1,:                                        # shift delimiter to right
/,;.F/!t                                           # repeat till end of string
s:,.*::                                            # print only the final string

Bash 4.4 + GNU sed, 70 228 222 227 bytes
IFS=;alias e=echo;K=`sed $([[ $2 != '
' ]]&&e "s/${2,}/Fizz/g;s/${2^}/FIZZ/g"||:)$([[ $3 != '
' ]]&&e ";s/${3,}/Buzz/g;s/${3^}/BUZZ/g"||:)<<<"$1"`;[[ $2 = '
'||$3 = '
' ]]&&e ${K//$'\n'/`[[ $2 = '
' ]]&&e Fizz||e Buzz`}||e "$K"

Apparently alias e=echo throws an error if referenced in Bash 4.3 or below, the version TIO is apparently using. Therefore, the longer and equivalent Bash 4.3 code is given in the below TIO test suite for the sake of testing. This passes all of the test cases, so that is nice.
Try it online!

@thedarkwanderer Now it should. Sorry that it took a bit long to fix.

Python 2, 271, 261 bytes
import fileinput as f
a=''
for m in f.input():a+=m
a=a.split(', ')
l=L=list(a[0])
for i in range(0,len(a[0])):
 j,k=l[i].lower(),l[i].istitle()
 if j==a[1].lower():
  L[i]='FIZZ'if k else'Fizz'
 elif j==a[2].lower():
  L[i]='BUZZ'if k else'Buzz'
print''.join(L)

Try it online!
Wow this one was a doozie! It turns out python won't accept multi-line inputs so fileinput must be used.
edit: should pass all cases now :)

Definite +1 for handling the case with newlines! Not many are able to incorporate that

You could save 3 bytes by doing something like import fileinput as f ... for m in f.input():

@Caleb Thanks for the suggestion! it should pass all tests now

MATLAB/Octave, 106 102 111 bytes
@(a,b,c)regexprep(a,num2cell([lower([b c]) upper([b c]) '1234']),{'2','4','1','3','FIZZ','Fizz','BUZZ','Buzz'})

This could probably be optimised further.
It uses a simple Regex replacement. However an intermediate step is required by replacing the input characters with numbers first. This is so that if the second input replace letter was contained in Fizz that the Fizz doesn't then get replaced when the next regex is performed.
This of course assumes there are no numbers in the input. However given the question says the input is a word or phrase I feel that this is an acceptable assumption.
The code will handle new lines in the input correctly.
You can Try it online!

JavaScript (ES6), 92 bytes
Takes input as a string and an array of two characters. Supports newlines.
f=(s,[a,b],r='Fizz')=>a?f(s.replace(RegExp(a,'gi'),m=>m<'a'?r.toUpperCase():r),[b],'Buzz'):s

Test cases

f=(s,[a,b],r='Fizz')=>a?f(s.replace(RegExp(a,'gi'),m=>m<'a'?r.toUpperCase():r),[b],'Buzz'):s

console.log(f("Hello", ['h', 'l']))
console.log(f("test", ['a', 'b']))
console.log(f("PCG rocks!", [' ', '!']))
console.log(f(`This
Is
SPARTA!`, [`
`, 'S']))
console.log(f("FizzBuzz", ['a', 'b']))

Pyth - 25 bytes
sXzsrBQ1scL2rB"FizzBuzz"1

Test Suite.

A capital as one of the characters seems to cause problems - "Hl", Hello does not capitalise the output correctly and "hL", Hello does not substitute the ls.

Haskell, 114 bytes
u=Data.Char.toUpper
p[f,b]x|f==u x="Fizz"|b==u x="Buzz"|2>1=[x]
q x y|u y<y=x|2>1=u<$>x
r x=concatMap$q=<<p(u<$>x)

r takes the fizz and buzz characters as a 2 element list as the first argument, and the input string as the second argument. Newlines and unicode should be handled appropriately, although the function is unfortunately not total (allowing for invalid inputs saved 5 bytes).

u=Data.Char.toUpper only works in ghci as far as I know. In standard Haskell you need the import. However you should be able to save some bytes by using =<< instead of concatMap.

Mathematica, 94 bytes
a=ToLowerCase;b=ToUpperCase;StringReplace@{a@#->"Fizz",b@#->"FIZZ",a@#2->"Buzz",b@#2->"BUZZ"}&

Anonymous function. Takes two strings as input and returns a function which takes a string as input and returns a string as output as output. It must be called in the format prog["c1", "c2"]["s"], where "s" is the target string and "c1" and "c2" are the two characters. Could probably be golfed further.

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


text:
Run a game of Flood
This is a Code Golf challenge.
Flood is a game in which the player is presented with a game board such as this:

On each turn, you choose a colour (on the link above, by clicking a square containing that colour), and the cell in the top-left corner is filled with that colour - this colour will absorb all adjacent cells with the same colour. So, for example, the first turn might be Blue, which will cause the yellow cell in the top corner to turn blue, and merge with the existing blue cell. The next turn might be Purple, which will fill both of the first two cells purple, merging them with the two-cell purple area attached to them. Then you might go Red, then Orange. With this sequence, the board will end up as:

Your task is to write a code that simulates the game, taking in an array or other data format containing the current state of the game, in a suitable format (picture, numbers in a square array, string with numbers indicating the dimensions, anything that can be identified with the game), along with one or more input commands (colours, cells that contain colours, etc - your choice of how to implement the sequence, but you need to explain it).
If (and only if) the input solves the board (causes all cells to be the same colour), then your code should print a message in some format informing the player that the board is cleared or completed. It is up to you how this is done, but it must be clear to any English speaker using the code without requiring separate documentation (so outputting "1" isn't good enough). Note that displaying a completed board is not sufficient.
Some example options for completion output include win, done, complete, or clear. If your language doesn't have a nice way to output a longer message, I recommend using win.
Whether the input solves the board or not, the code should output (either as function output or as a displayed output) the final state of the board.
The code may take input of moves interactively (from STDIN, to simulate the actual game) or as a code input.
Scoring
Your goal is to minimise the number of bytes in the function or code.
Rules and Assumptions
Standard Loopholes are forbidden.
Code must be able to handle non-square boards, with each dimension being anywhere between 6 and 30 cells (more is fine, it must handle this range). It must be able to handle between 3 and 9 distinct colours or "colour" labels (numbers are fine).
You may assume that input is in simplest form - that is, if there are four colours, they will be labelled 1-4, or a-d, or any other similar system as appropriate. You will not need to handle situations such as incorrect inputs, unsimplified inputs (you won't have the numbers 1, 3, 6, and 9, without the others in between, unless it suits your code).
Your answer should include a description of formats, etc.
Request: If you believe you have identified a non-standard loophole, and it's definitely a loophole and not in the spirit of the question, please comment to have the loophole closed, rather than posting an answer using it. This is not a rule, per se, but an effort to keep the challenge interesting.

We must be able to handle non-square boards, but what about non-rectangular ones?

@orlp - no need to deal with non-rectangular boards.

Related. Related.

What the rule "so outputting "1" isn't good enough" can add to the challenge?

@rahnema1 - it opens things up to some creativity per language. If outputting a "truthy" value was all that was required, it would be a bit boring, and the point is for the code to simulate the game itself - you'd find it sad if you played a game, and on winning, the game just output "1". Meanwhile, it might be easier in one language to output "complete" because it's part of an inbuilt string, while another language might be better with "You win!"

Also I just I just noticed the part about the output message. "it must be clear to any English speaker using the code without requiring separate documentation" is clearly not objective and makes it possible to make answers comparable. Is yes good enough, is y? Is win? Is w? And I agree with rahnema that having to output a readable string there adds absolutely nothing interesting to the challenge and potentially having to compress the string if it's long distracts from the main challenge of implementing the game.

After reading this interesting challenge, I am disappointed with the subjective output format and scoring. If those were changed to be the standard boolean output rules, and standard golf scoring (or at least something that could be scored by an automated and objective script), then I would consider writing an answer.

And the output format isn't subjective - anything that a person could look at and go "Oh, it clearly means I won/completed" is fine. The problem with outputting "1" or "true" is that, if you weren't instructed on what it means, it wouldn't make any sense. In the same way, outputting y or w (or yes) wouldn't make any sense. I will include some recommended options, though.

Nothing about anyone's constructive criticism of this challenge was as childish as calling it that, and then complaining that your challenge wasn't well-received since you didn't follow the recommended standards that the community agreed on for a reason. And as for the output format, I'm sure most if not all of the community would back me up in saying that it's not difficult to just say "output a truthy value if the simulation runs to completion." It's not that difficult to make sense of.

@PatrickRoberts - what was childish was downvoting the question because it didn't conform exactly to a specific, rigid expectation of how a question "should" be. I was trying to make things interesting, by saying "this is simulating an actual game, don't just output "1" for a win", and trying to set up the rules to make things more competitive. Also, attacking things without providing alternatives isn't constructive. I stated my intent, and all I got was criticism, much of which was worded as attack rather than contribution ("Sorry, but all of this just goes to show that...")

To be clear, I have no problem with standards, but the standard is "what does truthy value entail", not "use truthy values in all cases". Note that there was no output if you didn't win, so a "1" or a "true" doesn't have a "falsy" corresponding value.

Octave, 68 64 94 92 83 bytes
a=f(a,s)m=a;for k=s;[~,x]=bwfill(a~=k&m,1,1,4);m(x)=0;a(x)=k;end;~m&&puts("win\n");

A function that takes as input a matrix a and a vector s as the sequence of commands and outputs the final state of the board.
Explanation:
function a=Flood(a,s)
    m=a;
    for k=s
        [~,x]=bwfill(a~=k&m,1,1,4);
        m(x)=0;
        a(x)=k;
    end
    ~m&&puts("Game Completed\n");
end

Usage:
num_colors = 4;
a = randi(num_colors, 5 ,7)
s = randi(num_colors, 1 , 15);
Flood(a,s)

Use m as a mask representing the filled region so far. Repeatedly run commands and flood fill the masked grid from the top left corner.

Nice, using a function that performs a fill as though the array were an image. I suspected some languages might be able to do that. Pleased to see it happen with one of the languages I know well.

I've made it a little clearer regarding output options. Feel free to reduce the output message to win (unless Octave has a nice way to output something like clear or done, or another such message).

Thank you for reading comments and making the challenge "a little" clearer!


text:
Oddly Even, Positively Negative
Given N, output the Nth term of this infinite sequence:
-1 2 -2 1 -3 4 -4 3 -5 6 -6 5 -7 8 -8 7 -9 10 -10 9 -11 12 -12 11 ... etc.

N may be 0-indexed or 1-indexed as you desire.
For example, if 0-indexed then inputs 0, 1, 2, 3, 4 should produce respective outputs -1, 2, -2, 1, -3.
If 1-indexed then inputs 1, 2, 3, 4, 5 should produce respective outputs -1, 2, -2, 1, -3.
To be clear, this sequence is generated by taking the sequence of positive integers repeated twice
1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 ...

and rearranging each pair of odd numbers to surround the even numbers just above it
1 2 2 1 3 4 4 3 5 6 6 5 7 8 8 7 9 10 10 9 11 12 12 11 ...

and finally negating every other term, starting with the first
-1 2 -2 1 -3 4 -4 3 -5 6 -6 5 -7 8 -8 7 -9 10 -10 9 -11 12 -12 11 ...

The shortest code in bytes wins.

A001057 without the leading zero?

@devRicher no, the absolute values there go 1,1,2,2,3,3,4,4,... but here it's 1,2,2,1,3,4,4,3,....

Could you provide a closed form for this sequence or at least something a little more specific than just the first several terms

That equation for the nth term never evaluates to a negative value... something is wrong with it.

@0                            ' I've added what I think in an intuitive way of looking at it, though not a closed form. Part of the challenge is figuring out what the pattern is and how to translate it to math and code.

@devRicher A121496 looks to be correct for the absolute values.

Python 2, 23 bytes
lambda n:~n/2+n%2*(n|2)

Odd inputs give roughly n/2, even ones roughly -n/2. So, I started with -n/2+n%2*n and tweaked from there.
Try it online!

Explanation? :)

Mathematica, 29 bytes
((#~GCD~4/. 4->-2)+#)/2(-1)^#&

Pure function taking a 1-indexed input. Other than the alternating signs (-1)^#, twice the sequence is close to the input, the differences being 1, 2, 1, -2 cyclically. It's nice that #~GCD~4, the greatest common divisor of the input and 4, is 1, 2, 1, 4 cyclically; so we just manually replace 4->-2 and call it a day. I like this approach because it avoids most of the many-character Mathematica commands.

Java 8, 19 bytes
n->~(n/2)+n%2*(n|2)

Java 7, 47 37 bytes
int c(int n){return~(n/2)+n%2*(n|2);}

First time Java (8) actually competes and is shorter than some other answers. Still can't beat the actual golfing languages like Jelly and alike, though (duhuh.. what a suprise.. >.> ;P)
0-indexed
Port from @Xnor's Python 2 answer.
-10 bytes thanks to @G.B.
Try it here.

You don't need the ternary check if you put (n/2) in parentheses.

@GB Ah, so that was the issue.. Thanks. I kinda feel stupid now.. >.>

Oh, we're allowed just function definitions for java?

@Cruncher Unless the question states otherwise, the default is full program or function. So yes, it is allowed to just post a method in Java, or a lambda in Java 8 (I've added the Java 8 equivalent in my answer above).

The types for the lambda do need to be declared: https://codegolf.meta.stackexchange.com/questions/11223/untyped-functions-in-static-langauges

Nice. But don't golf submissions should be stand-alone programs? As in, save it as .java and compile?

@EricDuminil The default is program or function, unless the challenge states otherwise.

Jelly, 8 7 bytes
H^Ḃ~N⁸¡

This uses the algorithm from my Python answer, which was improved significantly by @GB.
Try it online!
How it works
H^Ḃ~N⁸¡  Main link. Argument: n

H        Halve; yield n/2. This returns a float, but ^ will cast it to int.
  Ḃ      Bit; yield n%2.
 ^       Apply bitwise XOR to both results.
   ~     Take the bitwise NOT.
    N⁸¡  Negate the result n times.

I think this is the most standard ASCII characters I've seen in a Jelly submission. I only see two characters that would annoy me (not counting ¡)

https://www.google.com/search#q=%22look+ma'+no+unicode%22+inurl:codegolf.stackexchange.com/questions

Pip, 24 22 bytes
v**a*YaBA2|1+:--a//4*2

Takes input, 1-indexed, as a command-line argument. Try it online or verify 1-20.
Explanation
Observe that the sequence can be obtained by combining three other sequences, one zero-indexed and the others one-indexed:

Start with 0 0 0 0 2 2 2 2 4 4 4 4 = a//4*2 (0-indexed);
Add 1 2 2 1 1 2 2 1 1 2 2 1 = aBA2|1, where BA is bitwise AND, and | is logical OR (1-indexed);
Multiply the sum by -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 = (-1)**a (1-indexed).

If we start with a 1-indexed, we can compute the 1-indexed parts first (reading the expression left to right) and then decrement a for the 0-indexed part. Using the builtin variable v=-1, we get
v**a*((aBA2|1)+--a//4*2)

To shave two more bytes, we have to use some precedence-manipulation tricks. We can eliminate the inner parentheses by replacing + with +: (equivalent to += in a lot of languages). Any compute-and-assign operator is of very low precedence, so aBA2|1+:--a//4*2 is equivalent to (aBA2|1)+:(--a//4*2). Pip will emit a warning about assigning to something that isn't a variable, but only if we have warnings enabled.
The only thing that's lower precedence than : is Y, the yank operator.* It assigns its operand's value to the y variable and passes it through unchanged; so we can eliminate the outer parentheses as well by yanking the value rather than parenthesizing it: YaBA2|1+:--a//4*2.
* Print and Output have the same precedence as Yank, but aren't useful here.

Jelly, 15 12 11 bytes
Ḷ^1‘ż@N€Fị@

Try it online!
How it works
Ḷ^1‘ż@N€Fị@  Main link. Argument: n

Ḷ            Unlength; yield [0, 1, 2, 3, ..., n-1].
 ^1          Bitwise XOR 1; yield [1, 0, 3, 2, ..., n-1^1].
   ‘         Increment; yield [2, 1, 4, 3, ..., (n-1^1)+1].
      N€     Negate each; yield [-1, -2, -3, -4, ..., -n].
    ż@       Zip with swapped arguments;
             yield [[-1, 2], [-2, 1], [-3, 4], [-4, 3], ..., [-n, (n-1^1)+1]].
        F    Flatten, yield [-1, 2, -2, 1, -3, 4, -4, 3, ..., -n, (n-1^1)+1].
         ị@  At-index with swapped arguments; select the item at index n.

I knew there'd be a jelly answer around 10

There's also a Jelly answer at 7. ;)

I saw it right after posting this comment lol. I really need to learn Jelly one of these days... It's funny if you look at the history of questions on this SE. Used to be all GolfScript, then CJam took over, and now it's Jelly.

Ruby, 26 23 18 bytes
->n{~n/2+n%2*n|=2}

0-based
-3 bytes stealing the -1^n idea from Greg Martin, Dennis and maybe somebody else, then -5 bytes stealing the n|2 idea from xnor.

RProgN 2, 31 25 22 bytes
nx=x2÷1x4%{+$-1x^*}#-?

Explained
nx=                         # Convert the input to a number, set x to it.
   x2÷                      # Floor divide x by 2.
      1                     # Place a 1 on the stack.
       x4%{       }#-?      # If x%4 is 0, subtract 1 from x//2, otherwise...
           +                # Add the 1 and the x together.
            $-1             # Push -1
               x^           # To the power of x.
                 *          # Multiply x//2+1 by -1^x. (Invert if odd, do nothing if even)

Try it online!

Nice approach! +1

Stacked, 30 28 bytes
:2%([:2/\4%2=tmo+][1+2/_])\#

Try it online! Returns a function, which as allowed per meta consensus.. Takes input from the top of the stack.
Using the same approach as the RProgN 2 answer.

Alternatively, 46 bytes. Try it online!:
{!()1[::1+,:rev,\srev\,\2+]n*@.n 1-#n 2%tmo*_}

This one generates the range then selects and negates the member as appropriate.

Python 2,  44  33 27 bytes
lambda n:(-1)**n*~(n/2^n%2)

Thanks to @GB for golfing off 6 bytes!
Try it online!

Jelly, 9 8 bytes
|2×Ḃ+H~$

Try it online!
-1 thanks to Dennis. Duh float conversions.
Uses @xnor's Python 2 approach.
EDIT: >_>

Just when you think you're winning, Dennis will come along and beat you.

|2×Ḃ+H~$ saves a byte. https://tio.run/nexus/jelly#AR0A4v//fDLDl@G4gitIfiT/MjThuLbCtcW8w4figqxH/w

@Dennis I thought that would spit an error.

05AB1E, 8 bytes
2‰`^±¹F(

Try it online
Explanation
2‰          divmod by 2
  `         flatten list
   ^        XOR
    ±       NOT
     ¹F(    Push 1st argument, loop N times, negate

Wow, I love it,  but ¹F( seems expensive for "if odd, negate".

@carusocomputing It does, but that's the shortest I know of. Dennis's similar answer in Jelly also has 3 bytes for that part. It's still shorter than duplicate, push parity, if, negate.

I tried for 15 minutes to beat it, only thing that came close was another 3 byte solution of to the power of  n, to the power of 1/n.

CJam, 16 bytes
{_(_1&)^2/)W@#*}

1-based input.
Try it online!
Explanation
Here is a breakdown of the code with the values on the stack for each input from 1 to 4. The first few commands only affect the two least significant bits of n-1 so after 4, this stuff just repeats cyclically, with the results incremented by 2, due to the halving.
Cmd             Stack: [1]       [2]       [3]       [4]
_    Duplicate.        [1 1]     [2 2]     [3 3]     [4 4]
(    Decrement.        [1 0]     [2 1]     [3 2]     [4 3]
_    Duplicate.        [1 0 0]   [2 1 1]   [3 2 2]   [4 3 3]
1&   AND 1.            [1 0 0]   [2 1 1]   [3 2 0]   [4 3 1]
)    Increment.        [1 0 1]   [2 1 2]   [3 2 1]   [4 3 2]
^    XOR.              [1 1]     [2 3]     [3 3]     [4 1]
2/   Halve.            [1 0]     [2 1]     [3 1]     [4 0]
)    Increment.        [1 1]     [2 2]     [3 2]     [4 1]
W    Push -1.          [1 1 -1]  [2 2 -1]  [3 2 -1]  [4 1 -1]
@    Rotate.           [1 -1 1]  [2 -1 2]  [2 -1 3]  [1 -1 4]
#    -1^n.             [1 -1]    [2 1]     [2 -1]    [1 1]
*    Multiply.         [-1]      [2]       [-2]      [1]

Perl 6,  55 27 24  22 bytes
{(-1,2,-2,1,{|($^a,$^b,$^c,$^d Z+ -2,2,-2,2)}...*)[$_]}

(Inspired by the Haskell zipWith answer)
Try it
{+^($_ div 2)+$_%2*($_+|2)}

(Inspired by several answers)
Try it
{+^($_+>1)+$_%2*($_+|2)}

Try it
{+^$_+>1+$_%2*($_+|2)}

Try it
Expanded:
{  # bare block lambda with implicit parameter ｢$_｣

    +^          # numeric binary invert the following
      $_ +> 1   # numeric bit shift right by one
  +
      $_ % 2    # the input modulo 2
    *
      ($_ +| 2) # numeric binary inclusive or 2
}

(All are 0 based)

Nice submission!

Haskell, 37 36 bytes
(([1,3..]>>= \x->[-x,x+1,-x-1,x])!!)

Try it online! This is an anonymous function which takes one number n as argument and returns 0-indexed the nth element of the sequence.

Perl 5 47 + 1 (for flag) =  48 Bytes
print(((sin$_%4>.5)+1+2*int$_/4)*($_%4&1?1:-1))

Old Submission 82 Bytes
@f=(sub{-$_[0]},sub{$_[0]+1},sub{-$_[0]-1},sub{$_[0]});print$f[$_%4](1+2*int$_/4)

Run like so:
perl -n <name of file storing script>  <<<  n

You can save one byte by using print +(( and removing the final ). And two more by using say and -E. And also one more by doing ($_%4&1||-1) instead of the ternary.

Haskell, 56 bytes
f n=concat(iterate(zipWith(+)[-2,2,-2,2])[-1,2,-2,1])!!n

0-indexed

JavaScript, 28 22 bytes
Thanks @ETHproductions for golfing off 6 bytes
x=>x%2?~x>>1:x%4+x/2-1

Try it online!

Hmm... would f=x=>x%2?~x>>1:x/2+x%4-1 work?

For some reason I had left the f= in front of the anonymous function :P

JavaScript (ES7), 28 bytes
n=>(n+2>>2)*2*(-1)**n-!(n&2)

1-indexed. I haven't looked at any other answers yet so I don't know if this is the best algorithm, but I suspect not.

dc, 98 bytes
?sa0sb1sq[lq1+dsqla!<i3Q]sf[lb1-lfx]su[lblfx]sx[lb1+dsblfx]sj[lqdd4%d0=u1=j2%1=xljxlfx]dsix_1la^*p

Gosh, this is the longest answer here, mainly because I went the path of generating the absolute value of each element of the sequence one by one based on the following recursive formula:

then outputting (-1)^n * a_n, rather than directly computing the n'th element. Anyways, this is 1-indexed.
Try it online!

R, 38 bytes
function(n)floor(n/2+1-2*!n%%4)*(-1)^n

Explanation
floor(n/2+1)                ->  1 2  2 3  3 4  4 5...
floor(n/2+1-2*!n%%4)        ->  1 2  2 1  3 4  4 3... (subtract 2 where n%%4 == 0)
floor(n/2+1-2*!n%%4)*(-1)^n -> -1 2 -2 1 -3 4 -4 3... (multiply odd n by -1)

TI-Basic (TI-84 Plus CE), 31 bytes
.5(Ans+1+remainder(Ans+1,2)-4not(remainder(Ans,4)))i^(2Ans

TI-Basic is a tokenized language and each token used here is one byte, except remainder(, which is two.
This uses the 1-indexed version.
Explanation:
There is a pattern that repeats every four numbers. In the 1-indexed version, it is: -(x+1)/2, (x+1)/2, -(x+1)/2, (x-1)/2 for the input value x. This can be represented as a piecewise-defined function.
f(x) = -(x+1)/2 if x ≡ 1 mod 4; (x+1)/2 if x ≡ 2 mod 4; -(x+1)/2 if x ≡ 3 mod 4; (x-1)/2 if x ≡ 0 mod 4
Because the "x ≡ 1 mod 4" and "x ≡ 3 mod 4" parts are the same, we can combine them into "x ≡ 1 mod 2".
Now are piecewise function is:
f(x) = -(x+1)/2 if x ≡ 1 mod 2; (x+2)/2 if x ≡ 2 mod 4; (x-2)/2 if x ≡ 0 mod 4
This is where I start breaking it into actual commands. Since the value is positive for even indexes and negative for odd ones, we can use (-1)^x. However, in TI-Basic i^(2X (5 bytes) is shorter than (-1)^Ans (6 bytes). Note that parentheses are required due to order of operations.
Now that we have the way to negate the odd inputs out of the way, we move on to the mods (adding the negating back on later). I made the case of an odd input the default, so we start with .5(Ans+1).
To fix the case of even input, just add one to the number in the parentheses, but only when x ≡ 0 mod 2. This could be represented as .5(Ans+1+remainder(Ans+1,2)) or .5(Ans+1+not(remainder(Ans,2))), but they have the same byte count, so it doesn't matter which.
To fix the case of multiple-of-4 input, we need to subtract 3 from the number in the parentheses, but also another 1 because all multiples of 4 are even, which would add one from our previous step, so we now have .5(Ans+1+remainder(Ans+1,2)-4not(remainder(Ans,4))).
Now, just tack on the sign-determining part to the end to get the full program.

Befunge 93, 25 bytes
Zero-indexed
&4/2*1+&4%3%!!+&2%2*1-*.@

Try it Online!
The number is given by ((2(n / 4) + 1) + !!((n % 4) % 3)) * (2(n % 2) - 1)

QBIC, 53 bytes
b=1:{[b,b+3|~b=a|_x(-(b%2)*2+1)*(q+(b%4>1)*-1)]]q=q+2

Explanation:
b=1     Set b to a starting value of 1
        QBIC would usually use the pre-initialised variable q, but that is already in use
:       Get an input number from the cmd-line, our term to find
{       Start an infinite loop
[b,b+3| FOR-loop: this runs in groups of 4, incrementing its own bounds between runs
~b=a|   If we've reached the term requested
_x      QUIT the program and print:

(-(b%2)*2+1)   The b%2 gives a 1 or a 0, times 2 (2,0), negged (-2,0) and plus one (-1,1)
*              That gives us the sign of our term. Now the value:
(q+(b%4>1)*-1) This is q + 1 if the inner loop counter MOD 4 (1,2,3,0...) is 2 or 3.
]       Close the IF that checks the term
]       Close the FOR-loop
q=q+2   And raise q by 2 for the next iteration of the DO-loop.

Wise, 19 bytes
::>!:><^^~![!-!-~]|

Try it Online!
This is just a port of @Dennis' Jelly answer to Wise.

Q, 52 bytes
{(1 rotate(,/){x,(-)x}each 1_((_)x%4)+til 3)x mod 4}

0 indexed solution.

Gets the block number ie. which [-x x+1 -(x+1) x] block within the sequence contains the index.
Gets the index of the value within the block based on the index of the value within the whole sequence.
Creates the block.
Indexes into it via index derived in step 2.


text:
Compute the most efficient binary function
Today, we'll be computing the most efficient binary function. More specifically, we'll be computing the function which, when an expression is created from applying the function to the constant input 0 or its own output, can represent all positive integers with the shortest possible expressions, placing higher priority on the smaller integers.
This function is built as follows:
For each integer, starting at 1 and going upwards, choose the shortest expression which we have not yet assigned an output to, and make that integer the output of that expression. Ties in expression length will be broken by smaller left argument, and then by smaller right argument. Here's how it works:

Initially, 1 is unassigned. The shortest unassigned expression is f(0, 0), so we'll set that to 1.
Now, 2 is unassigned. The shortest unassigned expressions are f(f(0, 0), 0) = f(1, 0) and f(0, f(0, 0)) = f(0, 1). Ties are broken towards smaller left argument, so f(0, 1) = 2.
The shortest unassigned expression remaining is f(f(0, 0), 0) = f(1, 0), so f(1, 0) = 3.
Now, we're  out of expressions with only 2fs and 30s, so we'll have to add one more of each. Breaking ties by left argument, then right argument, we get f(0, 2) = 4, since f(0, f(0, f(0, 0))) = f(0, f(0, 1)) = f(0, 2).
Continuing, we have f(0, 3) = 5, f(1, 1) = 6, f(2, 0) = 7, f(3, 0) = 8, f(0, 4) = 9, ...

Here's a table I filled out for the first few values:
    0  1  2  3  4  5  6  7  8
 /---------------------------
0|  1  2  4  5  9 10 11 12 13
1|  3  6 14 15 37 38 39 40 41
2|  7 16 42 43
3|  8 17 44 45
4| 18 46
5| 19 47
6| 20 48
7| 21 49
8| 22 50

Another way to look at it is that each output has a size, equal to the sum of the sizes of its inputs plus one. The table is filled out in order of increasing size of output, ties broken by minimizing left input then right input.
Your challenge is, given two non-negative integers as input, compute and output the value of this function. This is code golf. Shortest solution, in bytes, wins. Standard loopholes are banned.

Looks similar to A072766, but differs starting from f(3, 1).

This is the first challenge in a while that puzzles me somewhat to calculate efficiently. I believe something is possible with Catalan numbers, but can't immediately think of a solution. Hmm...

Alright, so I don't think it'd make a good golfed answer, but what you can do to make it reasonably efficient is repeatedly subtract Catalan numbers from the function arguments until they're smaller than the next Catalan number. Then you've found the length of their expressions. Then you can use the ranking/unranking functions from this paper, with modification, to calculate the result. Perhaps after doing all that it's possible to 'cancel out' bits of code in the middle and find a reasonably elegant solution.

Actually, the approach from my previous comment doesn't work. ((0, (0, (0, 0))), 0) is lexicographically smaller than (((0, 0), 0), (0, 0)), however the latter has a smaller left hand side.

Haskell, 110 bytes
f q=head[i|let c=[(-1,0)]:[[(f a,f b)|n<-[0..k],a<-c!!n,b<-c!!(k-n)]|k<-[0..]],(p,i)<-zip(concat c)[0..],p==q]

The argument here is taken to be the tuple (x,y). Pretty similar to the answer above, but the lookup list holds just the pairs of left and right indices instead of the trees.

Nice answer! head[...] is [...]!!0 and (p,i)<-zip(concat c)[0..] can be shortened to (i,p)<-zip[0..]$id=<<c.

Thanks for the improvements! Definitely adding id=<< to the repertoire :)

Wow! I actually managed to make an efficient computation algorithm. I did not expect this at first. The solution is quite elegant. It repeatedly deduces more and more, then recurses all the way down to the base case of 0. In this answer the C(n) function denotes the Catalan numbers.
The crucial first step is acknowledging that there are C(0) = 1 values of length zero (namely 0 itself), C(1) = 1 values of length one (namely f(0, 0)), C(2) = 2 values of length two (f(0, f(0, 0)) and f(f(0, 0), 0)).
This means that if we're looking for the nth expression, and we find the biggest k such that C(0) + C(1) + ... + C(k) <= n then we know that n has length k.
But now we can continue! Because the expression we look for is the n - C(0) - C(1) - ... - C(k) th expression in its length class.
Now we can use a similar trick to find the length of the left segment, and then the rank within that subsection. And then recurse on those ranks we found!
It found that f(5030, 3749) = 1542317211 in the blink of an eye.
Python, noncompeting
def C(n):
    r = 1
    for i in range(n):
        r *= 2*n - i
        r //= i + 1
    return r//(n+1)

def unrank(n):
    if n == 0: return 0

    l = 0
    while C(l) <= n:
        n -= C(l)
        l += 1

    right_l = l - 1
    while right_l and n >= C(l - 1 - right_l) * C(right_l):
        n -= C(l - 1 - right_l) * C(right_l)
        right_l -= 1

    right_num = C(right_l)

    r_rank = n % right_num
    l_rank = n // right_num

    for sz in range(l - 1 - right_l): l_rank += C(sz)
    for sz in range(right_l): r_rank += C(sz)

    return (unrank(l_rank), unrank(r_rank))

def rank(e):
    if e == 0: return 0
    left, right = e

    l = str(e).count("(")
    left_l = str(left).count("(")
    right_l = str(right).count("(")
    right_num = C(right_l)

    n = sum(C(sz) for sz in range(l))
    n += sum(C(sz)*C(l - 1 - sz) for sz in range(left_l))

    n += (rank(left) - sum(C(sz) for sz in range(left_l))) * C(right_l)
    n += rank(right) - sum(C(sz) for sz in range(right_l))

    return n

def f(x, y):
    return rank((unrank(x), unrank(y)))

I'm fairly certain I'm doing a bunch of unnecessary computation and a lot of middle steps could be removed.

Python 3, 154 bytes
b=lambda n:[(l,r)for k in range(1,n)for l in b(k)for r in b(n-k)]+[0]*(n<2)
def f(x,y):r=sum((b(n)for n in range(1,x+y+3)),[]);return r.index((r[x],r[y]))

It's not very fast nor very golfy, but it's a start.


text:
Dancing arrays. Output them with some forward-backward moves
The task is to create a program (or a function), which outputs array elements  in the order, determined by two numbers F and B. F is number of elements to print, B is the rollback distance (from last printed element). Each element must be printed on separate line and blank line must be inserted after each rollback. Run till the end of array. If endless loop or backward progression requested, program should print nothing and exit. Same for empty arrays.
F and B cannot be negative numbers. Be positive while dancing!
For example, if given:
array is 2, 3, 5, 7, 11, 101, 131;
F is 4;
B is 1;

then output must be:
2
3
5
7

5
7
11
101

11
101
131

Init array, F and B as you like.
Shortest code wins. Imperative beauty will be enjoyed.
Test cases:
Empty array.
Any F.
Any B.

Produces no output (array is empty).

Array: [42]
F = 0;
B = 1;

Produces no output (zero elements to print).

Array: [42, 17, 84]
F = 2;
B = 1;

Produces no output (endless printing).

Array: [7, 16, 65]
F = 2;
B = 3;

Produces no output (will be moving backward to negative indices).

Array: [7, 16, 65]
F = 2;
B = 0;

Output:
7
16

16
65

Array: [7, 16, 65]
F = 3;
B = 2;

Output:
7
16
65

(no rollback, end of array is reached).

Array: [7, 16, 65]
F = 17;
B = 15;

Output:
7
16
65

(run till the end)

Array: [7, 16, 65]
F = 17;
B = 16;

Output:
7
16
65

Whole array can be printed in first iteration, run till the end is working, even if F and B form endless-loop condition.

Can we get more test cases?

So.. It's like the snail climbing to escape the well, reads the number each time it moves?

Consider allowing more flexible output,  such as each subarray on a line without the blank lines, or an array of subarrays

Can I take input as [array],F,B?

Are we guaranteed that F < len(array)?

@HyperNeutrino Yes, input can be [array],F,B.

@HyperNeutrino There is no guarantee of F. in case of F >= len(array), If there is no endless or backward-movement break conditions, program should output one iteration (which will be whole array) and exit. "Run till the end of array"

Ok, i think it will be more interesting to print array once, if F if >= len(array). Even if F and B form bad conditions.

Nice first post here! For future challenges, I would recommend posting them in the Sandbox first so you can get suggestions and improve your challenge before posting!

@RomanBruhanov Request to print array once if F >= len(array) would just add F=min(F,len(array)) to every code. Nothing very interesting

Can we assume the entries in the array are all distinct?

Is it ok to print trailing newlines?

"Be positive while dancing" Nice play on words!

Python 2, 135 128 126 bytes
Pretty naive solution:
a,f,b=input()
b+=1
l=len(a)
i=0
e=min(l,f)
while f>b:
    print'\n'.join(map(str,a)[i:e])+'\n';i=e-b
    if e==l:f=b
    e=min(l,e+f-b)

Try it online!
Input format is [array], F, B except you can also use (). (You can't use {} because that's unordered; thanks to Felipe Batista for pointing that out because I forgot).
Output format is as specified in the challenge, with a single trailing newline at the end of all output and no leading whitespace.
-7 bytes by changing if f>b: while 1: to while f>b
-2 bytes by changing break to f=b because that causes the while loop to exit.

You can save bytes by removing the unnecessary indentation

@Mr.Xcoder all the indentation in his code is necessary.

Oh yes sorry :|||. My bad...

how would you use {} in the input? that would be unordered

@FelipeNardiBatista Whoops. I forgot about that.

JavaScript, 119 bytes
(a,b,c)=>{o="";for(s=++b;(s<(t=c.length)||s==b)&&s>=0&&b<a;)s-=b,o+=c.slice(s,s+=a<t?a:t).join`
`+`

`;return s>0?o:""}

Try it online!
Receives input in the format F, B, [Array]

You could save one byte by moving o+=...; inside the for loop.

Python 2, 116
Finally beat javascript!
Now in case of endless loop outputs full array only if it fits in one step, otherwise ouputs nothing. Output all array in every case of endless loop was harder.
Uncomment different test cases in footer in Try it online
a,F,B=input()
l=len(a)-F;m=F+~B or-1;s=l/m;s+=1+(s*m<l)
for i in range(s):print"\n".join(map(str,a)[m*i:F+i*m]+[''])

Explanation:
  a,F,B=input()
  l=len(a)-F            # length of input array minu F stored to compact code
  m=F+~B or-1           # get the difference beetween blocks of output
                        # if F-B-1 == 0, which means endless loop, makes m = -1, which will make s < 0 and for loop won't execute
  s=l/m                 # get number of blocks (does not count first block)
  s+=1+(s*m<l)          # +1 for first block (brackets are still needed)
                        # s*m<l-F equals +1 for numbers at the end of array, that are not enough to make full block
                        # s becomes 2 in case of F-B-1==0, but it doesn't matter
  for i in range(s):
                        # print elements from slices, joined by line separator
                        # additional empty element added at the end of each block to divide blocks with newline
    print"\n".join(map(str,a)[m*i:F+i*m]+[''])

"If endless loop or backward progression requested, program should print nothing and exit" You are printing the array once on endless loop...

@fəˈnɛtɪk "Whole array can be printed in first iteration, run till the end is working, even if F and B form endless-loop condition."
Doen't that counts?

@fəˈnɛtɪk I re-read post again and brought a little fix. Indeed it seems that program should not output anything in case of endless loop, until whole array fits in one step

You can save 2 bytes by changing 1+(s*m<1-F) to s*m<1-F+1 because that way you don't need the brackets.

@HyperNeutrino No, I can't do that as (s*m<l-F) should evaluates to 0 or 1. If I remove brackets, than it would evaluates as (s*m<l)-F

It still behaves as expected either way... I'm running it with s*m<l-F+1 and it still works properly.

@HyperNeutrino Nope, it does not, check proof

Oh never mind, I didn't notice the missing end part. Whoops.

05AB1E, 41 bytes
gD²³+‹iq}©0U[XD²<+Ÿv¹yè,}¶,³X+U®X³2*+-0‹#

Try it online!
That output format, and inability to limit inputs for F/B made this less fun, will explain soon.

Mathematica, 136 123 bytes
Here's my answer:
""<>r[#~(r=Riffle)~"\n"&/@Quiet@Check[Partition[#,#2,n=#2-#3-1,1,{}]~Take~-Floor[(L=#2-Length@#)/n-1],If[L<0,{},{#}]],"\n\n"]&

(where \ns are replaced by newlines). It's a function that takes a list of strings (e.g. {"1", "2", "3", ...}) and two integers.
Mathematica has a function that almost solves this challenge on its own, namely Partition[#, #2, #2-#3-1, 1, {}]. However, the output format isn't what we want, it returns errors if F and B would put the program into a loop, and it doesn't stop when it reaches the end of a list (so if the inputs are {"1", "2", "3"}, 3, 1, for instance, it returns {{"1", "2", "3"}, {"2", "3"}, {"3"}} instead of just {{"1", "2", "3"}}). We deal with those technicalities as follows:

...~Take~-Floor[(L=#2-Length@#)/n-1] gets rid of the extra bits after we hit the end of the list.
Quiet@Check[...,If[L<0,{},{#}]] deals with the infinite loop cases by Checking if the earlier code gives errors (but it does it Quietly, so it doesn't actually print them), and instead returns an empty list or the entire list as appropriate.
""<>r[#~(r=Riffle)~"\n"&/@...,"\n\n"]& formats the output properly, by putting newlines between everything, including double newlines between the separate groups, and string-joins that all together.

Ruby, 78 76 72 bytes
->a,f,b{i=b-=f-1;puts a[i,f]+[""]while 0>b&&a[f+i-=b];b<i&&puts(a[i,f])}

Explanation

Initialize the index so that the first step brings it back to zero.
Print f elements from the array starting with the current index, then a newline
Move the index f-b-1 elements forward, but only if (b-f+1) is negative
If the increment is not negative, or we reached the end of the array, stop.
If everything went Ok, the increment is negative, and the index is not (we took at least one step forward), in this case print the remaining elements.

dc, 123 bytes
[[[dx]dx]sOzlF!>O]sO?1+sBsFlFlB-1>O_1sq[lq1+:Rlq1+sqz0<k]dskx0sd[[10PlqlB+sq]sWld0<W]sz[ldlF%0=zlq;Rplq1-dsqld1+sd0!>g]dsgx

Much longer than it should have been because of strict output regulations. Takes input on one line in the format
n_1 n_2 ... n_k F B

where n_i represents the ith element of the k length array. I hope this is an okay input format.
Try it online!