text:
Wrap a seasonal present
Task
Given a wrapper element and a non-jagged 3D array, wrap the array top, bottom, and all-around. You must handle both character and numeric data, but the wrapper and the present will have the same data type.

Character example
For character data, you may chose to handle either 3D arrays of single characters or 2D arrays of strings:
Given the 2 layer, 2 row, 4 column character array
[[["Y","o","u","r"],
  ["g","i","f","t"]],

  [["g","o","e","s"],
  ["h","e","r","e"]]]

and the character ".", answer the 4 layer, 4 row, 6 column character array
[[[".",".",".",".",".","."],
  [".",".",".",".",".","."],
  [".",".",".",".",".","."],
  [".",".",".",".",".","."]],

 [[".",".",".",".",".","."],
  [".","Y","o","u","r","."],
  [".","g","i","f","t","."],
  [".",".",".",".",".","."]],

 [[".",".",".",".",".","."],
  [".","g","o","e","s","."],
  [".","h","e","r","e","."],
  [".",".",".",".",".","."]],

 [[".",".",".",".",".","."],
  [".",".",".",".",".","."],
  [".",".",".",".",".","."],
  [".",".",".",".",".","."]]]

or given the 2 row, 2 column array of 4-character strings
[["Your",
  "gift"],

 ["goes",
  "here"]]

and the character ".", answer the 4 row, 4 column array of 6-character strings
[["......",
  "......",
  "......",
  "......"],

 ["......",
  ".Your.",
  ".gift.",
  "......"],

 ["......",
  ".goes.",
  ".here.",
  "......"],

 ["......",
  "......",
  "......",
  "......"]]

