Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

5 of 5
added 86 characters in body
digEmAll
  • 5.1k
  • 15
  • 22

R, (削除) 95 (削除ここまで), 94 bytes

Assuming combn always returns sorted indexes

At the moment the assumption is valid in all R versions, but is not documented; the alternative (longer) solution is reported at the bottom of the answer

  • -1 byte thanks to @Dominc van Essen
function(v,s,`+`=length){for(x in combn(+v,+s,,F))if(all(v[x]==s)&+v[T]>+(y=x:x[+x]))T=y;v[T]}

Try it online!

Unrolled code with explanation:

function(v,s){ # take full vector v and the vector to search s
 r=v # init shortest slice r to full vector v
 for(x in combn(length(v), # for each combination x of length(s) elements taken 
 length(s),,F){ # from the vector of indexes 1:length(v)
 # (we assume x is sorted ascending)
 a=v[x:x[+x]] # get the slice between first and last index in x 
 if(all(v[x]==s) & # if the values of the combinations == s and
 length(r) > length(a)) # the slice is shorter than r
 r=a # store the new slice
 }
 r # return the shortest slice
}

Version without assumption:

R, 107 bytes

function(v,s,r=v,`+`=length){for(x in combn(+v,+s,,F)){y=sort(x);if(all(v[x]==s)&+r>+(a=v[x:x[+x]]))r=a};r}

Try it online!

digEmAll
  • 5.1k
  • 15
  • 22

AltStyle によって変換されたページ (->オリジナル) /