Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - Find nearest smaller number in array

I would like to be able to find the nearest smaller value in an array of numbers. For instance, if I have:

[1, 4, 6, 9, 14, 39]

And I'm looking for the nearest value smaller than:

8

The function would return:

6

Additionally, if I pass a number greater than the maximum value in the array, it should return the maximum. If I pass a number smaller than the minimum, it should return nil.

I tried doing this using the first function on arrays, however this on its own doesn't produce the result I'm looking for as I would need something like this:

numbers.first(where: { $0 <= target && $1 < target })

but unfortunately, this isn't valid. Any suggestions? I know this could be done fairly trivially with a while loop, however I was hoping there would be a cleaner, functional way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given that the array is sorted , You need

if let value = numbers.last(where: { $0 <= target }) {
  print(value)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...