text:
Letter-replacement challenge
The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2.
For example:
|    | Input                       | Starting Word | Output      |
|----|-----------------------------|---------------|-------------|
| #1 | Hello world -wo -ld +Ea +th | Hello world   | Hello Earth |
| #2 | Hello World -wo -ld +Ea +th | Hello World   | Hello Worth |
| #3 | Hello -llo +y               | Hello         | Hey         |
| #4 | Red -R -d +Gr +en           | Red           | Green       |
| #5 | mississippi -is -i +lz +p   | mississippi   | mlzslzspppp |
| #6 | Football -o -a +a +i        | Football      | Fiitbill    |
| #7 | mississippi -is -i +iz +p   | mississippi   | mpzspzspppp |

Explanation
The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of mississippi -is -i +iz +p to give the output mpzspzsppp (see example #7 above)
| Step  | Input                         | Output        |
|------ |---------------------------    |-------------  |
| #1    | mississippi -is -i +iz +p     |               |
| #2    | mississippi -is +iz           | mizsizsippi   |
| #3    | mizsizsippi -i +p             | mpzspzspppp   |

Rules

Inputs are always in this order <starting_string> <list_of_letters_to_replace> <replacement_letters>.
Letters to replace and replacement groups will never be mixed (ie: there will never be -a +i -e +o).
Letters to replace are always prefixed with - and replacement letters are always prefixed with +. (The prefix is mandatory)
There may be more than one set of letters to replace, so you'd need to look at the prefix.
Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be -a -e +i)
Replacements are case-sensitive (see example #1 and #2).
Replacements are done in the order they were given in the input.
Letter replacements can be replaced with other replacements. See example #6.
The first segment (starting word) will never include - or + characters.
This is code-golf so shortest bytes win.

Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
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 leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=96473,OVERRIDE_USER=38505;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://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

Given rules 2 and 5, you really don't need to look at the prefix. With n inputs, input 0 is the base string, inputs 1 to int(n/2) are letter to replace (with prefix -) and input int(n/2)+1 to n-1 are replacement (with prefix +)

@edc65 100% true, although the challenge was designed to have the prefix (and I could make up some weird explanation that I'm an alien who cannot process letter replacements without their prefix) but in reality, it's just another barrier to stop this being too trivial - though looking at the current answers (all are great by the way) it wasn't a complex barrier. Also fun fact, the idea behind this challenge was spawned from my friend in a Skype chat. He'd mis-spell a word (gello), and then send me the letter replacements (-g +h) because he wanted to be annoying instead of sending hello*.

Inputs are always in this order Why so restrictive?

@LuisMendo I guess it doesn't really matter - but it's the way my friend and I formatted it, but since answers have been posted to this requirement, I cannot really make a rule change. It wasn't questioned on the sandbox, so I didn't think of it as a negative.

Is the base string guaranteed to contain only letters and spaces without punctuation marks?

@Arnauld Yes, in fact the starting word will only be 1 or 2 words (special characters, hyphens).

By "base string", I meant the whole expression on which replacements are applied, not just the first word. "Hello world" is definitely two space-separated words. :-)

@Arnauld ah sorry, very light sleep last night. Yes, you're right. The base string character set is [a-zA-Z\+\-\s]

Example #2 is wrong (duplicate of #1). I don't know what it was supposed to be, but it should probably support the "Replacements are case-sensitive" rule (which neither #1 nor #2 really do).

@udioica is perfecly right and it in fact support  the "Replacements are case-sensitive" rule. Run the snippet in the JavaScript answer to see it implemented. (#1 world` vs #2 World)

JavaScript (ES6), 85 83 bytes
f=(s,n=1,l=s.split(/ \W/))=>(r=l[n+l.length/2|0])?f(s.split(l[n]).join(r),n+1):l[0]

Test cases

f=(s,n=1,l=s.split(/ \W/))=>(r=l[n+l.length/2|0])?f(s.split(l[n]).join(r),n+1):l[0]

console.log(f("Hello world -wo -ld +Ea +th"));
console.log(f("Hello World -wo -ld +Ea +th"));
console.log(f("Hello -llo +y"));
console.log(f("Red -R -d +Gr +en"));
console.log(f("mississippi -is -i +lz +p"));
console.log(f("Football -o -a +a +i"));
console.log(f("mississippi -is -i +iz +p"));

05AB1E, 15 17 bytes
IIð¡€áIð¡€á‚øvy`:

Try it online!
Explanation
I                   # read starting string
 I                  # read letters to be replaced
  ð¡                # split on space
    €á              # and remove "-"
      I             # read replacement letters
       ð¡           # split on space
         €á         # and remove "+"
           ‚ø       # zip to produce pairs of [letters to replace, replacement letters]
             vy`:   # for each pair, replace in starting string

Or with a less strict input format
vy`:

Try it online

Pyke, 13 11 bytes
z[zdcmt)[.:

Try it here!
z           - input()
 [zdcmt)    - def func():
  zdc       -  input().split(" ")
     mt     -  map(>[1:], ^)
            - func()
        [   - func()
         .: - translate()

Or 2 bytes if in a different input format:
.:

Try it here!

At work catbus.co.uk is blocked. Are you able to link an alternative test suite please?

@ʰᵈˑ I don't believe conforming to your (arbitrary) work firewall settings is reasonable.

@orlp - I agree, it's shit. But I don't set the firewall settings. I just wanted to test it out

@hd you can download Pyke at github.com/muddyfish/pyke

Perl, 58 bytes
57 bytes code + 1 for -p.
Requires first item on one line, then the replacements on the next. Big thanks to @Dada who came up with a different approach to help reduce by 4 bytes!
$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee

Usage
perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'Football
-o -a +a +i'
Fiitbill

perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'mississippi
-is -i +iz +p'
mpzspzspppp

perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'mississippi
-ippi -i -mess +ee +e +tenn'
tennessee

4 bytes longer, there is perl -pE 's/(.*?) -(\S*)(.*?)\+(\S*)/"(\$1=~s%$2%$4%gr).\"$3\""/ee&&redo'. I can't manage to get it any shorter, but maybe you can :)

Gotcha! 58 bytes : perl -pE '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee'. (takes the string on one line, and the "flags" on the next line)

Awesome! I'm not at a computer but I'll update that tomorrow! Thanks!

Are you sure about removing the q{} surrounding $2 ? Wouldn't this fail when there are 3 - and 3 + switches? (I can't test it now, so maybe you were right so remove it ;) )

@Dada ahhh, I did wonder why you'd added it, I tested all the cases in the test suite, but didn't think about a 3 for 3 replacement...

PHP, 98 97 bytes
for($s=$argv[$i=1];$v=$argv[++$i];)$r[$v[0]>'+'][]=substr($v,1);echo str_replace($r[1],$r[0],$s);

This challenge describes the exact behaviour of str_replace so for php it's all about making the arrays of replacements. I tried to do it using only one "substring" but that might not be the best solution. Use like:
php -r "for($s=$argv[$i=1];$v=$argv[++$i];)$r[$v[0]>'+'][]=substr($v,1);echo str_replace($r[1],$r[0],$s);" "mississippi" "-is" "-i" "+iz" "+p"

edit: 1 byte saved thanks to Titus

This is probably the shortest thing possible. But $v[0]>'+' saves one byte over $v[0]=='-'. You could also use ord($v)&4 instead.

GNU sed 86 Bytes
Includes +1 for -r
:;s,^([^-]*)(\w+)([^-]*-)\2( [^+]*\+)(\w*),\1\5\3\2\4\5,
t;s,-[^-+]*,,;s,\+[^-+]*,,;t

Try it online!
Example:
$ echo 'Hello world -wo -ld +Ea +th'|sed -rf replace.sed
Hello Earth

Java 7, 153 133 bytes
String c(String[]a){String r=a[0],z[]=a[1].split(" ?-");for(int i=0;i<z.length;r=r.replace(z[i],a[2].split(" ?[+]")[i++]));return r;}

Ungolfed & test code:
Try it here.
class M{
  static String c(String[] a){
    String r = a[0],
           z[] = a[1].split(" ?-");
    for(int i = 0; i < z.length; r = r.replace(z[i], a[2].split(" ?[+]")[i++]));
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "Hello world", "-wo -ld", "+Ea +th" }));
    System.out.println(c(new String[]{ "Hello World", "-wo -ld", "+Ea +th" }));
    System.out.println(c(new String[]{ "Hello", "-llo", "+y" }));
    System.out.println(c(new String[]{ "Red", "-R -d", "+Gr +en" }));
    System.out.println(c(new String[]{ "mississippi", "-is -i", "+lz +p" }));
    System.out.println(c(new String[]{ "Football", "-o -a", "+a +i" }));
    System.out.println(c(new String[]{ "mississippi", "-is -i", "+iz +p" }));
  }
}

Output:
Hello Earth
Hello Worth
Hey
Green
mlzslzspppp
Fiitbill
mpzspzspppp

Does this work for the input new String[]{'Rom Ro. Rom", "-Ro." , "+No."}? Just writing something that (hopefully) matches a wrong regex.

@RomanGräf Yes, works and outputs Rom No. Rom. Btw, you can try it yourself by clicking the Try it here. link in the post, and then fork it. :)

I know but I'm currently on my mobile. :(

R, 98 94 bytes
Edit: saved 4 bytes thanks to @rturnbull
i=scan(,"");s=i[1];i=gsub("\\+|-","",i[-1]);l=length(i)/2;for(j in 1:l)s=gsub(i[j],i[l+j],s);s

Ungolfed and test cases
Because scan (reads input from stdin) doesn't work properly in R-fiddle I showcase the program by wrapping it in a function instead. Note that the function takes a vector as an input and can be run by e.g.: f(c("Hello world", "-wo", "-ld", "+Ea", "+th")). The gofled program above would prompt the user to input using stdin whereby typing "Hello world" -wo -ld -Ea +th in the console would yield the same result.
Run the code on R-fiddle
f=function(i){
    s=i[1]                                   # Separate first element
    i=gsub("\\+|-","",i[-1])                 # Remove + and - from all elements except first, store as vector i
    l=length(i)/2                            # calculate the length of the vector i (should always be even)
    for(j in 1:l)s=gsub(i[j],i[l+j],s)       # iteratively match element j in i and substitute with element l+j in i
    s                                        # print to stdout
}

Can you provide a test suite link also, please?

@ʰᵈˑ added an R-fiddle test suite. Note that the test suite uses a function instead of reading input from stdin as explained in the edited answer.

Is this answer valid, since you have to use " around the input string?

@rturnbull I don't see why not. Wrapping every entry with quotes and pressing enter would yield the equivalent result (e.g.: "Hello world" => enter => "-wo" => enter => "-ld" => enter =>  "+Ea" => enter =>"+th") which is usually how strings are read anyways.

Right, but the input in the challenge specification in the OP does not include quotes.

@rturnbull I understand your point but simply including quotes does not invalidate the input (see other answers). However, one could argue that input has to be on the form: c("Hello world", "-wo -ld", "+Ea +th") such that one has to split the two last elements on white space. It seems unnecessary to me thoguh but I will of course update the answer if that's required. OP did not complain about the test suite given which uses same input vector, albeit, did not reply again either.

Yeah it's really up to the OP! I personally like your answer as-is, but I was worried that it might be invalid. Looking at answers for other languages it seems like quotes are pretty accepted. While I have your attention, I think you can golf off 4 bytes by changing l=length(i) to l=length(i)/2 and updating the later references to l.

PHP, 164 Bytes
preg_match_all("#^[^-+]+|-[\S]+|[+][\S]+#",$argv[1],$t);for($s=($a=$t[0])[0];++$i<$c=count($a)/2;)$s=str_replace(trim($a[+$i],"-"),trim($a[$i+$c^0],"+"),$s);echo$s;

Vim, 25 bytes
qq+dE+r-PdiW:1s<C-R>"-g<CR>@qq@q
Assumes input in this format:
mississippi
-is -i
+lz +p

+dE+r-PdiW: Combines - and + into single register, with the + turned into a -.
:1s<C-R>"-g: Uses the register as a code snippet, inserted directly into the :s command, with - as the separator.

Haskell, 85 78 bytes
import Data.Lists
g=map tail.words
a#b=foldl(flip$uncurry replace)a.zip(g b).g

Usage example: ("mississippi" # "-is -i") "+lz +p" -> "mlzslzspppp".
How it works:
g=map tail.words              -- helper function that splits a string into a
                              -- list of words (at spaces) and drops the first
                              -- char of each word

                zip(g b).g    -- make pairs of strings to be replaced and its
                              -- replacement
foldl(flip$uncurry replace)a  -- execute each replacement, starting with the
                              -- original string
                              -- -> "flip" flips the arguments of "uncurry replace"
                              --           i.e. string before pair of replacements
                              -- "uncurry" turns a function that expects two
                              --           lists into one that expects a list of pairs

Edit: @BlackCap found 6 bytes to save and I myself another one.

6 bytes: import Data.Lists;a#b=foldl(uncurry replaceflip)a.zip(g b).g;g=map tail.words

@BlackCap: Nice, thanks!  No need to make flip infix. Standard prefix is one byte shorter.

Convex, 19 bytes
¶:äz{S*"-+"-ä~@\ò}/

Try it online!

Python 3, 93 byte
def f(s):
  s,m,p=s
  for n,o in zip(m.split(),p.split()):s=s.replace(n[1:],o[1:])
  return s

Try it online!
Input is a list with strings, replacement strings are space separated.
Example input:
['mississippi','-is -i','+iz +p']

Are you able to add a test suite link, please?

Link provided and also reduced size a little.

PowerShell v2+, 90 bytes
param($a,$b,$c)-split$b|%{$a=$a-creplace($_-replace'-'),((-split$c)[$i++]-replace'\+')};$a

Takes input as three arguments, with the - and + strings space-separated. Performs a -split on $b (the -split when acting in a unary fashion splits on whitespace), then loops |%{...} through each of those. Every iteration we're removing the -, finding the next [$i++] replacement string and removing the + from it, and using the -creplace (case-sensitive replacement) to slice and dice $a and store it back into $a. Then, $a is left on the pipeline and output is implicit.
PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'mississippi' '-is -i' '+iz +p'
mpzspzspppp

PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'Hello world' '-wo -ld' '+Ea +th'
Hello Earth

PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'Hello World' '-wo -ld' '+Ea +th'
Hello Worth

PHP, 106 bytes
for($s=($v=$argv)[$i=1];$i++<$n=$argc/2;)$s=str_replace(substr($v[$i],1),substr($v[$n+$i-1],1),$s);echo$s;

straight forward approach. Run with php -r ' <arguments>.


text:
Nest a string inside an array n times
You must produce a function which nests a string s inside an array, n times
>>> N("stackoverflow",2)
[['stackoverflow']]

Parameters:

s - An ascii string
n - An integer >= 0

Rules

Shortest code wins.
The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases
>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]

Inspired by: Nesting a string inside a list n times ie list of a list of a list

Does the output have to be a list, or can it be a string representing that list?

Can we take the parameters in any order?

@SocraticPhoenix I think unless explicitly forbidden, yes - you can take the input in any reasonable format (which would include taking the two as a list too I believe). Maybe someone more experienced can point to a relevant meta post.

Will the string ever include an escaped "? E.g. N("stack\"overflow",5)

@Riley It could contain any ascii character

@SocraticPhoenix Should be in the order in the question

@Qwerp-Derp Should be a list

Lists don't exist in in some languages. In one of those can I output a string  instead?

@Riley What about an array, if not then a string

I have a solution in sed where a string is the only option.

Jelly, 2 bytes
W¡

Slightly confusing, since: (1) Jelly has no strings, only lists of characters; and (2); the output wont show the nesting. To see that this actually is doing what is asked look at a Python string representation of the result with:
W¡ŒṘ

An extra pair of [] will be present since the string itself will be a list of characters. For example
How?
W¡ - Main link: s, n
W  - wrap left, initially s, in a list
 ¡ - repeat previous link n times

The proof-of-concept code adds:
W¡ŒṘ - Main link: s, n
  ŒṘ - Python string representation

Better output representation

"Better" in that it looks like strings are being used... it does not show that a list of characters is actually being used though.

Java and C#, 62 bytes
Object f(String s,int n){return n<1?s:new Object[]{f(s,n-1)};}

Should work without modification in both Java and C#.

Smart! +1 I was trying to get it to work in Java by nesting a String-array, which didn't really work out. Using an Object as return type and nest it in an Object[] is just the solution required for this challenge, since Object[] (or any array) is also an Object themselves. Nice one.

05AB1E, 3 bytes
Code
`F)

Explanation
`   # Flatten the input array on the stack.
 F  # Element_2 times do:
  ) # Wrap the total stack into a single array.

This means that this also works for the 0-testcase, since the string is already on the stack.
Try it online!

JavaScript (ES6), 20 bytes
d=>g=n=>n--?[g(n)]:d

Although people normally nag me to curry my functions for the 1-byte saving, this is a case where it actually contributes to the solution.

Great use of currying. I think you can make it slightly more readable: d=>g=n=>n?[g(n-1)]:d

Mathematica, 13 bytes
List~Nest~##&

CJam, 7 6 bytes
{{a}*}

Online interpreter
This is an unnamed function that takes its arguments from the stack as S N, S being the string and N being the wraps. You can execute it with the ~ operator, meaning eval.
Explanation:
{{a}*}
{      Open block    [A B]
 {     Open block    [A]
  a    Wrap in array [[A]]
   }   Close block   [A B λwrap]
    *  Repeat        [A:wrap(*B)]
     } Close block   ["S" N λ(λwrap)repeat]

Just use an unnamed block to avoid the awkward input format {{a}*} or {'a*~}.

@MartinEnder I'm afraid it would take bytes, though, and I think that input format is 100% acceptable. It's just a list, and I think there is no restriction as to how those two parameters are entered. Also, I never named the block.

I don't know what you mean about the bytes? Both of those solutions are only 6 bytes.

@MartinEnder Oh, were these whole solutions? I thought you were talking about extending my program, but you just converted it to a function? Well, that changes the whole point. I'm a newbie at CJam/GolfScript/Pyth. I prefer the first one because it's more comprehensible (repeat {a} n times) instead of the second one (produce a string of n as and execute it).

Javascript ES6, 23 bytes
Recursive function

f=(a,i)=>i?f([a],--i):a

console.log(f("stackoverflow",0))
console.log(f("stackoverflow",1))
console.log(f("stackoverflow",2))
console.log(f("stackoverflow",5))

Currying results in the same length
f=a=>i=>i?f([a])(--i):a

Brachylog, 10 bytes
tT,?h:T:gi

Try it online!
Explanation
tT,            T is the integer (second element of the Input)
   ?h:T:g      The list [String, T, built-in_group]
         i     Iterate: Apply built-in_group T times to String

This would be 3 bytes if it wasn't bugged. Here we need all this to get the list [String, T, built-in_group] even though [String, T] is already our input.
Unfortunately :g directly results in [[String, T], built-in_group], which is not recognized properly by i because the integer T is inside the first list.

MATL, 6 bytes
ji:"Xh

This produces a nested cell array as the output. With MATL's default display, however, you can't necessary see that's what it is since it won't show all of the curly braces. The demo below is a slightly modified version which shows the string representation of the output.
ji:"Xh]&D

Try it Online
Explanation
j       % Explicitly grab the first input as a string
i       % Explicitly grab the second input as an integer (n)
:"      % Create an array [1...n] and loop through it
    Xh  % Each time through the loop place the entire stack into a cell array
        % Implicit end of for loop and display

Pyke, 3 bytes
V]1

Try it here!

Python, 32 bytes
N=lambda s,n:n and[N(s,n-1)]or s

PHP, 60 Bytes
for($r=$argv[1];$i++<$argv[2];)$r=[$r];echo json_encode($r);

48 Bytes if it looks only like the task
for($r=$argv[1];$i++<$argv[2];)$r="[$r]";echo$r;

I think a direct rewrite of the question owner's own Python answer is still the shortest in PHP too: function f($s,$n){return$n?[f($s,$n-1)]:$s;}.

print_r() and, if you don't like that option, serialize() are both shorter than json_encode()ing it while differentiating the output.

BTW, that lonely ') at the end of code looks strange.

@manatwork Copy and Paste error Thank You

Pyth, 3 bytes
]Fw

Permalink
This will output something like ...[[[[['string']]]]].... It will not quote for zero depth: string.
Explanation:
]Fw
   Q Implicit: Eval first input line
]    Function: Wrap in array
  w  Input line
 F   Apply multiple times

If you want quoting on zero depth, use this 4-byte solution instead (explanation):
`]Fw
    Q Implicit: Eval first input line
 ]    Function: Wrap in array
   w  Input line
  F   Apply multiple times
