# Ways to add 1 to lists of lists

In this challenge you will take a list of lists of integers, e.g.

A = [[1,2],[3,4],[5],[]]


And an additional single integer (e.g. n = 7). If you were to add n to the front of one of the lists in A there would be as many ways to do that as there are lists in A. In this example 4:

A' = [[7,1,2],[3,4],[5],[]]
A' = [[1,2],[7,3,4],[5],[]]
A' = [[1,2],[3,4],[7,5],[]]
A' = [[1,2],[3,4],[5],[7]]


In this challenge you will output all possible ways to do this, in the order of how early n is inserted. So for the example the output is just:

[ [[7,1,2],[3,4],[5],[]]
, [[1,2],[7,3,4],[5],[]]
, [[1,2],[3,4],[7,5],[]]
, [[1,2],[3,4],[5],[7]]
]


This is so answer answers will be scored in bytes with fewer bytes being better.

## Test cases

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

• The lists aren't guaranteed to be unique, right?
– att
Nov 18, 2021 at 4:19

# Rust, 185 184 bytes

My first ever code golf submission

fn r(a:Vec<Vec<u8>>,n:u8){let mut x:Vec<Vec<Vec<u8>>>=Vec::new();for i in 0..a.len(){let mut b=a.clone();let c=&vec![n];b[i].splice(0..0,c.iter().cloned());x.push(b);}print!("{:?}",x)}


Explanation

This code copies the list for every sublist, then appends the number to the front of it, adds it to a final list which it then prints. We can also get away with returning the print statement to save a ;!

Try it online!

Edit: Kevin Cruijssen pointed out a space in my print.

Edit: @Bubbler showed me what it's like to truly golf in Rust and got it down to 90 bytes! I won't be updating the byte count in the header since I don't believe that his edits counts as "edits" rather an entire new submission and it doesn't reflect my work.

|a:&mut[Vec<_>],n|{for i in 0..a.len(){a[i].insert(0,n);print!("{:?}",a);a[i].remove(0);}}

• Welcome to Code Golf, and nice first answer! Submissions are required to make a serious effort to meet the winning criteria as much as possible, in this case code-golf. You did a pretty good job of that already with short variable names and things like that, but you should make sure to also remove unnecessary whitespace. Nov 17, 2021 at 17:21
• No problem, glad to help! Also, I don't know personally know anything about Rust, but you should check out our tips for golfing in Rust to see if there are any other golfs you could use. Happy golfing! Nov 17, 2021 at 17:24
• You forgot to remove 1 space in your print. :) Nov 17, 2021 at 17:38
• With lots of type and output format fiddling, it is possible to get down to 98 bytes. Nov 18, 2021 at 1:59
• And 90 as a closure. Nov 18, 2021 at 2:03

This is Willem Van Onsem's SO answer with a couple of trivial golfs.

n!(a:b)=((n:a):b):map(a:)(n!b)
_!_=[]


Try it online!

# 05AB1E, 6 bytes

UεXšNǝ


Explanation:

U       # Pop the store the first (implicit) input-integer in variable X
ε      # Map over the second (implicit) input-list of lists:
Xš    #  Prepend X in front of the current part
Nǝ  #  And replace the item at the current map-index in the second (implicit)
#  input-list with this modified part
# (after which the result is output implicitly)


# APL+WIN, 36 bytes

Prompts for the list of lists as a nested vector then the integer to be added. Index origin = 0

m←((⍴n)*2)⍴n←,⎕⋄m[(1+⍴n)×⍳⍴n]←⎕,¨n⋄m


Try it online! Thanks to Dyalog Classic

# J, 22 17 21 20 bytes

(<@#"0~[:=#\),&.>"1]


Try it online!

Could save 4 bytes if we can assume each element of the input is unique.

Consider 7 f 1 2 3; 1 2; 4:

• [:=#\ Create an identity matrix whose sides equal our list length:

1 0 0
0 1 0
0 0 1

• <@#"0~ Use that as a mask to copy our new element, and box each result. Zeros become empty boxes:

┌─┬─┬─┐
│7│ │ │
├─┼─┼─┤
│ │7│ │
├─┼─┼─┤
│ │ │7│
└─┴─┴─┘

• ,&.>"1] For each row, join elementwise to the original input:

┌───────┬─────┬───┐
│7 1 2 3│1 2  │4  │
├───────┼─────┼───┤
│1 2 3  │7 1 2│4  │
├───────┼─────┼───┤
│1 2 3  │1 2  │7 4│
└───────┴─────┴───┘


# JavaScript (Node.js), 41 bytes

t=>a=>a.map(u=>a.map(v=>u==v?[t,...u]:v))


Try it online!

# Retina, 33 bytes

L$\[+(?=(.+),(.+))$>$2,$1
,]
]


Try it online! Takes n as the second argument. Explanation:

L$\[+(?=(.+),(.+))  Find the beginning of each list. $>$2,$1


For each occurrence, output the list with n moved to that position.

,]
]


