I would like to filter collection, so distance between adjacent elements would be at least 5.
So List(1, 2, 3, 4, 5, 6, 7, 11, 20) will become List(1, 6, 11, 20).
Is it possible to achieve in one pass using filter? What would be scala-way?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try with
foldLeft():If it’s not obvious:
Algorithm starts with first element (probably you need some edge cases handled) in the
outputcollectionIt iterates over all remaining elements from the
input. If the difference between this element (cur) and first element ofinputis greater than or equal than5, prepend toinput. Otherwise skip and proceedinputwas built by prepending and examiningheadto get better performance..reverseis needed in the endThis is basically how you would implement this in imperative way, but with more concise syntax.