Generalised Array Riffle
Python 2, 54
lambda B,*X:map(B.insert,*zip(*sorted(zip(*X))[::-1]))
Takes input as B,I,V
. Modifies the input B
when called (thanks to Martin Büttner for reminding me this is possible).
Uses map
to call B.insert
on each index/element pair. To avoid the issue of the list indices shifting as elements are inserted, sorts the pairs in decreasing order of index by an ugly zip/sort/unzip. If not for the shifting issue, we could just do map(B.insert,*X)
.
Old method (65):
B,V,I=input()
for i,v in sorted(zip(I,V))[::-1]:B[i:i]=v,
print B
Pyth, 14 bytes
s.icFPQmedSCtQ
Demonstration.
This program takes the inputs as a 3-tuple of lists in the order Base, Indices, Values.
Explanation on the example [5, 1, 4, 1, 3], [5, 0, 3], [0, 0, 7]
:
Take the input: implicit, Q is the input.
Make the index, value pairs:
CtQ
=[(5, 0), (0, 0), (3, 7)]
Sort the pairs into increasing index order:
SCtQ
=[(0, 0), (3, 7), (5, 0)]
Take the value out of each pair:
medSCtQ
=[0, 7, 0]
Split the base list at the location of the indicies:
cFPQ
=[[], [5, 1, 4], [1, 3], []]
Interleave 3 and 4:
.icFPQmedSCtQ
=[[], 0, [5, 1, 4], 7, [1, 3], 0, []]
Combine into one list:
s.icFPQmedSCtQ
=[0, 5, 1, 4, 7, 1, 3, 0]
Haskell, 62 bytes
import Data.List
f b v i=map snd$sort$zip[0.5,1.5..]b++zip i v
Usage example: f [5,1,4,1,3] [0,0,7] [5,0,3]
-> [0,5,1,4,7,1,3,0]
.
How it works: augment the base list with "and-a-half" indices starting at 0.5
(e.g. [(0.5,5),(1.5,1),(2.5,4),(3.5,1),(4.5,3)]
) and concatenate it with the index-value pairs. Sort and discard the index.
Remark: don't know if I'm cheating here. From a mathematical point of view it's fine, but a programmer might argue that the list of indices [5,0,3]
is not a list of Integers
as requested, but a list of Fractionals
(to be exact, the type is polymorphic, but must belong to the Fractional
class, e.g. Float
or Double
).