16
\$\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\$
1
  • \$\begingroup\$ The lists aren't guaranteed to be unique, right? \$\endgroup\$
    – att
    Nov 18, 2021 at 4:19

24 Answers 24

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, 2021 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, 2021 at 17:24
  • 1
    \$\begingroup\$ You forgot to remove 1 space in your print. :) \$\endgroup\$ Nov 17, 2021 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, 2021 at 1:59
  • 3
    \$\begingroup\$ And 90 as a closure. \$\endgroup\$
    – Bubbler
    Nov 18, 2021 at 2:03
7
\$\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\$
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\$
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\$
3
\$\begingroup\$

Wolfram Language (Mathematica), 31 bytes

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

Try it online!

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

Vyxal, 54 bitsv2, 6.75 bytes

vJ¨2¹^Ȧ

Try it Online!

Bitstring:

100010101100011111000100110100010110110111100010110010
\$\endgroup\$
1
3
\$\begingroup\$

Uiua, 13 12 bytes

≡⍜(⇌⊔⊡)⊂⇡⊃⧻¤

Try it!

-1 thanks to Bubbler

≡⍜(⇌⊔⊡)⊂⇡⊃⧻¤
         ⊃⧻¤  # fix the array and get its length
        ⇡     # range (of length)
≡⍜(⇌⊔⊡)       # change each unboxed reversed row by...
       ⊂      # join (the integer input)
              # then unreverse, re-box, and put each item back
\$\endgroup\$
2
  • 1
    \$\begingroup\$ ⍜⊡(□⊂:⊔) -> ⍜(⇌⊔⊡)⊂ to save 1. \$\endgroup\$
    – Bubbler
    Nov 21 at 1:53
  • \$\begingroup\$ @Bubbler Clever, thanks! \$\endgroup\$
    – chunes
    Nov 21 at 2:36
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\$

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\$
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\$

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\$
2
\$\begingroup\$

jq, 51 bytes

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

Where $n is n.

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

Curry (PAKCS), 21 bytes

n!(a++b:c)=a++(n:b):c

Attempt This Online!

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

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\$

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.

\$\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\$
    – Wezl
    Nov 20, 2021 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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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