`     Representation

Ruby: 23 bytes
->n,s{n.times{s=[s]};s}

This is updated to make it a callable Proc rather than the original snippet. I'd be interested to know whether there's a way to have s implicitly returned rather than having to explicitly return it.

Generally your "a few more words" should be an explanation of how your code works. But it's a good answer nonetheless.

“You must produce a function” This is a code snippet. Unless explicitly specified otherwise, input and output has to be handled explicitly by the code or implicitly by the interpreter if it has such feature. You can not expect some global variables to be set and you can not just leave the result in some global variables.

Welcome to PPCG! All answers should be callable functions or full programs, though. In your case, the shortest fix would be to use an unnamed function like ->s,n{...}.

@wizzwizz4, and Martin, thank you for your encouragement and helpful input, I have learned something and will update. manatwork, I've got thick skin and have plenty of points on SO but you know that blunt statements like that scare newbies away from Stack sites and intimidate them. Seems a shame no?

C, 44 bytes, 41 bytes
int*n(int*s,int a){return a?n(&s,a-1):s;}

You can test it by doing the following:
int main(void) {
    char* s = "stackoverflow";

    /* Test Case 0 */
    int* a = n(s,0);
    printf("'%s'\n", a);

    /* Test Case 1 */
    int* b = n(s,1);
    printf("['%s']\n", *b);

    /* Test Case 2 */
    int** c = n(s,2);
    printf("[['%s']]\n", **c);

    /* Test Case 3 */
    int*** d = n(s,3);
    printf("[[['%s']]]\n", ***d);

    /* Test Case 4 */
    int********** e = n(s,10);
    printf("[[[[[[[[[['%s']]]]]]]]]]\n", **********e);

    return 0;
}

The output:
'stackoverflow'
['stackoverflow']
[['stackoverflow']]
[[['stackoverflow']]]
[[[[[[[[[['stackoverflow']]]]]]]]]]

Of course, you'll get warnings. This works on gcc on bash on my Windows machine (gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3), as well as on a true Linux machine (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)).

Not sure about other compilers, but int*n(s,a)int*s;{return!a?s:n(&s,a-1);} works with gcc.

It segfaults for cc -v -> Apple LLVM version 8.0.0 (clang-800.0.38).

I have changed n(s,3); to n(s,6); and then to n(s,0); and found your solution incorrect. Check and fix it

It seems that your n function does not output [ and ], and solution require some update

Can you drop the ! from the ternary condition and switch the order of s and n(&s,a-1) to save a byte?

@VolAnd When you call n(s,6), you have to change *** to ****** in the variable declaration and use. This is needed exactly because the function does what it is expected to do: nest the string into an array several (here: 6) times. Of course you would still get three levels of [] because they are hardcoded. I think the program shouldn't output them at all. This challenge is not about brackets, it is about nesting. Some languages print arrays with brackets, C hasn't any builtin function to print them at all. So what? It is not needed here.

Can you drop the spaces after the * in the function signature?

@VolAnd I added more test cases - you can't change n(s,3) to n(s,6) without changing the variable type. Since n(s,6) would create an "array" (really just 6 nested pointers), you need to assign it to a type of int******, and then dereference that value 6 times to get the true value.

@VolAnd The function doesn't need to output anything - it just has to return a nested array (or in this case, a nested pointer).

@Riley Thanks! Just updated the count :)

@QPaysTaxes Thanks! Just updated the count :)

k, 3 bytes
,:/

Taken as a dyadic function, / will iteratively apply the left-hand function ,: (enlist) n times to the second argument.
Example:
k),:/[3;"hello"]
,,,"hello"

Thunno, \$ 5 \log_{256}(96) \approx \$ 4.12 bytes
s{KZO

Attempt This Online!
If the inputs could be taken in any order, the leading s could be dropped.
Explanation
s{KZO  # Implicit input
s      # Swap so the number is on top
 {K    # Loop input number of times:
   ZO  # Wrap in a list
       # Implicit output

Ruby, 25 characters
Rewrite of jamylak's Python solution.
f=->s,n{n>0?[f[s,n-1]]:s}

Sample run:
irb(main):001:0> f=->s,n{n>0?[f[s,n-1]]:s}
=> #<Proc:0x00000002006e80@(irb):1 (lambda)>

irb(main):002:0> f["stackoverflow",0]
=> "stackoverflow"

irb(main):003:0> f["stackoverflow",1]
=> ["stackoverflow"]

irb(main):004:0> f["stackoverflow",5]
=> [[[[["stackoverflow"]]]]]

C# 6, 50 bytes
dynamic a(dynamic s,int n)=>n<2?s:a(new[]{s},n-1);

Shouldn't it be n<1? Also -2 bytes if you use object instead of dynamic.

Ruby, 24 bytes
f=->*s,n{s[n]||f[s,n-1]}

Called the same as in manatwork's answer, but a weirder implementation. *s wraps the input (a possibly-nested string) in an array. Then if n is zero, s[n] returns the first element of s, turning the function into a no-op. Otherwise, it returns nil since s will only ever have one element, so we pass through to the recursive call.

V, 6 bytes
Àñys$]

Try it online!
Explanation:
À      "Arg1 times
 ñ     "repeat:
  ys$  "surround this line
     ] "with square brackets

Perl 6, 23 bytes
{($^a,{[$_]}...*)[$^b]}

Expanded:
{ # bare block lambda with two placeholder parameters ｢$a｣ and ｢$b｣
  (

    # generate Sequence

    $^a,       # declare first input
    { [ $_ ] } # lambda that adds one array layer
    ...        # do that until
    *          # Whatever

  )[ $^b ]     # index into the sequence
}

Perl never ceases to amaze me with its syntax

Agda, 173 bytes
Since the return type of the function depends on the number given as argument, this is clearly a case where a dependently typed language should be used. Unfortunately, golfing isn't easy in a language where you have to import naturals and lists to use them. On the plus side, they use suc where I would have expected the verbose succ. So here is my code:
module l where
open import Data.List
open import Data.Nat
L : ℕ -> Set -> Set
L 0 a = a
L(suc n)a = List(L n a)
f : ∀ n{a}-> a -> L n a
f 0 x = x
f(suc n)x = [ f n x ]

(I hope I found all places where spaces can be omitted.) L is a type function that given a natural n and a type a returns the type of n times nested lists of a, so L 3 Bool would be the type of lists of lists of lists of Bool (if we had imported Bool). This allows us to express the type of our function  as (n : ℕ) -> {a : Set} -> a -> L n a, where the curly braces make that argument implicit. The code uses a shorter way to write this type. The function can now be defined in an obvious way by pattern matching on the first argument.
Loading this file with an .agda extension into emacs allows to use C-c C-n (evaluate term to normal form), input for example f 2 3 and get the correct answer in an awkward form: (3 ∷ []) ∷ []. Now of course if you want to do that with strings you have to import them...

Just remembered that I could write → instead of ->, but of course that increases the size of an UTF-8 encoded file.

My ugly translation of this into Haskell is somewhat shorter. I have to stick to manual unary to keep it short.

Japt, 8 bytes
@[X]}gNÅ

Try it

R, 39 40 bytes
EDIT: Fixed the n=0 issue thanks to @rturnbull.
Function that takes two inputs s (string) and n (nestedness) and outputs the nested list. Note that R-class list natively prints output differently than most other languages, however, is functionally similar to a key/value map (with possibly unnamed keys) or a list in python.
f=function(s,n)if(n)list(f(s,n-1))else s

Example
> f=function(s,n)if(n)list(f(s,n-1))else s
> f("hello",3)
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "hello"

> # to access the string nested 5 times in the "list-object" named "list" we can do the following
> list = f("nested string",5)
> list[[1]][[1]][[1]][[1]][[1]]
[1] "nested string"

Very nice! It doesn't give the desired output for n=0, though. Before I saw your answer, I came up with a recursive solution which can deal with n=0, but it's 1 byte longer than your solution (40 bytes): f=function(s,n)if(n)list(f(s,n-1))else s

@rturnbull You're of course right. Your solution is much more elegant in my opinion and I totally forgot about the n=0 case. However, your solution is actually 38 bytes excluding the naming of the function and hence shorter. Great catch

Since it's a recursive function it must be named, unfortunately! (Otherwise it can't interpret the f(s,n-1) call inside of it.) Recursive anonymous functions are not possible in R, as far as I know.

@rturnbull You're again right. Updating the answer.

A year later, I've golfed off another byte: f=function(s,n)'if'(n,list(f(s,n-1)),s).

Jellyfish, 8 bytes
p\Ai
 ;i

Try it online!
Unary ; wraps its argument in a list. Binary \ on a function and a value n iterates that function n times.

PHP, 44 bytes
function n($s,$n){return$n?n([$s],--$n):$s;}

nothing sophisticated, just a recursive function

Haskell, 40 38 bytes
data L=N[Char]|C L
f 0=N
f n=C. f(n-1)

Haskell's strict type system prevents returning different types (Strings vs. List of Strings vs. List of List of Strings,...), so I have to define my own type that accommodates all those cases. The main function f recursively calls n times the constructor C for nesting and N for the base case.
Usage example (with deriving (Show) added to the new data type to be able to print it): f 4 "codegolf" -> C (C (C (C (N "codegolf")))).
Edit: @Christian Sievers saved 2 bytes by rewriting the function in a point-free style for the string argument. Thanks!

Of course Haskell's lists can be nested, but a function cannot return a string for one value and a list of lists of strings for another value of the same type. Golfing the additional deriving clause: the parens aren't needed. - Not sure if it's okay to only nest the C constructor which isn't list-like. My very similar attempt was based on a data type defined as data  D x=J x|L[D x].

If you reverse the order of the arguments and don't use an infix operator, you don't need to mention the second argument: f 0=N;f n=C. f(n-1)

@ChristianSievers: yes, you're right, my explanation about nested lists was not accurate - I've changed it. Regarding list-likeness: I think my data structure is list-like. Compare a native Haskell list 1:(2:(3:([]))) with C (C (C (N "codegolf"))). C is cons (:), N is nil ([]).

C doesn't cons, it only embeds, your data type can't express [["a","b"],["c"]]. But maybe that is fine as this problem only needs singletons.  - f n=... isn't point-free. Point-reduced?

You spend 19 characters defining your data type.  Wouldn't it be more sensible to use an existing type (e.g. Either) even if it meant the constructors were a little more verbose?

@PeriataBreatta: no, that's not possible. You can nest Either, but the nesting level would be fixed for function f. For example, the type for a nesting level of 2 Left (Left (Right "golf")) is Either (Either (Either a String) b) c) which is different from level 1 Left (Right "golf") :: Either (Either a String) b. With my custom data structure the type of f is L, regardless of the nesting level.

Hmm.  I was thinking that the type of the function would be t where t = Either String [t], but it seems that is explicitly caught and produces a specific error when you try to do it. :(

Python 2, 32 bytes
lambda s,n:eval('['*n+`s`+']'*n)

Puts n open brackets before the string and n close brackets before it, then evals the result. If a string output is allowed, the eval can be removed.

tinylisp (repl), 34 bytes
(d F(q((S N)(i N(F(c S())(s N 1))S

Defines a function F. Technically, tinylisp doesn't have strings, but this code will work for any data type it's given.
Ungolfed (key to builtins: d = define, q = quote, i = if, c = cons, s = subtract):
(d nest
 (q
  ((item number)
   (i number
    (nest (c item ()) (s number 1))
    item))))

Example usage:
tl> (d F(q((S N)(i N(F(c S())(s N 1))S
F
tl> (F 2 3)
(((2)))
tl> (F () 1)
(())
tl> (F (q Hello!) 7)
(((((((Hello!)))))))
tl> (F c 3)
(((<builtin function tl_cons>)))

Clojure, 24 bytes
#(nth(iterate list %)%2)

Clojure is somewhat competitive here. iterate creates a sequence of x, (f x), (f (f x)) ..., nth returns needed element.
See it online: https://ideone.com/2rQ166

Scala, 43 bytes
(s:Any,n:Int)=>((1 to n):\s)((_,x)=>Seq(x))

Explanation:
(s:Any,n:Int)=>   //define a function
  (
    (1 to n)      //create a range with n elements
    :\s           //foldRight with s as a start value
  )(              //using the following function:
    (_,x)=>Seq(x) //ignore the value of the range and wrap the accumulator in a list
  )

Racket 83 bytes
(for((c n))(set! s(apply string-append(if(= c 0)(list"[\'"s"\']")(list"["s"]")))))s

Ungolfed:
(define (f s n)
  (for ((c n))
    (set! s (apply string-append
                   (if (= c 0)
                       (list "[\'" s "\']")
                       (list "[" s "]"))
                   )))
  s)

Testing:
(f "test" 3)

Output:
"[[['test']]]"

Actually, 4 bytes
Input is string then n. Golfing suggestions welcome. Try it online!
`k`n

Ungolfing
          Implicit input string, then n.
`...`n    Run the function n times.
  k         Wrap the stack in a list.
          Implicit return.

APL (Dyalog), 6 bytes
(⊂⍣⎕)⎕

Try it online!
(note: the number of leading spaces in the output show how much the string is nested)
Explanation
⎕            take the string as input
  ⍣⎕         take the number (let's call it n) as input and n times
⊂             nest
             the string

Might want to unhighlight your explanation

Save a byte: ⊂⍣⎕⊢⎕

Common Lisp, 43 bytes
(defun f(x n)(if(= n 0)x(list(f x(1- n)))))

Try it online!

Japt, 8 bytes
V´?[ß]:U

Try it online!
Requires the -Q flag in order to output the returned array with the brackets and quotes.

Clojure, 28 bytes
#(nth(iterate list %)%2) is the shortest (already posted) solution, so here is something different:
#(apply comp(repeat % list))

This takes arguments via currying:
(def f #(apply comp(repeat % list)))
((f 3) "test")
; ((("test")))

Add++, 31 bytes
L,$Vd"]"*$"["*B]G$V"'"d@jGbU@jv

Try it online!

Brachylog v2, 2 bytes
g₎

Try it online!
Although I can't think of what subscripting g could hypothetically do other than nesting arrays as it does, it can't be ruled out that getting stuck with a 10-byte solution on this challenge might have influenced it, so here's a version that doesn't use g at all:
Brachylog v2, 3 bytes
∈ⁱ⁾

Try it online!
The main difference between g and ∈ is that g constrains its output to be a single-element list containing its input, while ∈ constrains its output to be any list containing its input--it just so happens that in the absence of backtracking or any prior constraints the simplest list containing its input is the one containing nothing else. The difference which adds a byte is that subscripting g changes how many layers of array the output gets wrapped in, but it's far more useful in every circumstance except this one for ∈ to constrain the index of the input in the output when subscripted instead, so we need to use ⁱ to iterate instead.

Haskell with extensions, 109 bytes
data Q a where E::Q();R::Q n->Q[n]
type family n&a where()&a=a;[n]&a=[n&a]
(#)::a->Q n->n&a
a#E=a
a#R n=[a#n]

Try it online!
Examples
"Hello"#E = "Hello"
"Hello"#R E = ["Hello"]
"Hello"#R(R E) = [["Hello"]]

Explanation
This is based loosely on the Agda solution. Since type literal numbers aren't very nice in Haskell, the numerical argument to (#) is given in unary format. Rather than taking space to define a Nat kind, we use () for zero and [] for successor. The type signature is mandatory thanks to the GADT argument.

Factor, 20 bytes
[ [ 1array ] times ]

Try it online!

1array Create an array with one element from an object.
times Call a quotation a certain number of times.

Vyxal, 3 bytes
$(w

Try it Online!

Arturo, 27 bytes
$[s,n][do.times:n->s:@[s]s]

Try it
Recursion is 2 bytes longer:
f:$[s,n][(0=n)?->s->f@[s]n-1]

JavaScript, 23 bytes
f=(s,c)=>c?[f(s,c-1)]:s

Try it:

f=(s,c)=>c?[f(s,c-1)]:s

console.log(JSON.stringify(f("stackoverflow",0))); // 'stackoverflow'
console.log(JSON.stringify(f("stackoverflow",1))); // ['stackoverflow']
console.log(JSON.stringify(f("stackoverflow",2))); // [['stackoverflow']]
console.log(JSON.stringify(f("stackoverflow",5))); // [[[[['stackoverflow']]]]]

20 bytes. Note, though, that your solution is identical to Neil's.

@Shaggy I saw Neil's answer but I think it doesn't meet the requirements because it requires two arguments to be passed, like (string,number) rather than (string)(number)

Thunno 2, 3 bytes
s{W

Attempt This Online!
If we could take input the other way round, the s could be dropped.
Explanation
s{W  # Implicit input
s    # Swap so the number is on top
 {   # And, this many times, repeat the following:
  W  #  Wrap TOS (initially string input) in a list
     # Implicit output

GNU sed 44 Bytes
Includes +1 for -r
s/(.*),(1*)/\2"\1"\2/
:;s/1(.*".*)1/[\1]/;t

Try it online!
Takes the depth to nest the string as a unary number based on this consensus
Example:
$ echo 'stack"o,verflow,1111' | sed -rf nest.sed
[[[["stack"o,verflow"]]]]

Python 2, 42 bytes
def f(a,b):
 if b:f([a],b-1)
 else:print a

Recursive function

Did you see the shorter version of this that was posted by the OP?

@Jonathan - yes I did after I had posted. Should I remove mine?

It's up to you. I'm not downvoting it.

Thanks. Guess I'll leave it as an alternative until it gets downvoted.

Postscript, 24 bytes (11 bytes in binary encoding)
{{1 array astore}repeat}

Takes arguments on the stack, n at top-of-stack and s under it
The binary encoding is
{{1\x92\x09\x92\x0b}\x92\x83}

Groovy, 33 37 34 Bytes
Groovy's inject method is weird, but essentially is the fold method.
{a,n->(0..<n).inject(a){i,r->[i]}}

Edited to make it valid for n=0 using ternary.
Edited again with ..< to make the integer range an empty set when n=0 thanks to @manatwork.

Is the wrapping count correct? I'm afraid it adds and extra layer. Anyway, {a,n->(0..<n).inject(a){i,r->[i]}} seems enough: http://pastebin.com/GwpBQd1A

@manatwork Ahhh... THAT IS AWESOME. I've never seen that notation for integer ranges!

RProgN, 22 Bytes
►xX=x=1\_1:[s]xPX=}x

Explination
►xX=x=1\_1:[s]xPX=}x
►                   # Spaceless segment.
 xX=                # Assign 'x' to X
    x=              # Assign the string input to 'x'
      1\_1:       } # Push 1, flip it under the number input Then floor it, converting it from a string(?) to an integer, push another one, execute it as a for loop (i=1; i<=INPUT; i+=1)
           [            # Pop the incrementer of the for loop. We don't need it here.
            s]      # Push a new stack, then clone it.
              xP        # Push x, (Either the current bottom stack or the string), Push it to the new stack
                X=  # Assign it back to 'x' (This is why we set X to x)
                   x    # Push x to the reg stack. Implicitly return.

Easy enough, fun to finally get to use multi-dimensional stacks.
Try it Online!

Lua, 47 Bytes
function(a,b)for _=1,a do b={b}end return b end

A huge amount of this is boiler plate, because of Lua.
for _=1,a do b={b}end is the real meat.

Lithp, 48 Bytes
#S,N::((if (== 0 N) (S) ((list (n S (- N 1))))))

Can be assigned to a variable or function definition like so:
(def n #S,N::((if (== 0 N) (S) ((list (n S (- N 1)))))))

And called:
(print (inspect (n "stackoverflow" 5)))

[[[[["stackoverflow"]]]]]

(inspect is used because JS' print method stops if the object is too deep.)

Julia 77 bytes
U(n)=Val{n}
g(::U(1),s)=[s]
g{n}(::U(n),s)=[g(U(n-1)(),s)]
f(n,s)=g(U(n)(),s

Convex, 4 bytes
'a*~

Try it online!

Haskell, 41 bytes
Actually, it can be done with Haskell's standard list type. Here is how:
n?s|m<-([1..n]>>)=read$m"["++show s++m"]"

m is a local helper function that repeats a string n times. It is used in ? to prepend n [ and append n ] to the result of show s, which for a string s is that string surrounded by quotation marks and with its possible own quotation marks escaped. This is then parsed by read which tries to return the type at which the result is used. The infered type of ? is (Enum a2, Num a2, Read a, Show a1) => a2 -> a1 -> a. It could be specialized by setting a1 to String and a2 to Integer or Int, removing all but one of the constraints. But of course it is golfier to let the compiler infer a complicated type than to explicitely state a simple one.
Now simply calling the function in the interpreter gives an ambigous type variable error, but we can state the expected type or use the value in a way that gives enough information to infer the type:
Prelude> 2 ? "codegolf" :: [[String]]
[["codegolf"]]
Prelude> putStrLn $ 2 ? "hi" !! 0 !! 0
hi
Prelude> [[["test"]]] ++  (3 ? "hi")
[[["test"]],[["hi"]]]
Prelude> map(map("a":)) $  [2 ? "x" ++ 2 ? "y"] ++ 3 ? "z"
[[["a","x"],["a","y"]],[["a","z"]]]
Prelude> let x=(2 ? "golf") in (x,"code"++x!!0!!0)
([["golf"]],"codegolf")
Prelude> 0 ? "hi" ++ "!"
"hi!"

There is no reason to only use strings:
Prelude> map(map not) $ 2 ? False
[[True]]

Python 3, 34 bytes
f=lambda s,n:n and f([s],~-n)or s

Try it online!
This might be about as short as I can make it.
Turns out, if you look at super old submissions, you can shave bytes off that you didn't see before. Huh.

Proton, 23 bytes
f=s=>n=>n?f([s])(n-1):s

Try it online!

Tcl, 42 bytes
proc N s\ t {time {set s \{$s\}} $t;set s}

Try it online!

Recursive approach did not render shorter: 50 bytes proc N s\ t {expr {$t?"\{[N s [expr $t-1]]\}":$s}} https://tio.run/##K0nO@f@/oCg/WcFPoThGoUShOrWioEihWqXEXimmOhooqBANFlEp0TWMjY2pVbJSKa6t/V9QWgKUAUqXJCZn55elFqXl5JcrGMf@BwA

Axiom, 60 43 bytes
f(a:Any,c:NNI):Any==(c<1=>a;f(copy[a],c-1))

Possibly one can use less characters but this is one here compile smoothly without warning... I don't know too if it is right copy one parameter in a recursive function but this silent all warning...

Symbolic Python, 31 bytes
__('_=_[_>_]'+';_=[_]'*_[_==_])

Try it online!
__('_=_[_>_]'                       Var1 = input string
             +'     '*_[_==_])      Nest depth times do:
               ;_=[_]                   Make Var1 a list containing itself

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:
Display a Connect Four game
Connect Four is a game where two players take turns to drop disks into columns of a vertically mounted grid, and attempt to connect four disks orthogonally or diagonally. When a column is chosen, the disk falls to the lowest empty position in that column, so any game may be completely specified by the size of the grid and the sequence of columns chosen. The task is to generate the configuration of the grid given this information.
Input

Width w and Height h of the grid, both positive integers.
Sequence of columns c1, c2, ..., cn chosen by the players, in any reasonable format (list, array etc.); either 0-based (0 to w-1) or 1-based (1 to w) indexing can be used.

It may be assumed that all of the column numbers lie within the grid (so the sequence won't contain -3 or w+50) and that any column number appears at most h times in the sequence (so a column can't be chosen once it is full).
Note that the sequence of columns may not constitute a complete game, nor a legal game. For instance, the players could opt to continue playing even after a player has connected four disks.
Output

Any reasonable representation of the resulting state of each position in the grid, either "occupied by Player 1", "occupied by Player 2", or "empty". Player 1 always moves first.

For example, a string, array, tuple etc. with each position containing one of three symbols (ASCII character, number etc.) representing the state of that position in the grid. The grid may be transposed.
For list/tuple/array outputs, the separator cannot be one of the three representative symbols. For string outputs, trailing spaces at the end of each line are permitted, provided a space is not one of the three representative symbols. Trailing newlines at the very end are permitted.
Test cases
Here, string output is used, with X, O, . denoting "occupied by Player 1", "occupied by Player 2", "empty".
IN: Width 1 Height 1 Sequence (empty sequence)
OUT:
.

IN: Width 7 Height 6 Sequence 4 4 5 5 6 7 3 [1-based]
                              3 3 4 4 5 6 2 [0-based]
OUT:
.......
.......
.......
.......
...OO..
..XXXXO

IN: Width 5 Height 5 Sequence 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 [1-based]
                              0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 [0-based]
OUT:
XOXOX
OXOXO
XOXOX
OXOXO
xOXOX

IN: Width 4 Height 4 Sequence 3 3 2 4 3 2 4 2 2 3 4 4 1 1 1 1 [1-based]
                              2 2 1 3 2 1 3 1 1 2 3 3 0 0 0 0 [0-based]
OUT:
OXOO
XOXX
OOOX
XXXO

IN: Width 10 Height 10 Sequence 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 10  [1-based]
                                0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0  9 0  9  [0-based]
OUT:
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X........O
XOOOOOOOOO

Shortest code in bytes wins.

A representation of the resulting state, with rows and columns switched, would be clearly understandable and reasonable, and SO easier to obtain

Does it matter which player starts the game?

@edc65 You may print a transposed board, if that's what you are asking.

@Shebang No it doesn't matter. Player 1 always moves first, label his disks with the same symbol.

@lastresort Your first and last sentence seem to contradict. So any game can start with either O or X moving?

@Shebang Only consider Player 1 moving first. If you choose to label Player 1's disks with X, then the lowest position in the first column chosen is always marked X (unless it's an empty game, where no columns are chosen).

Pyth, 19 bytes
m.[2vz%R2fq@QTd_UQE

Try it online.
Takes input as c,o,l,s\nheight\nwidth, 0-indexed. Outputs a list of columns (transposed), using 012 for player 1, player 2, empty respectively.

Vim, 34 bytes
@wO-<Esc><C-V>(d@hpqq<C-O>+D@"G+bs<C-R>=!@.<CR><Esc>@qq@q
Input is width in the "w register, height in the "h register, and the 1-indexed moves in the buffer, one per line. Output is a transposed grid with - as blank, 1 as player 1, and 0 as player 2 (with a bunch of newlines at the end).
To clarify, if you want Height 6, Width 7: type qh6qqw7q before starting.

@wO-<Esc><C-V>(d@hp: Use the height and width in the registers to make a transposed grid of -s. Note that ( is run from the last line of the grid, one above the moves. This sets up the jump list.
<C-O>+D@"G: The <C-O> uses the jump list to move back to before the last G, always to the line above the next number. @"G moves to the line number indicated by the deleted text. + not only moves the cursor, but it's the failure point; when it runs on the last line, the macro dies.
+b: This maneuver goes to the first - in the line, even if it's the first character. (f- would go to the second character if the line was still all -s.)
s<C-R>=!@.: Replaces a - with the last insert @., but NOTted. First time through, the previous insert of - will NOT to 1 because that's the way Vim is. After that, it will alternate between 0 and 1.

Example
Start with the moves in the buffer:
4
4
5
5
6
7
3

Make sure you're on line 1 with gg, clear "q with qqq, set up the registers for width 7, height 6 with qw7qqh6q. Then run the solution above and get the following output (with newlines at the end):
------
------
1-----
10----
10----
1-----
0-----

Python 2, 91 88 bytes
w,h,s=input()
i,x=0,['']*w
for c in s:x[c]+='XO'[i%2];i+=1
for c in x:print(c+'.'*h)[:h]

Since transposed is fine, this prints the board sitting on its right hand side.
repl.it

The XO alternation can be done directly as for p,c in zip('XO'*w*h,s):x[c]+=p .

Python 2, 143 131 107 Bytes
This doesn't use any real fancy tricks, except list transposition to make index access easier since we can print the board transposed. Definitely not done with this just yet. Moves are taken as 0-based numbers. Byte count comes before commenting.
Jonathan Allan had a better approach to building the board, mine is improved slightly since the slicing is a bit shorter [-j:] -> [:j] and the list comprehension helps shorten printing.
i,j,k=input()                                     # split up the input
t=0                                               # keep track of whose move it is
g=i*['']                                          # board init
for b in k:g[b]+='XO'[t%2];t+=1                   # read moves sequentially, place pieces
print'\n'.join(''.join((m+'.'*j)[:j])for m in g)  # build the board

Example Input: [7, 6, [3, 3, 4, 4, 5, 6, 2]]
Example Output:
......
......
X.....
XO....
XO....
X.....
O.....

Try it online or view all test cases.

The ''.join is redundant, if you then move the print into the loop, you'll have the same as me.

JavaScript (ES6), 62 69
Edit 7 bytes saved thx @Arnauld
I have used this kind of string representation when logging the board status in my connect four player. It's short coded and easy to understand at first sight.
Input is 0 based
(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`

