Issubset() but order matters

Is there a function that returns true or false whenever one vector is a subvector from another? issubset() does not implies order.

Thanks!

I don’t believe so, but you could roll your own pretty easily.

setdiff() is order-sensitive so you can probably use it in combination with isempty?

One proposal:

function issubvec(sv, v)
    ix = Int64[]
    for s in sv
        i = findfirst(==(s), v)
        isnothing(i) && return false
        push!(ix, i)
    end
    return (length(ix) == length(sv)) && issorted(ix)
end

Examples:

sv = [7, 3, 5]
issubvec(sv, collect(1:10))         # false
issubvec(sv, [1, 7, 2, 3, 5, 4])    # true
issubvec(sv, [])                    # false
issubvec(sv, [3, 5, 7])             # false
issubvec([], [3, 5, 7])             # true
issubvec([], [])                    # true
2 Likes

A non-allocating (and a bit faster) version would be:

function issubvec(sv::AbstractVector, v::AbstractVector)
    i = firstindex(v)
    for s in sv
        i = findnext(==(s), v, i)
        isnothing(i) && return false
        i += 1
    end
    return true
end
6 Likes

After all the fat of the Christmas holidays, this pretty lean code by @bkamins is quite healthy.

2 Likes