14
\$\begingroup\$

Adapted from this StackOverflow question

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]]]
\$\endgroup\$
6
  • \$\begingroup\$ Can the added number already be in the lists? This might matter if solutions try to remove the number after each insertion. \$\endgroup\$
    – xnor
    Nov 17 at 18:18
  • \$\begingroup\$ @xnor Added a new test case covering that. \$\endgroup\$
    – Grain Ghost
    Nov 17 at 19:26
  • \$\begingroup\$ The first test case is weird. What if it was 9, [[]]? \$\endgroup\$
    – roblogic
    Nov 18 at 0:06
  • 1
    \$\begingroup\$ @roblogic That case has been added the result is [[[9]]]. \$\endgroup\$
    – Grain Ghost
    Nov 18 at 1:57
  • 1
    \$\begingroup\$ @GrainGhost it looks like the newly added test case is incorrect, shouldn't it be 9, [[]] -> [[[9]]]? All the other cases with a nest list result in one additional layer of nesting. \$\endgroup\$
    – Tyberius
    Nov 19 at 18:01

22 Answers 22

10
\$\begingroup\$

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);}}
\$\endgroup\$
8
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Nov 17 at 17:21
  • 1
    \$\begingroup\$ 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! \$\endgroup\$ Nov 17 at 17:24
  • 1
    \$\begingroup\$ You forgot to remove 1 space in your print. :) \$\endgroup\$ Nov 17 at 17:38
  • 2
    \$\begingroup\$ With lots of type and output format fiddling, it is possible to get down to 98 bytes. \$\endgroup\$
    – Bubbler
    Nov 18 at 1:59
  • 3
    \$\begingroup\$ And 90 as a closure. \$\endgroup\$
    – Bubbler
    Nov 18 at 2:03
6
\$\begingroup\$

Haskell, 37 bytes

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!

\$\endgroup\$
6
\$\begingroup\$

05AB1E, 6 bytes

UεXšNǝ

Try it online or verify all test cases.

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)
\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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│
    └───────┴─────┴───┘
    
\$\endgroup\$
3
\$\begingroup\$

JavaScript (Node.js), 41 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

Julia 1.0, 47 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Ruby, 60 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 31 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
1
\$\begingroup\$

Charcoal, 16 bytes

IEηEη⎇⁼κμ⮌⊞O⮌λθλ

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

  η                 Input list of lists
 E                  Map over each list
    η               Input list of lists
   E                Map over each list
       κ            Outer index
      ⁼             Equal to
        μ           Inner index
     ⎇              If true then
             λ      Current list
            ⮌       Reversed
              θ     Input `n`
          ⊞O        Appended
         ⮌          Reversed
               λ    Otherwise current list
I                   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:

Eη⭆¹Eη⎇⁼κξ⮌⊞O⮌νθν

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

\$\endgroup\$
1
\$\begingroup\$

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)

\$\endgroup\$
1
\$\begingroup\$

Pip -xP, 13 bytes

aRA_(BPEb)MEa

Replit! Or, with a header simulating the -x flag: Try it 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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Pari/GP, 48 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

jq, 51 bytes

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

Where $n is n.

\$\endgroup\$
0
\$\begingroup\$

Ruby, 42 bytes

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

Try it online!

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

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
\$\endgroup\$
0
\$\begingroup\$

Stax, 10 bytes

ü↨○◘╞Q┐p☺Ç

Run and debug it

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.