More in line with the OP examples, this is 93 bytes
(w,h,s)=>s.map((v,i)=>r[v]+=i%2,r=Array(w).fill(``))&&r.map(r=>r+Array(h+1-r.length)).join`
`

(note: here the fill``  trick won't work)
Output for [7, 6, [3, 3, 4, 4, 5, 6, 2]]
,,,,,,
,,,,,,
0,,,,,
01,,,,
01,,,,
0,,,,,
1,,,,,

Test

f=(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`

console.log=s=>O.textContent+=s+'\n'

;[
  [1, 1, []]
, [7, 6, [3, 3, 4, 4, 5, 6, 2]]
, [5, 5, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]]
, [4, 4, [2, 2, 1, 3, 2, 1, 3, 1, 1, 2, 3, 3, 0, 0, 0, 0]]
].forEach(t=>{
  var w=t[0],h=t[1],s=t[2],r=f(w,h,s)
  console.log(w+' '+h+' ['+s+']\n'+r+'\n')
})

JavaScript (ES6), 121 bytes
(w,h,a,r=Array(w).fill``)=>a.map((c,j)=>r[c]+="XO"[j%2])&&[...Array(h)].map((_,i)=>r.map(s=>s[h+~i]||`.`).join``).join`\n`

0-indexed. I wanted to see how well I could match the example output, but most of the code seems to be taken up by the rotation.

Scala, 122 bytes
def%(w:Int,h:Int,m:Int*)=((Seq.fill(w)(Nil:Seq[Int]),1)/:m){case((a,p),x)=>(a.updated(x,a(x):+p),-p)}._1.map(_.padTo(h,0))

Ungolfed:
def f(w:Int,h:Int,m:Int*)=
  m.foldLeft((Seq.fill(w)(Nil:Seq[Int]),1)){
    case((res,player),x)=>
      (res.updated(x,res(x):+player), -player)
  }._1.map(_.padTo(h,0))

Explanation:
def%(w:Int,h:Int,m:Int*)=        //define a method
  (
    (                            //with a tuple of
      Seq.fill(w)(Nil:Seq[Int]),   //a Sequence of w empty sequences
      1                            //and 1
    )                            //as a start value,
    /:m                          //foldLeft the moves
  ){                             //using the following function,
    case((a,p),x)=>                //which takes the result, the player and the x coordinate
      (                            //return a tuple of
        a.updated(x,a(x):+p),        //the seq with index x with p appended
        -p                           //and the other player
      )
  }._1.map(                      //take the resulting seq and foreach column
    _.padTo(h,0)                 //append 0 until the length is h
  )

Returns a sequence of the columns in bottom-to-top order.
The players are represented as -1 and 1, empty cells are 0.

Java 7, 209 bytes
Not very inspiring.Simple and plain solution.
char[][]f(int w,int h,int[]a){char[][]b=new char[h][w];for(char[]r:b)Arrays.fill(r,'.');for(int l=a.length,i=l-1,j,c=0;i>-1;b[h-c-1][a[i]]=i--%2==0?'X':'O',c=0){for(j=i-1;j>-1 ;)if(a[j--]==a[i])c++;}return b;}

Ungolfed
 char[][] f( int w , int h , int[]a ) {
 char[][] b = new char [h][w];
for ( char[] r : b)
    Arrays.fill( r , '.') ;

for ( int l = a.length,i = l-1 , j , c = 0 ; i > -1 ;
                         b[h-c-1][a[i]] = i--%2 == 0 ? 'X' : 'O', c = 0 ) {
    for ( j = i-1 ; j > -1 ;)
        if ( a[j--] == a[i] )
              c++ ;
      }

return b;
}

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


text:
Image Smoothie!
Input into your program a black and white image. (png, jpg, etc)
Convert the image to a 2D matrix of pixels, where each index is the grayscale value of the image.
Take each index of the matrix and average the 8 pixels around it. Then replace that index with the average.
For example if you had:
120 80  60
20  10  30
40  100 05

If you were finding the average for 10, the result would be 56.875, which is (120,80,60,30,05,100,40,20)/8.
Round to up to the nearest integer (57) and replace the index. The result of this iteration would be
120 80  60
20  57  30
40  100 05

If you are finding the average for a pixel on an edge then only take values that are valid. In the example above if you were finding the average for 20 You would only consider 120, 80, 57, 100, and 40 which is 79.4 rounded to 80.
You may start at any index of the graph but it must be in order. For example you could do
[0][0], [0][1], ... [0][n], then [1][0], [1][1],... [1][n]

Once the averaging is complete, convert the matrix back into a new image.
Display the new image as the output of the program. (Or save it and add it in your solution). The result of your code should be a blurry looking image but much smoother than the original.
Example Input

Example Output

Example Input two

Example Output two

Please provide your code and start and end image results.
Q/A
1Q. If one of the 8 neighbors has already been changed, should the average be calculated based on this new value, or based on the original values? That is, does the order of calculation affect the end result?
1A Yes, You should change each index with new values from any potential indices done before. That is why you need to go left-right, top-bottom etc. In order.
2Q. Could you clarify what is meant by "must be in order"? Does this mean that only raster order/reading order is acceptable? Or does it mean that the order must be the same each time the code is run? Would a spiral be valid? Or a shuffled order that is always the same?
2A. You should go left to right, right to left, top to bottom, or bottom to top. I.E. Do all of the 0th row, do all of the 1st row,... do all of the nth row

If one of the 8 neighbours has already been changed, should the average be calculated based on this new value, or based on the original values? That is, does the order of calculation affect the end result?

Yes each value is based on the previous ones. That is why you need to change them going from one direction to another. and not hop around.

Could you clarify what is meant by "must be in order"? Does this mean that only raster order/reading order is acceptable? Or does it mean that the order must be the same each time the code is run? Would a spiral be valid? Or a shuffled order that is always the same?

You should go left to right, right to left, top to bottom, or bottom to top. I.E. Do all of the 0th row, do all of the 1st row,... do all of the nth row

Are we allowed to take the image as an array of integers?

Yes, that will work

"You may start at any index of the graph but it must be in order" seems to conflict with "2A [...] Do all of the 0th row, do all of the 1st row,... do all of the nth row"

what about edges? should the array indices wrap or should the average be taken from fewer pixels?

@Aaron that case is specified in the description.
"If you are finding the average for a pixel on an edge then only take values that are valid. In the example above if you were finding the average for 20 You would only consider 120, 80, 57, 100, and 40 which is 79.4 rounded to 80."

J, 90 82 bytes
[:((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/(#<@-#\)@,,<

This iterates over pixels from left-to-right, then top-to-bottom.
You can see the progression of values here.
   |. ((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/\. ((#<@-#\)@,,<) 120 80 60 , 20 10 30 ,: 40 100 5
┌──────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┬────────┐
│120  80 60│37  80 60│37  32 60│37  32 24│37  32 24│37  32 24│37  32 24│37  32 24│37 32 24│37 32 24│
│ 20  10 30│20  10 30│20  10 30│20  10 30│44  10 30│44  39 30│44  39 40│44  39 40│44 39 40│44 39 40│
│ 40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│61 100  5│61 38  5│61 38 39│
└──────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┴────────┘

The output for the first sample image is (converting from an array of pixels to a bmp)

Here's code in groovy to change the image into a 2D array (85 bytes, 1 more than you already, jesus.......), {i->(0..i.getWidth()-1).collect{x->(0..i.getHeight()-1).collect{y->i.getRGB(x,y)}}}...... Ha. I concede, you win before I even start.

Can you provide the image before and after?

@jacksonecac Sure, also could you clarify what order (directions to iterate over the pixels) you used for the sample images?

@JonathanAllan Thanks, I've added a simple fix using a permutation that shifts the center to the front so it can be dropped

PHP, 321 bytes
$i=imagecreatefromjpeg($f="96512.jpg");list($w,$h)=getimagesize($f);for($y=$h;$y--;)for($x=$w;$x--;$s=$n=0){for($a=-2;$a++<1;)for($b=-2;$b++<1;)if(false!==($d=imagecolorat($i,$x+$a,$y+$b))){$n++;$s+=imagecolorsforindex($i,$d)[red];}imagesetpixel($i,$x,$y,imagecolorallocate($i,$r=ceil($s/$n),$r,$r));}imagejpeg($i,"b$f");

does the blurring from bottom to top, from right to left.
-2 bytes for a gif or png; could save even more with a shorter file name
and -6 if rounding down was allowed. pity that image processing functions have so long names.
but I´m fine. pretty byte count.

Nice job looks great

PHP, 70 bytes
imagefilter($i=imagecreatefromjpeg($f="i.jpg"),10,0);imagejpeg($i,$f);

Overwrites the original image file. Run with -r.
-2 bytes if you use a gif or png.

I thought PHP might have a built-in for this, and indeed:
10 stands for IMG_FILTER_SMOOTH; and 0 is the weight parameter.
See the GD library source code: This calls gdImageSmooth which calls gdImageConvolution with the requested matrix. I am not sure what it does at the edges; but overall it does the smoothing from top to bottom, from left to right.

Ruby 2.3.1, 338 bytes
->w{d,k=16843008,ChunkyPNG::Canvas.from_file(w);(0..k.height-1).each do |y|;(0..k.width-1).each do |x|;t,i,a=0,0,[[x-1,y-1],[x,y-1],[x+1,y-1],[x-1,y],[x+1,y],[x,y+1],[x,y+1],[x+1,y+1]];a.each do |c|; next unless k.include_xy?(c[0],c[1]);t=t+k.[](c[0],c[1]);i=i+1;end;n=t/i;while(n%d)>0 do;n=n+1;end;k.[]=(x,y,n-1);end;end;k.save("w")}

Uses oily_png/chunky_png for image handling.
Goes left to right, top to bottom doing the averaging.
Since chunky uses integer color values, I'm doing a really, really slow up rounding method to get averaged color values to an actual grayscale value.

Example output(that took a very, very long time):

Ungolfed, slightly modded, and commented
require 'oily_png'
l = -> img {
  time_begin = Time.new
  d = 16843008
  k = ChunkyPNG::Canvas.from_file(img)
  # go line by line, pixel by pixel
  (0..k.height-1).each do |y|
    (0..k.width-1).each do |x|
      total, i = 0, 0
      p "Starting color is #{curr} or #{curr.to_s(16)}"
      # set the coords around the pixel we want
      around = [[x-1,y-1], [x, y-1], [x+1, y-1], [x-1,y], [x+1, y], [x,y+1], [x, y+1], [x+1, y+1]]
      # grab the 8 colors around the current pixel
      around.each do |coords|
        # ignore values that are not in bounds
        next unless k.include_xy?(coords[0], coords[1])
        # get a total to average later
        total = total + k.[](coords[0], coords[1])
        # increment
        i = i+1
      end
      # get the average value for the new color
      new_color = total/i
      # since new color will likely not be a grayscale value,
      # round up to the nearest grayscale value.
      # This is unfortunately really slow.
      while (new_color%d) > 0 do
        new_color = new_color+1
      end
      p "New color is now #{new_color-1} or #{(new_color-1).to_s(16)}"
      # set the color and
      # remove one from the color value to get full alpha instead of none.
      k.[]=(x, y, new_color-1)
    end
  end
  # save the complete image
  k.save("#{Time.new}.png")
}
l.($*[0])

Could certainly do things a bit more efficiently, unfortunately I'm not quite how to. There's got to be a more clever way of handling the coordinate management for the 8 surrounding locations.

Racket 346 bytes
(let((s1 sub1)(a1 add1)(lr list-ref)(ln length))(define(g r c)(if(or(> r(s1(ln l)))(> c(s1(ln(lr l 0))))(< r 0)(< c 0))
#f(lr(lr l r)c)))(define(ng r c)(define h'(-1 0 1))(define k(filter(λ(x)x)(for*/list((i h)(j h)#:unless(= 0 i j))
(g (+ r i)(+ c j)))))(round(/(apply + k)(ln k))))(for/list((i(ln l)))(for/list((j(length (lr l 0))))(ng i j))))

Ungolfed (comments follow ';'):
(define (f l)
  (define (get r c)                       ; to get value at a row,col
    (if (or (> r (sub1 (length l)))
            (> c (sub1 (length (list-ref l 0))))
            (< r 0)
            (< c 0))                      ; if row/col number is invalid
        #f (list-ref (list-ref l r) c)))  ; return false else return value
  (define (neighbors r c)                 ; finds average of neighboring values
    (define h '(-1 0 1))
    (define k (filter                     ; filter out false from list
               (lambda(x) x)
               (for*/list ((i h)(j h) #:unless (= 0 i j))
                 (get (+ r i) (+ c j)))))
    (round(/(apply + k)(length k))))      ; find average of values (sum/length of list)
  (for/list ((i (length l)))              ; create a list of lists of average values
    (for/list ((j (length (list-ref l 0))))
      (neighbors i j))
    ))

Testing:
(f (list
    '(120 80 60)
    '(20 10 30)
    '(40 100 5)))

Output:
'((37 48 40) (70 57 51) (43 21 47))

Nice Job! Please provide the image result as well.


text:
Find the Infinity Words!
(Note: This is a spin-off of my previous challenge Find the Swirling Words!)
Definition of Infinity Word:

If you connect with curves all the characters of an Infinity Word on the alphabet (A-Z) you obtain the infinity symbol ∞ like in the diagrams below.
All the even connection must be down, all the odd connections must be up.
You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.
The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.
Each word must be exactly 5 characters. Words > 5 or < 5 are not valid.
If a word has double consecutive characters, the word is not valid, like "FLOOD" or "QUEEN".
All the Infinity Words start and end with the same character.

Here there are some examples:

Task:
Write a full program or function that will take a word from standard input and will output if is an Infinity Word or not. The output can be true/false, 1/0, 1/Null, etc.
Test cases:
Infinity Words:
ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW

NOT Infinity Words:
CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST,
KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO

Rules:

Shortest code wins.

Optional Task:
Find, as a list, as many Infinity Words as you can in an English dictionary. You can take for example as reference the complete list of English words here.

Can we assume the input is always of length 5? You have defined rule 5: "Each word must be exactly 5 characters. Words > 5 or < 5 are not valid.", but no NOT Infinity Words containing less or more than 5 characters.

Pretty funny that ALPHA makes that pattern

@KevinCruijssen You must check that the word respect the definition, I updated the false cases.

Also, one more thing I noticed. At your picture you have ORTHO NO, but at the Test Cases, ORTHO is at the truthy cases instead of falsey.

@KevinCruijssen My mistake! :) I updated it

IMO, a word such as AAAAA should be considered as a valid singularity, which is currently not the case because of rule #6. Does that make sense?

@Arnauld five "A"'s connects to themselves (or doesen't move at all) creating a single point, it doesen't draw the infinity symbol, so I don't think it's a positive case.

@Mario FYI there is no test case that fails if I perform only my rotation test without checking last letter equals first. How about adding "RULES"?

@JonathanAllan I'm not sure I understood well your last comment, but the word "RULES" doesen't draw a closed infinity symbol, so I think it should be considered as false case. The path should be closed and with no ending anywhere.

Yes it is Falsely, but if one performs the test I described in my answer but without checking first==last all test cases work.

I have decided to tackle the Optional Task: "Find, as a list, as many Infinity Words as you can in an English dictionary..." I used this source and Kevin Cruijssen's answer, to produce this list of 278 Infinity Words.

Jelly, 43 41 40 25 24 23 22 21 14 13 bytes
-7 bytes thanks to fireflame241 (0ị=1ị$->=ṚḢ and use of IIA⁼2,2 to test for the 4 rotations)
-1 Thanks to Kevin Cruijssen (use of previously unavailable nilad Ø2 which yields [2,2])
=ṚḢȧOIṠIIA⁼Ø2

TryItOnline
Or all test cases (plus "RULES")
How?
An infinity word has:

the same first and last letter;
length 5;
no equal letters next to each other;
sum of its four alphabet deltas equal to zero;
sum of its four alphabet deltas signs equal to zero;
two positive alphabet deltas or two negative alphabet deltas in a row.

All but (1) and (equivalently) (4) may be boiled down to a condition that the alphabet delta signs are some rotation of [1,1,-1,-1] (where the sign of 0 is 0)
fireflame241 noted that this is then equivalent to the deltas of the deltas of the alphabet delta signs being in [[2,2],[2,-2],[-2,2],[-2,-2]] which may be tested by the absolute values being equal to [2,2]!
How?
=ṚḢȧOIṠIIA⁼Ø2 - Main link: word
 Ṛ            - reverse word
=             - equals? (vectorises)
  Ḣ           - head (is the first character equal to the last?)
   ȧ          - and
    O         - cast word to ordinals
     I        - increments - the alphabet deltas (or just [] if 1st != last)
      Ṡ       - sign (vectorises)
       I      - increments - deltas of those signs
        I     - increments - deltas of those
         A    - absolute value (vectorises)
           Ø2 - literal [2,2]
          ⁼   - equals? (non-vectorising version)

How does this work?

incoming explanation.

I'm always wondering: what do you think is the most valuable thing you get out of being good at / using Jelly :)? For what would you advise people to give Jelly a go; any other reason than fun?

@PascalvKooten It is mostly for the fun, and to be competitive at code golf - I'm fairly new to both code golf and Jelly, so putting together a Jelly program is like a little puzzle almost every time; I find it satisfying. If one wishes to get something tangible out of this game one should use it to hone one's skills in a language that is more commonly used in the real world though, or, of course, create a golfing language of one's own!

@JonathanAllan how do you start with something unintelligibly  as this ?XD

@lois6b :). You start with the tutorial, and then use the pages with Atom definitions, Quicks definitions, and browse the source code.

14 bytes The main golf here uses II to check for equality to a rotation of 1,1,-1,-1.

@fireflame241 very nice golfing! I shall update in a few...

Probably wasn't available yet when you posted this answer, but 2,2 can be Ø2 now.

@KevinCruijssen - indeed it was not; updated, thanks!

Java 8, 231 193 185 122 103 78 bytes
s->s.length==5&&(s[1]-s[0])*(s[3]-s[2])<0&(s[2]-s[1])*(s[4]-s[3])<0&s[4]==s[0]

Try it here.
-38 bytes thanks to @dpa97 for reminding me to use char[] instead of String.
-63 bytes thanks to @KarlNapf's derived formula.
-25 bytes by converting it from Java 7 to Java 8 (and now returning a boolean instead of integer).
193 bytes answer:
int c(char[]s){if(s.length!=5)return 0;int a=s[0],b=s[1],c=s[2],d=s[3],e=s[4],z=b-a,y=c-b,x=d-c,w=e-d;return e!=a?0:(z>0&y>0&x<0&w<0)|(z<0&y>0&x>0&w<0)|(z>0&y<0&x<0&w>0)|(z<0&y<0&x>0&w>0)?1:0;}

Explanation:

If the length of the string isn't 5, we return false
If the first character doesn't equal the last character, we return false
Then we check the four valid cases one by one (let's indicate the five characters as 1 through 5), and return true if it complies to any of them (and false otherwise):

If the five characters are distributed like: 1<2<3>4>5 (i.e. ALPHA)
If the five characters are distributed like: 1>2<3<4>5 (i.e. EAGLE, HARSH, NINON, PINUP)
If the five characters are distributed like: 1<2>3>4<5 (i.e. RULER)
If the five characters are distributed like: 1>2>3<4<5 (i.e. THEFT, WIDOW)

These four rules can be simplified to 1*3<0 and 2*4<0 (thanks to @KarlNapf's Python 2 answer).

+1 to compensate the unexplained downvote ... As far as I can tell, this is a perfectly functional solution.

I got it down to 215 converting s to a char[]
char[]c=s.toCharArray();int z=c[1]-c[0],y=c[2]-c[1],...

@dpa97 Thanks for the reminder to use char[] as input instead of String. -38 bytes thanks to you.

Your booleans can be optimized: z,x and w,y must have an alternating sign, so it suffices to check z*x<0 and w*y<0

@KarlNapf Ah, I misinterpreted your comment a few hours ago. I've implemented your derived formula for a whopping -63 bytes. :) Thanks.

"int" + "?1:0" is 7 characters long. "boolean" is 7 characters long. I don't see why you return an "int" value. In Java 8, it'd be shorter to use the boolean return type. Also, remove the "length is 5" condition: the OP says they're not "valid", not that you shouldn't return something falsy. Also given that no truthy/falsy, an exception is considered "false", just use that to your advantage.

JavaScript (ES6), 91 89 87 bytes
Saved 2 bytes thanks to Ismael Miguel
s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1)

How it works
We build a 4-bit bitmask k representing the 4 transitions between the 5 characters of the string:
k += p > c ? 1<<i : 0 / (p < c)

if the previous character is higher than the next one, the bit is set
if the previous character is lower then the next one, the bit is not set
if the previous character is identical to the next one, the whole bitmask is forced to NaN so that the word is rejected (to comply with rule #6)

The valid bitmasks are the ones that have exactly two consecutive 1 transitions (the first and the last bits being considered as consecutive as well):
Binary | Decimal
-------+--------
0011   | 3
0110   | 6
1100   | 12
1001   | 9

In other words, these are the combinations which are:

k? : greater than 0
!(k%3) : congruent to 0 modulo 3
lower than 15

The other conditions are:

!s[5] : there's no more than 5 characters
s[0]==s[4] : the 1st and the 5th characters are identical

NB: We don't explicitly check k != 15 because any word following such a pattern will be rejected by this last condition.
Test cases

let f =

s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1)

console.log("Testing truthy words...");
console.log(f("ALPHA"));
console.log(f("EAGLE"));
console.log(f("HARSH"));
console.log(f("NINON"));
console.log(f("PINUP"));
console.log(f("RULER"));
console.log(f("THEFT"));
console.log(f("WIDOW"));

console.log("Testing falsy words...");
console.log(f("CUBIC"));
console.log(f("ERASE"));
console.log(f("FLUFF"));
console.log(f("LABEL"));
console.log(f("MODEM"));
console.log(f("RADAR"));
console.log(f("RIVER"));
console.log(f("SWISS"));
console.log(f("TRUST"));
console.log(f("KNEES"));
console.log(f("QUEEN"));
console.log(f("ORTHO"));
console.log(f("GROOVE"));
console.log(f("ONLY"));
console.log(f("CHARACTER"));
console.log(f("OFF"));
console.log(f("IT"));
console.log(f("ORTHO"));

Initial version
For the record, my initial version was 63 bytes. It's passing all test cases successfully but fails to detect consecutive identical characters.
([a,b,c,d,e,f])=>!f&&a==e&&!(((a>b)+2*(b>c)+4*(c>d)+8*(d>e))%3)

Below is a 53-byte version suggested by Neil in the comments, which works (and fails) equally well:
([a,b,c,d,e,f])=>!f&&a==e&&!((a>b)-(b>c)+(c>d)-(d>e))

Edit: See Neil's answer for the fixed/completed version of the above code.

0000 is also congruent to 0 modulo 3 but again you can't have the first and last letters the same, so, like 15, you don't need to explicitly test for it.

For that initial version, can you use !((a>b)-(b>c)+(c>d)-(d>e))?

p<c?0:NaN can be written as 0/(p<c), which saves 2 bytes.

@Neil Regarding the test against 0: you're perfectly right. (However, I do need the k? test because of the possible NaN.) Regarding your alternate version: that should work indeed.

@IsmaelMiguel - Good call! Thanks.

Only 53 bytes? Nice, I can add &&!/(.)\1/.test(a+b+c+d+e) to that to exclude identical adjacent letters and still come in under 80 bytes!

@Neil Sounds good! I think you should post it. (This is clearly not related to my original answer anymore.)

JavaScript (ES6), 78 bytes
([a,b,c,d,e,f])=>a==e&&!(f||/(.)\1/.test(a+b+c+d+e)||(a>b)-(b>c)+(c>d)-(d>e))

Based on @Arnauld's incorrect code, but golfed and corrected. Works by first checking that the first character is the same as the fifth (thus guaranteeing 5 characters) and that the length of the string is no more than 5. After checking for consecutive duplicate characters, it remains to check the waviness of the string, which should have one peak and one trough two letters apart.

If the peak and the trough are the middle and first/last letters, then the first two comparisons and the last two comparisons cancel out
If the peak and the trough are the second and fourth letters, then the middle two comparisons and the outer two comparisons cancel out
Otherwise, something fails to cancel and the overall expression returns false

Edit: Alternative 78-byte solution based on @KarlNapf's answer:
([a,b,c,d,e,f],g=(a,b)=>(a<b)-(a>b))=>a==e&&!f&&g(a,b)*g(c,d)+g(b,c)*g(d,e)<-1

Python 2, 110 87 60 bytes
Saving 1 byte thanks to Neil
Requires input enclosed in quotes, e.g. 'KNEES'
True if it is an infinity word, False if not and it has length of 5 and prints error message if wrong length
s=input()
a,b,c,d,e=map(cmp,s,s[1:]+s[0])
print a*c+b*d|e<-1

Inspired by xnor's answer using map(cmp...
s=input()
e=map(cmp,s,s[1:]+s[0])
print e[4]==0and e[0]*e[2]+e[1]*e[3]==-2and 5==len(s)

previous solution:
s=input()
d=[ord(x)-ord(y)for x,y in zip(s,s[1:])]
print s[0]==s[4]and d[0]*d[2]<0and d[1]*d[3]<0and 4==len(d)

Using the optimized logic of Kevin Cruijssen

Why not a*c+b*d+2==0==e?

@Neil yes why not, but xnor's a*c+b*d|e is even shorter.

I think <-1 might work, since both -2|1 and -2|-1 equal -1.

Python 2 exit code, 56 bytes
s=input()
v,w,x,y,z=map(cmp,s,s[1:]+s[0])
v*x+w*y|z>-2>_

Outputs via exit code: Error for False, and successful run for True.
Takes the string s with characters abcde, rotates it to bcdea, does an elementwise comparison of corresponding characters, and assigns them to five variables v,w,x,y,z. The wrong length gives an error.
The infinity words all have
v*x == -1
w*y == -1
z == 0

which can be checked jointly as v*x+w*y|z == -2. The chained comparison v*x+w*y|z>-2>_ short-circuits if this is the case, and otherwise goes on to evaluate -2>_ which gives a name error.

Ah, that's nice how you golfed the conditional more!

PHP, 102 Bytes
for(;$i<strlen($w=$argv[1]);)$s.=($w[$i++]<=>$w[$i])+1;echo preg_match("#^(2200|0022|2002|0220)#",$s);

Python 2, 71 bytes
lambda s:map(cmp,s,s[1:]+s[0])in[[m,n,-m,-n,0]for m in-1,1for n in-1,1]

Takes the string s with characters abcde, rotates it to bcdea, and does an elementwise comparison of corresponding characters.
a  b   cmp(a,b)
b  c   cmp(b,c)
c  d   cmp(c,d)
d  e   cmp(d,e)
e  a   cmp(e,a)

The result is a list of -1, 0, 1. Then, checks if the result is one of the valid sequences of up and downs:
[-1, -1, 1, 1, 0]
[-1, 1, 1, -1, 0]
[1, -1, -1, 1, 0]
[1, 1, -1, -1, 0]

as generated from the template [m,n,-m,-n,0] with m,n=±1. The last 0 checks that the first and last letter were equal, and the length ensures that the input string had length 5.

An alternative 71. Checks the conditions on comparisons while ensuring the right length.
def f(s):a,b,c,d,e=map(cmp,s,s[1:]+s*9)[:5];print a*c<0==e>b*d>len(s)-7

R, 144 bytes
The answer is based off the logic of @Jonathan Allan. It could probably be golfed though.
s=strsplit(scan(,""),"")[[1]];d=diff(match(s,LETTERS));s[1]==tail(s,1)&length(s)==5&all(!rle(s)$l-1)&!sum(d)&!sum(sign(d))&any(rle(sign(d))$l>1)

R-fiddle test cases (vectorized example but same logic)

Since you already have a check that length(s)==5, you can replace s[1]==tail(s,1) with s[1]==s[5]. A one-byte shorter method to check the length is is.na(s[6]). Together these two changes return TRUE for s of length 5 exactly and FALSE otherwise, as TRUE&NA is NA but FALSE&NA is FALSE. You can also save a few bytes by replacing !sum(sign(d))&any(rle(sign(d))$l>1) with !sum(a<-sign(d))&any(rle(a)$l>1).

Actually, 38 27 bytes
This answer was largely inspired by Jonathan Allan's excellent Jelly answer. There are probably several places where this can be golfed, so golfing suggestions welcome! Try it online!
O;\♀-dY@♂s4R`0~;11({k`Míub*

Ungolfing
     Implicit input s.
O    Push the ordinals of s. Call this ords.
;    Duplicate ords.
\    Rotate one duplicate of ords left by 1.
♀-   Vectorized subtraction. This effectively gets the first differences of ords.
d    Pop ord_diff[-1] onto the stack. This is ords[0] - ords[-1].
Y    Logical negate ord_diff[-1], which returns 1 if s[0] == s[-1], else 0.
@    Swap (s[0] == s[-1]) with the rest of ord_diff.

♂s       Vectorized sgn() of ord_diff. This gets the signs of the first differences.
4R       Push the range [1..4] onto the stack.
`...`M   Map the following function over the range [1..4]. Variable x.
  0~;      Push -1 onto the stack twice.
  11       Push 1 onto the stack twice.
  (        Rotate x to TOS.
  {        Rotate the stack x times, effectively rotating the list [1, 1, -1, -1].
  k        Wrap it all up in a list.

     Stack: list of rotations of [1, 1, -1, -1], sgn(*ord_diff)
í    Get the 0-based index of sgn(*ord_diff) from the list of rotations. -1 if not found.
ub   This returns 1 only if sgn(*ord_diff) was found, else 0.
     This checks if the word loops like an infinity word.

*    Multiply the result of checking if the word s loops and the result of s[0] == s[-1].
     Implicit return.

GNU Prolog, 47 bytes
i([A,B,C,D,A]):-A>B,B>C,C<D,D<A;i([B,C,D,A,B]).

Defines a predicate i which succeeds (infinitely many times, in fact) for an infinity word, thus outputting "yes" when run from the interpreter (as is usual for Prolog); fails for a candidate word whose first and last letters don't match, or isn't 5 letters long, thus outputting "no" when run from the interpreter; and crashes with a stack overflow if given a candidate word that isn't an infinity word, but which is five letters with the first and last two matching. (I'm not sure why it crashes; the recursive call should be treatable as a tailcall. Apparently GNU Prolog's optimizer isn't very good.) Succeeding is Prolog's equivalent of truthy, and failing the equivalent of falsey; a crash is definitely more falsey than truthy, and fixing it would make the solution substantially longer, so I hope this counts as a valid solution.
The algorithm is fairly simple (and indeed, the program is fairly readable); check whether the letters form one of the four patterns that make an infinity word, and if not, cyclicly permute and try again. We don't need to explicitly check for double letters as the < and > operators let us implicitly check that at the same time that we check that the deltas match.

APL (Dyalog), 16 15 bytes
0=16|3⊥×2-/⎕a⍳⍞

Try it online!

TI-BASIC, 81 bytes
String to pass into the program is in Ans. Returns (and implicitly displays) 1 if the entered word is an Infinity Word, and 0 (or exits with an error message) if it isn't.
seq(inString("ABCDEFGHIJKLMNOPQRSTUVWXYZ",sub(Ans,A,1)),A,1,length(Ans
min(Ans(1)=Ans(5) and {2,2}=abs(deltaList(deltaList(deltaList(Ans)/abs(deltaList(Ans

Errors on any repeated characters, or non-5-letter-words.

05AB1E, 16 bytes
Ç¥DO_s.±¥¥Ä2DиQ*

Port of @JonathanAllan's Jelly answer.
Try it online or verify all test cases.
Explanation:
Ç             # Convert the (implicit) input string to a list of unicode values
              #  i.e. "RULES" → [82,85,76,69,82]
 ¥            # Take the deltas
              #  i.e. [82,85,76,69,82] → [3,-9,-7,13]
  DO          # Duplicate and take the sum
              #  i.e. [3,-9,-7,13] → 0
    _         # Check if that sum is exactly 0
              # (which means the first and last characters are equal)
              #  i.e. 0 and 0 → 1 (truthy)
 s            # Swap so the deltas are at the top of the stack again
  .±          # Get the sign of each
              #  i.e. [3,-9,-7,13] → [1,-1,-1,1]
    ¥         # Get the deltas of those signs
              #  i.e. [1,-1,-1,1] → [-2,0,2]
     ¥        # And then get the deltas of those
              #  i.e. [-2,0,2] → [2,2]
      Ä       # Convert them to their absolute values
       2Dи    # Repeat the 2 two times as list: [2,2]
          Q   # Check if they are equal
              #  i.e. [2,2] and [2,2] → 1 (truthy)
 *            # Check if both are truthy (and output implicitly)
              #  i.e. 1 and 1 → 1 (truthy)