Numeric example
Given the 2 layer, 2 row, 2 column numeric array
[[[1,2],
  [3,4]],

 [[5,6],
  [7,8]]]`

and the number 0, answer the 4 layer, 4 row, 4 column numeric array
[[[0,0,0,0],
   [0,0,0,0],
   [0,0,0,0],
   [0,0,0,0]],

  [[0,0,0,0],
   [0,1,2,0],
   [0,3,4,0],
   [0,0,0,0]],

  [[0,0,0,0],
   [0,5,6,0],
   [0,7,8,0],
   [0,0,0,0]],

  [[0,0,0,0],
   [0,0,0,0],
   [0,0,0,0],
   [0,0,0,0]]]

Can we assume the length of each "gift element" to wrap is identical?

@XavCo7 Yes you can.

Related.

What kind of output is acceptable. Need it be a datastructure of a three d array or is textual output acceptable

@RohanJhunjhunwala You may freely choose representation, but input and output formats must be the same.

@Adám Congrats on 10k!!

@LuisMendo Thanks. I guess that'll be by seasonal present from SE :-)

In the example of 3D char arrays, the wrapped gift says 'Your gift/goea here', do we need to edit the string?

Dyalog APL, 31 19 13 12 bytes
Almost a transliteration (31 bytes) of @Zgarb's solution.
An anonymous function. Left argument is wrapping, right argument is gift.
⊣h⍤1⊣h⍤2(h←⍪⍪⊣)

⊣h⍤1 h applied, with the anonymous function's left argument, to the columns of
⊣h⍤2 h applied, with the anonymous function's left argument, to the rows of
h← h applied to the major cells i.e. the layers of the anonymous function's arguments, where h is
 ⍪ the left argument prepended to the right argument
 ⍪ prepended to
 ⊣ the left argument
In other words, h is a function which surrounds its right argument (the gift) with its left argument (the wrapper). h is then applied to the gift's layers, then the rows of that, and finally the columns of that.
TryAPL online!

This Dyalog APL version 16.0 solution (19 bytes – courtesy of @ngn) handles any number of dimensions:
{⍵@(1+⍳⍴⍵)⊢⍺⍴⍨2+⍴⍵}

⍵ the gift
@( placed at
 1+ one plus
 ⍳ all the indices of
 ⍴⍵ the shape of the gift
)⊢ in the array consisting of
⍺⍴⍨ the wrapper reshaped to the shape
2+ two added to
⍴⍵ the shape of the gift
In other words, we create an array entirely of wrapper elements, which in every dimension is two elements larger than the gift, then we place the gift into that array (thus replacing the wrapping elements in those positions) at an offset of one from the edges, i.e. in the center.

My own invention (-1 thanks to @ngn):
(⌽2 3 1⍉,)⍣6

This applies an anonymous function-train 6 times, each time with the wrapper as left argument, and the result of the previous application as right argument (although the first time around it will be the unmodified gift):
(  an anonymous function-train
 ⌽ reverse columns of
 2 3 1⍉ the rows-to-layers, columns-to-rows, layers-to-columns transposition of
 , the wrapper followed by the gift
)⍣6 applied six times
In other words, we add a layer of wrapper on the top of the array, then warp it so that the next side gets rotated into the top layer position, ready for another round of wrapping. This is repeated six times, with the final warping repositioning all axes to the original order.
TryAPL online!

J, 16 15 bytes
[h"2[h"1 h=.,,[

This is an anonymous verb. Try it online!
Thanks to Adám for 1 byte!
Explanation
[h"2[h"1 h=.,,[  Wrapper is x, present is y.
            ,    Prepend x to y
             ,   then append
              [  x.
                 This gives x y x, and the wrapper automatically spreads to form 2D slices.
         h=.     Save the above operation (not its result) to h.
    [h"1         Apply h to x and every 2D slice of the previous result.
[h"2             Apply h to x and every 1D slice of the result of that.

Couldn't you save a byte with h=.,,[

JavaScript (ES6), 97 bytes
(a,e)=>[c=[,,...b=a[0]].fill(d=[,,...b[0]].fill(e)),...a.map(a=>[d,...a.map(a=>[e,...a,e]),d]),c]

Where a is the three-dimensional array and e is the wrapper. Automatically converts a two-dimensional array of strings to a three-dimensional array of characters. Alternative version for when a is a two-dimensional array of strings and e is a character and you want to return a two-dimensional array of strings:
(a,e)=>[c=[,,...a[0]].fill(d=e.repeat(a[0][0].length+2)),...a.map(b=>[c,...b.map(s=>e+s+e),d]),c]

Looks like this fails on numeric e.

@Adám Ah, sorry, I may have misunderstood the question.

@Adám New version, fortunately same byte count, works on three-dimensional arrays of arbitrary elements (will autoconvert strings to character arrays).

Python, 106 104 126 bytes
def w(g,c):x=len(g[0][0])+2;k=[[c*x]*(len(g[0])+2)];return k+[[c*x,*[c+"".join(str(k)for k in j)+c for j in i],c*x]for i in g]+k

Called as w(gift, wrapping character). Can use the string and the array notation. Try it online!

I couldn't figure out how to run this on repl.it. Can you create a link?

@Adám https://repl.it/Eu4M/1

Thanks. Looks like numeric fails.

@Adám Gotcha, I misinterpreted (hehe) the specification. Slightly longer now, but it actually works correctly > https://repl.it/Eu4M/4

Wow, now you went beyond specs, you didn't need to handle the mixed data types case.

Octave, 23  27 bytes
@(a,p)padarray(a,[1 1 1],p)

array: a
padval: p
It  can be called as :
(@(a,p)padarray(a,[1 1 1],p))([1 2;3 4],40)

try (paste!)it on Octave Online
note: previous answer assumed default padval

This looks like it only accepts a single argument (the array). Where does it get the wrapping character/number from?

by default the function pad by 0

@rahnema1 So what if the padding is 42, or "Z"?

Oh...answer updated including PADVAL

+1 I'm surprised that there is a built-in for exactly this.

Perl 6, 86 bytes
->\a,\w{my @z=[[w xx a[0;0]+2]xx a[0]+2]xx a+2;@z[1..a;1..a[0];1..a[0;0]]=a[*;*;*];@z}

A lambda that takes the 3D array and wrapping character as arguments.

It first creates a 3D output array of the correct size, filled with the wrapping character.
Then it uses the array slice syntax to assign the values of the original array into the correct slots of the new array, in one fell swoop.

05AB1E, 34 33 31 bytes
vy¬gÌ²s×S©svy².ø¼}®)ˆ}¾F®})¯s.ø

Try it online! (string) or Try it online! (numerical)

Ruby, 89 bytes
->a,b{(w=[[z=b*2+a[0][0].tr('^|',b)]*(2+a[0].size)])+a.map{|x|[z]+x.map{|y|b+y+b}+[z]}+w}

Have I ever told you I'm only here to learn ruby? :-)


text:
An Array of Challenges #2: Separate a Nested Array
Note: This is #2 in a series of array challenges. For the previous challenge, click here.
Separating Nested Lists

To separate values in a nested list, flatten it, and then wrap each value so it is at the same nested depth as before.

That is to say, this list:
[1, [2, 3], [4, 4, [5, 2], 1]]

Would become:
[1, [2], [3], [4], [4], [[5]], [[2]], [1]]

The Challenge
Your task is to write a program which takes any nested list of positive integers (within your language's limits) and performs this separation operation.
You may submit a function which takes the list as an argument, or a full program which performs I/O.
As this is code-golf, the shortest submission (in bytes) wins!*
*Standard golfing loopholes are banned. You know the drill.

Test Cases
Input lists will only ever contain integers in your language's standard integer size. To avoid languages' constraints preventing them from competing, values will not be nested at depths of more than 10.
You may assume that input will not have empty sub-lists: for example - [[5, []]] will not be given. However, the main list could be empty.
[]            ->  []

[[1, 2]]      ->  [[1], [2]]
[3, [4, 5]]   ->  [3, [4], [5]]
[3, [3, [3]]] ->  [3, [3], [[3]]]
[[6, [[7]]]]  ->  [[6], [[[7]]]]
[[5, 10], 11] ->  [[5], [10], 11]

Don't hesitate to leave a comment if I've missed out a corner case.
Example
I threw together a quick (ungolfed) Python 3 solution as an example - you can test it on repl.it.

Add a testcase with bigger than single digit numbers for string based answers.

@orlp good idea.

Can we assume a certain maximum depth? Say, 16?

@orlp I'm going to say yes, the maximum nested depth will be 10, as I'm more interested in your algorithm and method execution than your language's constraints. Will update thread now.

May I output as a string?

@RohanJhunjhunwala as always with code-golf, I/O is flexible. As long as the string is a valid, unambiguous representation of a list, then that is fine.

The input list will not contain 0, right?

@ZacharyT yep, only positive integers (0 isn't regarded as positive on PPCG: if I wanted to include 0, I would say "non-negative")

Brachylog v1, 16 bytes
:{##:0&:ga|g}ac|

Try it online!
Explanation
Example input: [1:[2:3]]

:{          }a     Apply the predicate below to each element of the list: [[1]:[[2]:[3]]]
              c    Concatenate: Output = [1:[2]:[3]]
               |   Or: Input = Output = []

  ##                 Input is a list: e.g. Input = [2:3]
    :0&              Call recursively the main predicate with this input: [2:3]
       :ga           Group each element in a list: Output = [[2]:[3]]
          |          Or (not a list): e.g. Input = 1
           g         Group into a list: Output = [1]

What does the Z argument do on TIO? Without it this seems to output with true/false, which makes it seem like Z is necessary in the byte count.

@FlipTack Z tells Brachylog that the output argument is a variable. This is this variable that gets unified with the resulting output. When you remove it it tells Brachylog the output is an anonymous variable, and instead will print whether the main predicate succeeds or fails. This is the same as in Prolog where the result is "put" in a variable.

Ok :) nice answer!

Mathematica, 24 21 bytes
##&@@List/@#0/@#&/@#&

or one of these:
##&@@List/@#&/@#0/@#&
##&@@List@*#0/@#&/@#&
##&@@List/@#&@*#0/@#&

Explanation
The reason this is so short is that it's basically a recursion that doesn't require an explicit base case.
There's a lot of syntactic sugar here, so let's start by ungolfing this. & denotes an unnamed function left of it, whose argument is written as #. Inside this function #0 refers to the function itself, which allows one to write unnamed recursive functions. But let's start by giving the inner function a name and pulling it out:
f[x_] := ##& @@ List /@ f /@ x
f /@ # &

The other important syntactic sugar is f/@x which is short for Map[f, x] i.e. it calls f on every element of x. The reason f[x_] := ... f /@ x doesn't lead to infinite recursion is that mapping something over an atom leaves the atom unchanged without actually calling the function. Hence, we don't need to check for the base case (current element is an integer) explicitly.
So the function f first recurses down to the deepest list inside x, at which point f/@ becomes a no-op. Then we call use ##& @@ List /@ on that. Mapping List over the list simply wraps each element in a separate list, so {1, 2, 3} becomes {{1}, {2}, {3}}. Then we apply ##& to it, which means the head (i.e. the outer list) gets replaced by ##&, so this turns into ##&[{1}, {2}, {3}]. But ##& simply returns it's arguments as a Sequence (which you can think of as an unwrapped list, or a sort of "splat" operator in other languages).
So ##& @@ List /@ turns a list {1, 2, 3} into {1}, {2}, {3} (kind of, that last thing is actually wrapped in the head Sequence, but that vanishes as soon as we use the value anywhere).
That leaves the question why f itself isn't already the solution to the challenge. The problem is that the outermost list should be treated differently. If we have input {{1, 2}, {3, 4}} we want {{1}, {2}, {3}, {4}} and not {{1}}, {{2}}, {{3}}, {{4}}. My original solution fixed this by passing the final result as a list of arguments to Join which would restore the outer level of lists, but this one just skips the outer level by using f itself in a map on the output. Hence f is only applied to the individual elements of the outermost list and never gets to touch that list.
As for the other three solutions, the first one simply applies the recursion outside of f which works just as well. The other two solutions avoid a repeated Map operation by first composing two functions and then mapping the result only once.

J, 19 18 bytes
(<@]/@,~>)S:0 1{::

This is an anonymous verb that takes and returns boxed arrays, which are J's (rather cumbersome) version of nested arrays.
See it pass all test cases.
Explanation
This uses the somewhat exotic operations {:: (map) and S: (spread), which operate on boxed arrays.
{:: replaces each leaf with the boxed path to that leaf.
S: applies a given verb to a given nesting depth, then splats the results into an array.
(<@]/@,~>)S:0 1{::  Input is y.
(        )          Let's look at this verb first.
        >           Open the right argument,
      ,~            append the left argument to it,
    /               then reduce by
 <@]                boxing. This puts the left argument into as many nested boxes
                    as the right argument is long.
                    This verb is applied to y
               {::  and its map
            0 1     at levels 0 and 1.
                    This means that each leaf of y is paired with its path,
                    whose length happens to be the nesting depth of y,
                    and the auxiliary verb is applied to them.
          S:        The results are spread into an array.

R, 199 bytes
function(l){y=unlist(l);f=function(x,d=0){lapply(x,function(y){if(class(y)=='list'){f(y,d=d+1)}else{d}})};d=unlist(f(l));lapply(1:length(d),function(w){q=y[w];if(d[w]){for(i in 1:d[w])q=list(q)};q})}

This question was HARD. R's lists are a bit weird and it is absolutely not straightforward to loop over all the elements of sublists. It is also not straightforward to then determining the depth of that list. Then the challenge becomes to recreate the list with all the elements separated, so we also need a way to adaptively create a list of a certain depth.
The solution consists of two big parts. A recursive function that loops over all the lists and records the depth:
  f=function(x,d=0){
    lapply(x,function(y){
      if(class(y)=='list'){
        f(y,d=d+1)
      } else {
        d
      }})
  }

When we have the depths of every entry of the vector unlist(l), stored in d, we implicitly create a list through lapply, and fill it with the following function:
  lapply(1:length(d),function(w){
    q=y[w]
    if(d[w]){
      for(i in 1:d[w]){
        q=list(q)
      }
    }
    q
  })

In this apply call, we create an object q with the value of the entry in the list, check its depth and see if it is nonzero. If it is zero, we can just leave it as a numeric value. If it is non-zero, we need to nest it in that amount of lists. So we call a for-loop d times and repeatedly call q=list(q).
lapply then puts all these values of q in a list, creating the desired output.
Complete program with proper spacing and such:
function(our.list){
  values <- unlist(our.list)
  f <- function(part.list, depth = 0){
    lapply(part.list, function(y){
      if(class(y)=='list'){
        f(y, depth <- depth + 1)
      } else {
        return(depth)
      }})
  }
  depths <- unlist(f(our.list))
  new.list <- lapply(1:length(depths), function(w){
    q <- values[w]
    if(depths[w] != 0){
      for(i in 1:depths[w]){
        q <- list(q)
      }
    }
    return(q)
  })
  return(new.list)
}

Nice one, this is the method I used with my initial Python solution for the test cases :)

is.list(y) instead of class(y)=='list' ? can't verify that that will actually work.

180 bytes

Retina, 34 bytes
+`(.(?>()\[|(?<-2>)]|.)+)\2,
$1],[

Try it online!

How does the (?<-2>) work?

@KritixiLithos It's a balancing group. It pops from capture stack 2 which lets me keep track of the current nesting depth.

JavaScript (Firefox 30-57), 53 bytes
f=a=>[for(e of a)for(d of e.map?f(e):[e])e.map?[d]:d]

Best ES6 answer I have so far is 76 bytes:
f=(a,r=[],d=0)=>a.map(e=>e.map?f(e,r,d+1):r.push((n=d=>d?[n(d-1)]:e)(d)))&&r

In both code blocks, I think you omitted the leading f=.

@ConorO'Brien Yet again...

Python 2, 122 106 bytes
Pretty terrible score, just a straightforward implementation.
Thanks to @Zachary T for helping save 16 bytes!
def x(l,a=[],d=0):
 n=lambda b:b and[n(b-1)]or l
 if'['in`l`:[x(e,a,d+1)for e in l];return a
 else:a+=n(d)

Call x with one argument to run. For some reason it can only be run once.

You can change a+=[n(l,d)] to a+=n(l,d), (note the trailing comma)

Do you even need to assign to t?

Does this work when you call it more than once?

You can move n to the function and remove the first argument since it's always going to be l.

https://repl.it/EwPz

And I meant move the assignment to n inside the function, then remove the first argument.  n=lambda b:b and[n(b-1)]or l. And replace n(l,d) with n(d). And I also meant [x(e,a,d+1)for e in l] instead of t=[x(e,a,d+1)for e in l].

@ZacharyT oh, ok. Thank you! Also, I have no idea why it doesn't work twice.

https://repl.it/EwQQ/1, that explains it.

It considers the [] as a single value. And since it's a reference, it carries throughout the entire program.

Just put a=[]: on the same line just before you define n, and remove it from the function args - it won't cost you any bytes

PHP, 101 94 bytes
saved 1 byte thanks to @Christoph, saved another 6 inspired by that.
function s($a){foreach($a as$b)if($b[0])foreach(s($b)as$c)$r[]=[$c];else$r[]=$b;return$r?:[];}

recursive function, pretty straight forward
breakdown
function s($a)
{
    foreach($a as$b)                // loop through array
        if($b[0])                       // if element is array
            foreach(s($b)as$c)$r[]=[$c];    // append separated elements to result
        else$r[]=$b;                    // else append element to result
    return$r?:[];                   // return result, empty array for empty input
}

Where does the result get initialised?

@Neil: PHP doesn´t require explicit initialization. Either $r gets elements in the loop or the function returns an empty array. It may yield notices, but those are not printed with the default config.

Doesn't that mean that you'd only be able to call it once?

@Neil: Every function call (including every recursion) starts with a clean slate; i.e. all variables (except the parameters) are unset (===NULL) unless they are declared static or global.

you only need to support any nested list of positive integers so !is_int() instead of is_array() saves you a byte. Restructing the if would take another space so you might as well use !.

You might as well get crazy: !cos(). cos() returns null for every array and a float != 0 for every positiv integer. I mean ... who cares for warnings?

@Christoph: warnings are printed, notices are not (in thje default config). But it´s a great idea! On is_int: Reversing the condition doesn´t save anything; I need a space between else and foreach. BUT: $b[0] for an integer is NULL.

Sadly $b[0] breaks it because $b[0] might be 0 and therefore the array might not be detected as such. But you could supress the warning using an @.

@Christoph: which takes any nested list of positive integers. positive == >0

Ah sry I looked up the question again and only read the will only ever contain integers part. Certainly you're right. Take my upvote ;)

C (gcc), 147 bytes
d=0,l,i;
P(n,c){for(;n--;)putchar(c);}
main(c){for(;~(c=getchar());l=i)i=isdigit(c),P((l<i)*d,91),P(i,c),P((l>i)*d,93),P(l>i,32),d+=(92-c)*(c>90);}

Example input:
1 [23 3] [40 4 [5 2] 1]

Example output:
1 [23] [3] [40] [4] [[5]] [[2]] [1]

stacked, noncompeting, 25 bytes
{e d:e$wrap d 1-*}cellmap

This is a function in that it modifies the top member of the stack. If you want a bonafide function, just add [ and ] to the beginning and end. Try it here!
Here's a readable version:
{ arr :
  arr { ele depth :
    ele   $wrap depth 1- * (* execute wrap n times, according to the depth *)
  } cellmap (* apply to each cell, then collect the results in an array *)
} @:a2
(1 (2 3) (4 4 (5 2) 1)) a2 out

Test case:
(1 (2 3) (4 4 (5 2) 1))    (* arg on TOS *)
{e d:e$wrap d 1-*}cellmap
out                        (* display TOS *)

Output without newlines:
(1 (2) (3) (4) (4) ((5)) ((2)) (1))

Is * like argument to code block?

@Downgoat in this case it wraps the argument d-1 times. $func is a function that can be manipulated.

Haskell, 71 bytes
data L=N Int|C[L]
d#C l=((C .pure.d)#)=<<l
d#n=[d n]
f(C l)=C$(id#)=<<l

Again I have to define my own list type, because Haskell's natives lists can't be arbitrarily nested. This new type L can be returned from a function but not be printed by default, so in order to see a result I define a show instance for L:
instance Show L where
  show (N n)=show n
  show (C l)=show l

Now we can do some test in the REPL:
*Main> f $ C[N 1, C[N 2, N 3], C[N 4, N 4, C[N 5, N 2], N 1]]
[1,[2],[3],[4],[4],[[5]],[[2]],[1]]

*Main> f $ C[C[N 6, C[C[N 7]]]]
[[6],[[[7]]]]

How it works: a simple recursion which passes the nesting level as a function of C constructors. We start with the identity function id and whenever there's a list (-> pattern match d#C l=) we add a further layer of C (-> C .pure.d) to the recursive call of # to all elements of the list. If we encounter a number, we simply apply the nesting-level-function d to the number.

Pyth - 29 bytes
.b]FYt-F/LN`[)PsM._:`Q"\d"3.n

Test Suite.

Perl 6, 60 47 bytes
sub f{[$_~~List??|([$_] for .&f)!!$_ for |$^a]}

(Try it online.)
Explanation:

[... for |$^a]: Iterate over the input array, and construct a new array from it.
$_ ~~ List ?? ... !! ...: For each element, check if it is itself an array.
|([$_] for .&f): If the element is an array, recursively apply the function to it, iterate over the elements of the new array returned from that recursive call, wrap each element in an array of its own, and slip them into the outer list.
$_: If the element is not an array, pass it on as-is.

APL (Dyalog), 44 bytes*
Anonymous tacit prefix function. Takes nested APL list as argument and returns a nested APL array.
∊{⊃⊂⍣⍵,⍺}¨{⊃¨(j∊⎕D)⊆+\-⌿'[]'∘.=j←⎕JSON⍵}

Try it online!
{…} apply the following explicit function where the argument is represented by ⍵:
 ⎕JSON⍵ convert the argument to JSON
 j← store in j
 '[]'∘.= table where j equals open (top row) and close (bottom row) brackets
 -⌿ top row minus bottom row (vertical difference reduction)
 +\ cumulative sum (this gives the nesting level for each character)
 (…)⊆ partition, beginning a new partition whenever a 1 is not preceded by a 1 in…
  j∊⎕D where each character of j is a member of the set of Digits
 ⊃¨ pick the first of each (this gives nesting level per multi-digit number)
∊{…}¨ apply the following function to each nesting level (⍵), using the corresponding element from the ϵnlisted (flattened) argument as left argument (⍺):
 ,⍺ ravel (listify) the number (because scalars cannot be enclosed)
 ⊂⍣⍵ enclose ⍵ times
 ⊃ disclose (because the innermost list is itself an enclosure)

* Using Dyalog Classic with ⎕ML←3 (default on many systems), substituting ⊂ for ⊆ and ↑ for ⊃. Tio!

Jelly, 12 10 bytes
FWṛ¡"ŒJẈ’Ɗ

Try it online!
How it works
FWṛ¡"ŒJẈ’Ɗ - Main link. Takes a list l on the left
F          - Flatten l
         Ɗ - Group the three previous commands over l:
     ŒJ    -   Multidimensional indices of l
       Ẉ   -   Get the length of each
        ’  -   Decrement
           - This gets the depth of each element in l
    "      - Zip together l and the depths, d
   ¡       - Do the following...
  ṛ        -   d times:
 W         -     Wrap the element of l

J, 23 bytes
([:;^:(1<L.)<"+L:0)^:L.

Try it online!
Since J requires boxing for ragged arrays, we use boxing level for array nesting level.  Thus for example:
Original:
┌─────┐
│┌───┐│
││1 2││
│└───┘│
└─────┘
Transformed:
┌───┬───┐
│┌─┐│┌─┐│
││1│││2││
│└─┘│└─┘│
└───┴───┘

Original:
┌─┬───────┐
│3│┌─┬───┐│
│ ││3│┌─┐││
│ ││ ││3│││
│ ││ │└─┘││
│ │└─┴───┘│
└─┴───────┘
Transformed:
┌─┬───┬─────┐
│3│┌─┐│┌───┐│
│ ││3│││┌─┐││
│ │└─┘│││3│││
│ │   ││└─┘││
│ │   │└───┘│
└─┴───┴─────┘

Vyxal, 11 bytes
f?⁽L€f‹¨£(w

Try it Online!
       ¨£   # Zip
f           # Input flattened
  ⁽L€       # Replace elements with depths
 ?          # in input
     f‹     # Flatten and decrement
       ¨£   # Zipwith...
         (w # Repeatedly wrap

source: Stack Exchange

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

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

sort: votes


text:
Incremental Quine
Your task is to write a program or function that outputs the first character of its source code, then the second, then the third... each time it is run.
For example, if your program was foo in language bar in file baz.bar, then you should get output similar to this:
λ bar baz.bar
f
λ bar baz.bar
o
λ bar baz.bar
o

Your program can do anything once its done printing its source code in this fashion. You may modify the source code for the file, but remember that the source code to be printed is the original source code.
This is a code-golf, so the shortest program in bytes wins.

If we can modify the source code for the file, does that mean we can read it too?

@Flp.Tkc Good question. I honestly have no idea. I don't want you to construct the quine by reading the source, but I'm okay if you read the source for the modification of the file only.

Jelly, 12 bytes
“;⁾vṾ®ȯ©Ḣ”vṾ

This is a niladic link. Try it online! (Includes code to call the link twelve times.)
How it works
“;⁾vṾ®ȯ©Ḣ”vṾ  Niladic link.

“;⁾vṾ®ȯ©Ḣ”    Set the left argument and the return value to s =: ';⁾vṾ®ȯ©Ḣ'.
           Ṿ  Uneval; yield r =: '“;⁾vṾ®ȯ©Ḣ”', a string representation of s.
          v   Eval; execute s as a Jelly program with argument r.

 ⁾vV          Yield 'vṾ'.
;             Concatenate r and 'vṾ', yielding q =: '“;⁾vṾ®ȯ©Ḣ”vṾ'.
    ®ȯ        Take the flat logical OR of the register (initially 0) and q.
              This replaces 0 with q in the first run, but it will yield the
              content of the register in subsequent runs.
      ©       Copy the result to the register.
       Ḣ      Head; pop and yield the first character of the register.
              This modifies the string in the register, so it holds one fewer
              character after each call.

As an added bonus, since the register will hold an empty string after the twelveth call, it is once again falsy and the link is ready to start over. Calling the link 24 times will output the source code twice, calling it 36 times thrice, etc.

I don't know Jelly, so what does the footer do precisely? Why ^17?

Call the link above (¢), identity function (¹, not really needed after the first call), set return value to linefeed (⁷, implicitly prints the previous return value), repeat. ¹ and ⁷ are both superscripts, but they're unrelated. I've replaced them with the less confusing ¢;¢;¢;¢;¢;¢;¢;¢;¢;¢;¢;¢ (call, concatenate, repeat).

Javascript - 26 bytes
Defines f() that returns the source code character by character.
n=0;f=x=>("n=0;f="+f)[n++]

Returns undefined after it runs out of characters.

n=0;f=x=>("n=0;f="+f)[n++]
for(i=0;i<30;i++){console.log(f())} //test harness

If I'm not mistaken, you have to include the function call as part of the code.

@MamaFunRoll link to relevant meta post?

I know of none :P However, I've always thought that the function call itself was part of the quine; maybe there's something I'm missing?

@MamaFunRoll The spec specifically allows functions, so a call should not be needed. It wouldn't make much sense for this particylar challenge anyway.

Alrighty, just making sure.

stacked, noncompeting, 34 bytes
[tostr ':!' + execCounter # out]:!

A variation on the standard quine. This is a full program. This uses execCounter to get how many times this program specifically was run. Errors after outputting everything.
Try it here!

Pip, 31 bytes
{Y"{Y (yRsRPy++v)}"(yRsRPy++v)}

An anonymous function. Test it on TIO!
Explanation
Start with this standard Pip quine:
Y"Y yRsRPy"yRsRPy
Y"Y yRsRPy"        Yank that string into y
           yRsRPy  In y, replace the space with repr(y)

Wrap this in curly braces to make it a function. Now, instead of returning the whole source, we need to index into it. Using a global variable for the index and incrementing it each time will fulfill the "next character each time it's called" requirement. v is the best candidate because it is preinitialized to -1. Incrementing it the first time gives an index of 0, next time 1, etc.
Pip has cyclical indexing, so once the function prints its last character, it will start over at the beginning.

Python, 90 bytes
An extension on the standard Python quine (golfing tips welcome):
def f(n=0,s='def f(n=0,s=%r):\n while 1:yield(s%%s)[n];n+=1'):
 while 1:yield(s%s)[n];n+=1

This is a python generator function, meaning that you iterate over it, and each iteration provides the next character in the source code. When all the characters have been returned, this crashes with IndexError.
For testing, simply append this script to the end of the program:
source = ''
try:
    # Call generator, add characters to the string
    for char in f():
        source += char
except IndexError:
    # Generator has reached end of source code
    pass

print(source)

Or try it online!

Microscript II, 40 33 bytes
A code block literal, the language's closest equivalent to a function:
{ss1K+>K>s#<v{o}sl*v!(123v)lKp<o}

After running, it puts itself back into x to make it easier to invoke again.

*><>, 13 21 bytes
" r:2+a1Fi1+:1F1+[ro;

Creates a file named \n to keep track of the index.
This may be able to be golfed more, but nothing immediately jumps out at me ...
Output
$ starfish incrementalquine.sf
"$ starfish incrementalquine.sf
 $ starfish incrementalquine.sf
r$ starfish incrementalquine.sf
:$ starfish incrementalquine.sf
2$ starfish incrementalquine.sf
+$ starfish incrementalquine.sf
a$ starfish incrementalquine.sf
1$ starfish incrementalquine.sf
F$ starfish incrementalquine.sf
i$ starfish incrementalquine.sf
1$ starfish incrementalquine.sf
+$ starfish incrementalquine.sf
:$ starfish incrementalquine.sf
1$ starfish incrementalquine.sf
F$ starfish incrementalquine.sf
1$ starfish incrementalquine.sf
+$ starfish incrementalquine.sf
[$ starfish incrementalquine.sf
r$ starfish incrementalquine.sf
o$ starfish incrementalquine.sf
;$ starfish incrementalquine.sf

Explanation
" r:2+                 build the quine
      a1F              open file named "\n"
         i1+:          read input, increment by 1, duplicate
             1F        save incremented input to file
               1+[     increment input, copy that many values to a new stack
                  ro   output the character at the beginning of the new stack
                    ;  end

Cheating Incremental Quine
a1Fi1+:0go1F;

Explanation
a1F            open file named "\n"
   i1+         read input and add 1 to it
      :0g      push the value at (input,0) to the stack
         o     output the value
          1F   save the incremented input to the file
            ;  exit

haha, I had no idea you could name a file "\n". Though this technically reads the source code, by the g instruction.

@ConorO'Brien, ah fair enough. hmm ...

Does *><> have some sort of stack indexing? Or command repetition? Then, you can use the standard quine framework "your code goes here; for ><>, then access the nth member on the stack

@ConorO'Brien yeah Teal Pelican showed me this quine variant on my other cheating quine answer :).

@redstarcoder I've been working more on quines (YAY!) and I figured out a nice trick, if you replace r for # you can :1- the # like; #;or[+1F1:+1iF1a-1:" I cannot test this at the moment but I believe it cuts 1 byte from your code. ><> quines can be done like #o<-1:" etc :D

@Tealpelican haha that's really cool and thanks again! I'll definitely remember these. I still get 21 bytes though because it seems you need a } :p, otherwise the " is output first! #;or[+1F1:+1iF1a}-1:" it does seem like it can be golfed more still though hmm...

Mathematica, 91 bytes
Comments very welcome; I'm still learning the ropes about what quines are proper quines.
(If[!NumberQ[q], q = 0]; StringTake[ToString[#0]<>FromCharacterCode[{91, 93}], {++q}]) & []

Defines a function called repeatedly with no arguments. After the 91st call, it throws a big error and returns unevaluated.
There were two issues to overcome: first, I wanted to just use StringTake[ToString[#0]<>"[]"], but ToString[] seems to erase the quotation marks; so I had to replace "[]" by FromCharacterCode[{91, 93}]. Second, Mathematica variables start out uninitialized, so I can't call ++q before q is defined; this is why the initial If[!NumberQ[q], q = 0] is needed.
Irrelevant coda: while looking up NumberQ, I learned that Mathematica has a function called TrueQ ... which, yes, returns True if the argument is True and False if the argument is False! (The utility is that it returns False on all other arguments as well.)

Bash (and zsh, ksh), 39-bytes
a=`<$0`;pwd>>0;echo ${a:`wc -l<0`-1:1}

It prints nothing after once the program is printed out.
Ensure 0 does not exists in the current directory and run:
bash iquine.bash

Welcome to PPCG! You've got a clever idea for incrementing the index. Unfortunately, it looks like this answer works by reading its own source code, which means it's not a valid quine by our standards. If you modify it to use quine techniques other than reading its own source, it'll be a good answer.

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/


text:
Find the nearest Date, given a TargetDate and Day of Week
Find the nearest Date to a TargetDate for a given Day of Week.
For example, given a date of 20161219 and a day of week of Friday (6), the answer is 20161216.
Another example, given a date of 20161219 and a day of week of Wednesday (4), the answer is 20161221.
A final example, given a date of 20161219 and a day of week of Monday (2), the answer is 20161219.
Rules:

The Date format for the input and output must match. In the examples, I used yyyymmdd, but you may use any format as long as the year (at least two digits), month, and day of month are "human readable".
Day of Week is input as an integer. In my example, Sunday is the first day of the week, therefore it is day of week number 1. You can have any Day of Week numbering, as long as you note it when it differs from the example.
Years 1970 through 2030 must be accommodated.
Common language date tools and libraries are allowed, but street cred is given to those that choose not to use them.
Least number of bytes wins.

Could answers take the date in a different form if convenient? Also the days of the week also seen inconvenient for languages that take Monday to be the first day of the week

Yeah, the strict format requirements make this task more about parsing/converting/formatting, than about the actual date finding. Would have IMO been better to specify it along the lines of "You can accept the date and weekday in any reasonable format, as long as you use the same format for input and output.". But since a bunch of people have already submitted answers,I guess it has to be keep it as it is now.

@smls I agree. Lesson learned for next time.

@BrettVanderVeen I don't think it is too late to relax the requirements. You can just add a comment to each of the (currently 8) answers about the updated spec. I've done such on occasion.

Perl 6, 46 bytes
{~first *.day-of-week==$^b,Date.new($^a)-3..*}

A lambda that accepts two arguments: A date string in yyyy-mm-dd format, and a weekday number between 1=Monday and 7=Sunday.
Explanation:
                           Date.new($^a)       # Construct Date object from first argument.
                                        -3     # Subtract 3 days.
                                          ..*  # Construct a Range from that, to infinity.
  first                   ,                    # Iterate the range, and return first date...
        *.day-of-week==$^b                     # whose weekday number equals the second arg.

Using the date and weekday format used in the examples, it would be 88 bytes:
{S:g/\-//with ~first *.day-of-week==($^b-2)%7+1,Date.new(|($^a~~/(....)(..)(..)/))-3..*}

FYI, I eased up on the date and day of week format rules. Feel free to resubmit.

@BrettVanderVeen: Updated.

Perl 6, 83 bytes
->$_,\w{~(Date.new(|m/(....)(..)(..)/)-3...*.day-of-week%7+1==w)[*-1]~~{S:g/"-"//}}

Try it
Expanded
->     # pointy block lambda
  $_,
  \w
{
  ~(  # turn into a Str

    Date.new( |m/(....)(..)(..)/ ) - 3 # three days earlier
    ...                                # generate a sequence
    *.day-of-week % 7 + 1 == w         # stop when the right day is found

  )[*-1]  # the last one

  ~~      # apply the following block

  {
    S:g/"-"//  # remove ｢-｣
  }
}

FYI, I eased up on the date and day of week format rules. Feel free to resubmit.

JavaScript (ES6), 93 bytes
(s,n,d=new Date(s))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toISOString().slice(0,10)

Uses %Y-%m-%d date format. If %a %b %d %Y is an acceptable date format, then for 82 bytes:
(s,n,d=new Date(s))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toDateString()

I could save a further 2 bytes by requiring Sunday = 10 to Saturday = 16, but that's a silly day of week mapping. Previous 142 141 bytes (thanks to @Guedes) version that used the specific YYYYMMDD date format, with its explanation:
(s,n,d=new Date(s.replace(/(?=..(..)?$)/g,'-')))=>d.setDate(d.getDate()+(n+9-d.getDay())%7-3)&&d.toISOString().replace(/-(..)-(..).*/,'$1$2')

This feels far too long. Explanation: First, inserts -s into the date to get it into ISO format which new Date can then parse. Then, compares the desired day with the actual day to get a value between -3 and 3 for the actual offset. The magic 9 comes from 7 (because % is CPU modulo, not true modulo) plus 3 (for the -3 offset) minus 1 (because n is 1-indexed and getDay is 0-indexed). The date is then converted back into ISO format and the unwanted characters removed.

You can save one byte changing the first replace to .replace(/(?=..(..)?$)/g,'-')

FYI, I eased up on the date and day of week format rules. Feel free to resubmit.

Bash + coreutils, 50
date -d$1+$[($2-`date -d$1 +%u`+9)%7-3]day +%Y%m%d

Try it online.

date -d$1 +%u gives the day of week (1..7); 1 is Monday
This is subtracted from the input day of week to give a difference of day indexes.  We want to add a factor between in the range [-3, 3] to the input date to get the closest date, so we add a magic factor 9, take the modulo 7, then subtract 3.  The magic factor 9 is 3 + 7 - 1.  The 3 adjusts the input range for range [-3, 3], and is subtracted again after the modulo.  The 7 is required because bash modulo is the same as CPU modulo and can give -ve results - adding 7 adjusts into the right range.  The -1 is because in the input, 1 is Sunday, but with the %u output, 1 is Monday.
The outer date then parses <input date> + <magic factor>days and presents it in the YYYYMMDD format.

FYI, I eased up on the date and day of week format rules. Feel free to resubmit.

Python, 150 149 bytes
from datetime import*
lambda s,n,t='%Y%m%d':[d for d in[datetime.strptime(s,t)+timedelta(o-3)for o in range(7)]if(n-2)%7==d.weekday()][0].strftime(t)

Oouuf, 149. repl.it
Unnamed function that takes a string s, the date as specified (using format string t='%Y%m%d' for both input and output) and a number in [1,7], n.
Inspects the seven days from three days prior to three days after that given for the day of the week requested.
The week in datetime starts on Monday and is zero based, so the test is (n-2)%7==d.weekday().

FYI, I eased up on the date and day of week format rules. Feel free to resubmit.

R, 119 77 56 bytes
Unnamed function that takes two inputs, the date D (string) and the day d (numeric).
function(D,d,s=-3:3+as.Date(D))s[lubridate::wday(s)==d]

Uses the function wday() from the lubridate package. It can conveniently convert Date objects into week days with 1 being treated as Sunday by default.
Edit: I/O is now the default of the as.Date() function: "YYYY-mm-dd"
Ungolfed and Explained
function(D,d){
    D=as.Date(D);            # Format input date
    s=-3:3+D;                # Generate sequence of +- 3 days
    s[lubridate::wday(s)==d] # Match the weekday that equals to target day
}

Edit: Now creates a sequence of +-3 days for which any given weekday is guaranteed to be found in. Subsequently we only have to match one day which made the problem much easier.

FYI, I eased up on the date and day of week format rules. Feel free to resubmit.

@BrettVanderVeen Thanks, updated.

Mathematica, 85 49 bytes
#~DatePlus~Mod[#2-#~DateValue~"ISOWeekDay",7,-3]&

The input format for dates is either a list like {2016, 12, 16} or an actual DateObject (I think a few others work as well, but I've tested these). In either case, the output format will match automatically. The day numbering starts from 1 on Mondays.
The idea is to compute the difference between the input weekday and the target weekday with #2-#~DateValue~"ISOWeekDay" and then to map it into [-3, 3] using a modulo with offset (i.e. Mod[...,7,-3]). The result is simply added to the input date (the default unit for date object addition is days).

FYI, I eased up on the date and day of week format rules. Feel free to resubmit.

@BrettVanderVeen thanks, edited.

SAS Macro Language, 110 Bytes
%macro s(d,a);%put %sysfunc(putn(%sysfunc(intnx(week.&a.,%eval(%sysfunc(putn(&d,8.))-4),1)),yymmddn8.));%mend;

A terrible golfing language but here's the explanation (from the inside out):
Create a macro s that accepts a date input d and a numeric weekday a. Then %eval(%sysfunc(putn(&d,8.))-4) converts the date to a SAS numeric date and decrements it by 4 days. The intnx function then returns the next occurrence of the specified weekday. putn then formats the date back to yyyymmdd and %put prints the output to the log.

FYI, I eased up on the date and day of week format rules. Feel free to resubmit.

Shell + GNU date, 43 bytes
date +%F -d$1-3day`date -d$1+$2day +%w`day

I wish I could explain how this works, but there was so much trial-and-error tweaking it no longer makes sense even to me!  We start by subtracting three days so that adding a number in range 0-6 gives the nearest.   But why adding the desired weekday to the target date gives the necessary offset has slipped my grasp.
Input as in the question; output format is YYYY-MM-DD.
Online test