Fix up the list if it was originally empty.

# R, 58 bytes

Or R>=4.1, 44 bytes by replacing two function occurrences with \s.

function(x,A)Map(function(i){A[[i]]=c(x,A[[i]]);A},seq(A))


Try it online!

# Julia 1.0, 47 bytes

n\l=(k=keys(l)).|>i->k.|>j->[fill(n,i==j);l[j]]


Try it online!

# Ruby, 60 bytes

->n,l{(0...t=l.size).map{|i|[*l[0,i],[n]+l[i],*l[i+1...t]]}}


Try it online!

# Wolfram Language (Mathematica), 31 bytes

(i=1;x##~Insert~{i++,1})/@#&


Try it online!

# ayr, 15 bytes

Beats J by 5 bytes, so I'm happy :)

],"\:]:#":i:&#


# Explanation

           i:&#    Construct an NxN identity matrix (N = # lists)
#":        Foreach num I in that, replace with left arg I times
]:           Convert that to a hook
\:             For each item on the right and entirety of left
,"               Concatenate left to back of right on an element x element basis
]                  Where the left is the list


Takes the number on the left and the list of lists on the right.

# Vyxal, 11 9 bytes

ẏƛ¹n~i⁰pȦ


Try it Online!

I'm sure Aaron or Emanresu will come along and outgolf me with better use of stack/context, but for now, gaming. Turns out I did that.

## Explained

ẏƛ¹n~i⁰pȦ   # Full program, takes the nested lists (A) and then the integer (n)
ẏ           # Push the range [0, len(A))
ƛ          # and to each item I:
¹n~i      #     push A[I] without popping the top two items on the stack
⁰p    #     prepend n to that
Ȧ   #     and A[I] = that


# Charcoal, 16 bytes

ＩＥηＥη⎇⁼κμ⮌⊞Ｏ⮌λθλ


Try it online! Link is to verbose version of code. Explanation:

  η                 Input list of lists
Ｅ                  Map over each list
η               Input list of lists
Ｅ                Map over each list
κ            Outer index
⁼             Equal to
μ           Inner index
⎇              If true then
λ      Current list
⮌       Reversed
θ     Input n
⊞Ｏ        Appended
⮌          Reversed
λ    Otherwise current list
Ｉ                   Cast to string
Implicitly print


Charcoal's default output format might be a little tricky to read, so here's a 17-byte version with prettier output:

Ｅη⭆¹Ｅη⎇⁼κξ⮌⊞Ｏ⮌νθν


Try it online! Link is to verbose version of code.

# Python 3, 50 bytes

lambda a,L:[[[a][:l is k]+l for l in L]for k in L]


Try it online!

Will not work on lists with multiple references to the same object. I..e.: L = [[10],[10]] fine (same value but different objects) but L = 2*[[10]] fail (twice the same object)

# JavaScript (ES6), 44 bytes

Expects (n)(list_of_lists).

### Version 1

n=>a=>a.map((v,i,[...b])=>(b[i]=[n,...v],b))


Try it online!

### Version 2

n=>a=>a.map((_,i)=>a.map(v=>i--?v:[n,...v]))


Try it online!

# Pari/GP, 48 bytes

(n,a)->matrix(#a,,i,j,concat([n][1..i==j],a[j]))


Try it online!

# jq, 51 bytes

. as$a|[range(length)]|map(. as$i|$a|.[$i]|=[$n]+.)  Where $n is n.

# Pip-xP, 13 bytes

aRA_(BPEb)MEa


Attempt This Online!

### Explanation

The -x flag evaluates the inputs, meaning we can treat [[1];[2;3]] as a list rather than a string.

aRA_(BPEb)MEa
a  First command-line input (the nested list)
ME   Map the following function to that list, enumerated (first function arg
is index, second function arg is sublist):
a               The whole list
RA             Replace the element at index given by
_            first function arg
(    )      with
B          second function arg
PE        with the following value prepended:
b       Second command-line input


The -P flag prints each sublist of the result, formatted as a list, on a separate line. Other formats that could work include -p and -S.

# Ruby, 42 bytes

->n,l{i=-1;l.map{|w|z=*l;z[i+=1]=[n]+w;z}}


Try it online!

• ->n,l{i=-1;l.map{z=*l;z[i+=1]=[n]+_1;z}} to save 2 bytes Nov 20, 2021 at 14:18

# Burlesque, 24 bytes

1svsa.*zi{{1gv+]}x/ap}^m


Try it online!

I'm sure there's a better way...

1sv    # Save input as 1
sa.*   # Repeat arr len(arr) times
zi     # Zip with indices
{
{
1gv  # Get input (value1)
+]   # Prepend
}
x/    # Reorder local stack
ap    # Apply function to index (from zip)
}^m    # Push and map each


# Stax, 10 bytes

ü↨○◘╞Q┐p☺Ç


Run and debug it