How to interpolate from number in one range to a corresponding value in another range?How does one make random number between range for arc4random_uniform()?How do I generate random integers within a specific range in Java?How to use a decimal range() step value?Generating random whole numbers in JavaScript in a specific range?How do you round UP a number in Python?How to scale down a range of numbers with a known min and max valueHow to call Objective-C code from SwiftHow do I check if a string contains another string in Swift?Swift Beta performance: sorting arraysHow does one make random number between range for arc4random_uniform()?What are the differences between functions and methods in Swift?

Do I have a right to cancel a purchase of foreign currency in the UK?

OR-backed serious games

Is there a strong legal guarantee that the U.S. can give to another country that it won't attack them?

What's it called when the bad guy gets eaten?

What happens to unproductive professors?

Were initial voiced stops voiceless in early Latin?

How do we handle pauses in a dialogue?

Would it be appropriate to sand a floor between coats of poly with a handheld orbital sander?

Single word for "refusing to move to next activity unless present one is completed."

Can Jimmy hang on his rope?

What's the point of having a RAID 1 configuration over incremental backups to a secondary drive?

Why is the ladder of the LM always in the dark side of the LM?

LED glows slightly during soldering

Is English unusual in having no second person plural form?

What are the original Russian words for a prostitute?

Disc brake equipped time trial bikes in grand tour

What is the right approach to quit a job during probation period for a competing offer?

Integer Lists of Noah

How can I get a player to accept that they should stop trying to pull stunts without thinking them through first?

Managing and organizing the massively increased number of classes after switching to SOLID?

Is it OK to leave real names & info visible in business card portfolio?

What is this little owl-like bird?

Does a wizard need their hands free in order to cause their familiar from the Find Familiar spell to reappear?

Is there any reason why MCU changed the Snap to Blip



How to interpolate from number in one range to a corresponding value in another range?


How does one make random number between range for arc4random_uniform()?How do I generate random integers within a specific range in Java?How to use a decimal range() step value?Generating random whole numbers in JavaScript in a specific range?How do you round UP a number in Python?How to scale down a range of numbers with a known min and max valueHow to call Objective-C code from SwiftHow do I check if a string contains another string in Swift?Swift Beta performance: sorting arraysHow does one make random number between range for arc4random_uniform()?What are the differences between functions and methods in Swift?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I currently receive a Int that could be anywhere between 0 and 180,000. I need to change it to fit between 0 and 3000. I know in other languages you can use something like



Map(min1,max1,min2,max2,input)


I can't seem to find something like that inside of swift.
This is what I currently have, but it always returns 0.



var newY = [(Int)(input)]
newY = newY.map _ in 0 * 3000
print(newY[0])


I think I am using the wrong function. I have never done any mapping in Swift before.










share|improve this question
























  • stackoverflow.com/questions/24132399/…

    – Sahil
    Mar 15 '17 at 17:50











  • What does "keep a number between two numbers" mean? Do you want to generate a random number?

    – Andrew Brooke
    Mar 15 '17 at 17:51











  • Your question is unclear, but documentation on map can be found here.

    – Caleb
    Mar 15 '17 at 17:55











  • Lets say you get a value 3003: should this be mapped to 3, or to an integer of the size ~3000*3003/180000 (~50)?

    – dfri
    Mar 15 '17 at 17:57












  • Which other language does your example come from? It might be easier to answer your question if I could see the definition of how that one behaves.

    – Phillip Mills
    Mar 15 '17 at 18:02

















0















I currently receive a Int that could be anywhere between 0 and 180,000. I need to change it to fit between 0 and 3000. I know in other languages you can use something like



Map(min1,max1,min2,max2,input)


I can't seem to find something like that inside of swift.
This is what I currently have, but it always returns 0.



var newY = [(Int)(input)]
newY = newY.map _ in 0 * 3000
print(newY[0])


I think I am using the wrong function. I have never done any mapping in Swift before.










share|improve this question
























  • stackoverflow.com/questions/24132399/…

    – Sahil
    Mar 15 '17 at 17:50











  • What does "keep a number between two numbers" mean? Do you want to generate a random number?

    – Andrew Brooke
    Mar 15 '17 at 17:51











  • Your question is unclear, but documentation on map can be found here.

    – Caleb
    Mar 15 '17 at 17:55











  • Lets say you get a value 3003: should this be mapped to 3, or to an integer of the size ~3000*3003/180000 (~50)?

    – dfri
    Mar 15 '17 at 17:57












  • Which other language does your example come from? It might be easier to answer your question if I could see the definition of how that one behaves.

    – Phillip Mills
    Mar 15 '17 at 18:02













0












0








0


1






I currently receive a Int that could be anywhere between 0 and 180,000. I need to change it to fit between 0 and 3000. I know in other languages you can use something like



Map(min1,max1,min2,max2,input)


I can't seem to find something like that inside of swift.
This is what I currently have, but it always returns 0.



var newY = [(Int)(input)]
newY = newY.map _ in 0 * 3000
print(newY[0])


I think I am using the wrong function. I have never done any mapping in Swift before.










share|improve this question
















I currently receive a Int that could be anywhere between 0 and 180,000. I need to change it to fit between 0 and 3000. I know in other languages you can use something like



Map(min1,max1,min2,max2,input)


I can't seem to find something like that inside of swift.
This is what I currently have, but it always returns 0.



var newY = [(Int)(input)]
newY = newY.map _ in 0 * 3000
print(newY[0])


I think I am using the wrong function. I have never done any mapping in Swift before.







swift integer range






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 15 '17 at 18:28









Travis Griggs

10.8k16 gold badges63 silver badges113 bronze badges




10.8k16 gold badges63 silver badges113 bronze badges










asked Mar 15 '17 at 17:43









Jacob BashistaJacob Bashista

371 silver badge8 bronze badges




371 silver badge8 bronze badges












  • stackoverflow.com/questions/24132399/…

    – Sahil
    Mar 15 '17 at 17:50











  • What does "keep a number between two numbers" mean? Do you want to generate a random number?

    – Andrew Brooke
    Mar 15 '17 at 17:51











  • Your question is unclear, but documentation on map can be found here.

    – Caleb
    Mar 15 '17 at 17:55











  • Lets say you get a value 3003: should this be mapped to 3, or to an integer of the size ~3000*3003/180000 (~50)?

    – dfri
    Mar 15 '17 at 17:57












  • Which other language does your example come from? It might be easier to answer your question if I could see the definition of how that one behaves.

    – Phillip Mills
    Mar 15 '17 at 18:02

















  • stackoverflow.com/questions/24132399/…

    – Sahil
    Mar 15 '17 at 17:50











  • What does "keep a number between two numbers" mean? Do you want to generate a random number?

    – Andrew Brooke
    Mar 15 '17 at 17:51











  • Your question is unclear, but documentation on map can be found here.

    – Caleb
    Mar 15 '17 at 17:55











  • Lets say you get a value 3003: should this be mapped to 3, or to an integer of the size ~3000*3003/180000 (~50)?

    – dfri
    Mar 15 '17 at 17:57












  • Which other language does your example come from? It might be easier to answer your question if I could see the definition of how that one behaves.

    – Phillip Mills
    Mar 15 '17 at 18:02
















stackoverflow.com/questions/24132399/…

– Sahil
Mar 15 '17 at 17:50





stackoverflow.com/questions/24132399/…

– Sahil
Mar 15 '17 at 17:50













What does "keep a number between two numbers" mean? Do you want to generate a random number?

– Andrew Brooke
Mar 15 '17 at 17:51





What does "keep a number between two numbers" mean? Do you want to generate a random number?

– Andrew Brooke
Mar 15 '17 at 17:51













Your question is unclear, but documentation on map can be found here.

– Caleb
Mar 15 '17 at 17:55





Your question is unclear, but documentation on map can be found here.

– Caleb
Mar 15 '17 at 17:55













Lets say you get a value 3003: should this be mapped to 3, or to an integer of the size ~3000*3003/180000 (~50)?

– dfri
Mar 15 '17 at 17:57






Lets say you get a value 3003: should this be mapped to 3, or to an integer of the size ~3000*3003/180000 (~50)?

– dfri
Mar 15 '17 at 17:57














Which other language does your example come from? It might be easier to answer your question if I could see the definition of how that one behaves.

– Phillip Mills
Mar 15 '17 at 18:02





Which other language does your example come from? It might be easier to answer your question if I could see the definition of how that one behaves.

– Phillip Mills
Mar 15 '17 at 18:02












4 Answers
4






active

oldest

votes


















3














The map function on collections is going to do something very different. It applies a mapping function to each element of a collection and returns a new collection based on the results.



What you're looking for would be:



func map(minRange:Int, maxRange:Int, minDomain:Int, maxDomain:Int, value:Int) -> Int 
return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)


print(map(minRange: 0, maxRange: 1800000, minDomain: 0, maxDomain: 3000, value: 200000))


With only a little more work you can make it generic over all integer types:



func map<T:IntegerArithmetic>(minRange:T, maxRange:T, minDomain:T, maxDomain:T, value:T) -> T 
return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)



Another option would be to take advantage of the Swift Range type to make calling more succinct:



func map<T:IntegerArithmetic>(range:Range<T>, domain:Range<T>, value:T) -> T 
return domain.lowerBound + (domain.upperBound - domain.lowerBound) * (value - range.lowerBound) / (range.upperBound - range.lowerBound)


map(range:0..<3000, domain:0..<180000, value: 1500)





share|improve this answer

























  • There's a substantial difference between dfri's answer and mine in that due to the order of operations mine will have more even distribution while his is less likely to result in overflows. All depends on what you're looking for.

    – David Berry
    Mar 15 '17 at 18:16






  • 1





    Wouldn't it be better to suggest a different name of the new function, to avoid confusion with the existing map?

    – Travis Griggs
    Mar 15 '17 at 18:25











  • Probably, I was just keeping his name intact.

    – David Berry
    Mar 15 '17 at 18:28











  • Combined with explicit parameter naming, it seems clear enough.

    – David Berry
    Mar 15 '17 at 18:28


















0














It's not clear whether the OP simply wants to clamp (title seems to say that) or wants to interpolate from one bounding range to another. The title makes me think one, but the dual max/min values make me think they're after an interpolation. I answered the former. David Berry has a good answer for the latter.



What you may want is min/max functions. Swift has these. To "clamp" a value between a low and high value, you usually combine the two:



var bottom = 13
var top = 42
var tooLow = 7
var clamped = min(top, max(bottom, tooLow)) -> 13
var justRight = 23
clamped = min(top, max(bottom, justRight)) --> 23
var tooHigh = 99
clamped = min(top, max(bottom, tooHigh)) --> 42


This is usually the route most people go, and is probably good enough for most. I personally hate writing that again and again, and I get tired of having to think about which side to feed into the max and the min. And I don't like that it uses what looks like a free function, I'm an object oriented message sending sort of guy, so I do the following:



precedencegroup MinMaxPrecedence 
associativity: left
higherThan: NilCoalescingPrecedence, AdditionPrecedence, MultiplicationPrecedence


infix operator <> : MinMaxPrecedence

func <><T:Comparable>(a:T, b:T) -> T
return a < b ? a : b


infix operator >< : MinMaxPrecedence

func ><<T:Comparable>(a:T, b:T) -> T
return a < b ? b : a



Basically, this defines two new operators (<> and ><) that can be used between any type that adopts Comparable. They're easy for me to remember, the one that tucks in smaller wants the smaller value, and the one that opens up bigger returns the bigger value. What's nice is that you can then put them in simpler expressions:



var bottom = 13
var top = 42
var tooLow = 7
var justRight = 23
var tooHigh = 99
bottom >< tooLow <> top --> 13
bottom >< justRight <> top --> 23
bottom >< tooHigh <> top --> 42





share|improve this answer

























  • Although I agree it's not absolutely clear, his map function takes two ranges which implies he's actually wanting to interpolate. Combine that with having seen a map function somewhere somewhen that does exactly that, it seems likely that's what they're actually wanting.

    – David Berry
    Mar 15 '17 at 18:26











  • Yup, realized that was likely after writing all of the above out. :(

    – Travis Griggs
    Mar 15 '17 at 18:27


















0














Given that you are looking for mapping the relative position of a value in a given range to another range, you could do something along the lines:



// dummy function name
func transform(_ number: Int, fromRange: (Int, Int), toRange: (Int, Int)) -> Int?
guard number >= fromRange.0 && number <= fromRange.1,
toRange.0 <= toRange.1 else return nil
return toRange.0 + (number-fromRange.0)*(toRange.1-toRange.0)/(fromRange.1-fromRange.0)


// ex1
let numberA = 3001
let transformedNumberA = transform(numberA, fromRange: (0, 180_000), toRange: (0,3000))
print(transformedNumberA ?? -1) // 50

// ex2
let numberB = 134_000
let transformedNumberB = transform(numberB, fromRange: (0, 180_000), toRange: (0,3000))
print(transformedNumberB ?? -1) // 2233

// ex3
let numberC = 200_000
let transformedNumberC = transform(numberC, fromRange: (0, 180_000), toRange: (0,3000))
print(transformedNumberC ?? -1) // -1 (nil return)


Just take care to notice that (number-fromRange.0)*(toRange.1-toRange.0) (left associativity of / and * operators) may overflow.






share|improve this answer

























  • You need to subtract the minimum input range value before math, otherwise it only works if the input range starts at zero.

    – David Berry
    Mar 15 '17 at 18:15











  • @DavidBerry: you are right, thank you!

    – dfri
    Mar 15 '17 at 18:22


















0














//Map function
func mapy(n:Double, start1:Double, stop1:Double, start2:Double, stop2:Double) -> Double
return ((n-start1)/(stop1-start1))*(stop2-start2)+start2;
;





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42817020%2fhow-to-interpolate-from-number-in-one-range-to-a-corresponding-value-in-another%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    The map function on collections is going to do something very different. It applies a mapping function to each element of a collection and returns a new collection based on the results.



    What you're looking for would be:



    func map(minRange:Int, maxRange:Int, minDomain:Int, maxDomain:Int, value:Int) -> Int 
    return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)


    print(map(minRange: 0, maxRange: 1800000, minDomain: 0, maxDomain: 3000, value: 200000))


    With only a little more work you can make it generic over all integer types:



    func map<T:IntegerArithmetic>(minRange:T, maxRange:T, minDomain:T, maxDomain:T, value:T) -> T 
    return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)



    Another option would be to take advantage of the Swift Range type to make calling more succinct:



    func map<T:IntegerArithmetic>(range:Range<T>, domain:Range<T>, value:T) -> T 
    return domain.lowerBound + (domain.upperBound - domain.lowerBound) * (value - range.lowerBound) / (range.upperBound - range.lowerBound)


    map(range:0..<3000, domain:0..<180000, value: 1500)





    share|improve this answer

























    • There's a substantial difference between dfri's answer and mine in that due to the order of operations mine will have more even distribution while his is less likely to result in overflows. All depends on what you're looking for.

      – David Berry
      Mar 15 '17 at 18:16






    • 1





      Wouldn't it be better to suggest a different name of the new function, to avoid confusion with the existing map?

      – Travis Griggs
      Mar 15 '17 at 18:25











    • Probably, I was just keeping his name intact.

      – David Berry
      Mar 15 '17 at 18:28











    • Combined with explicit parameter naming, it seems clear enough.

      – David Berry
      Mar 15 '17 at 18:28















    3














    The map function on collections is going to do something very different. It applies a mapping function to each element of a collection and returns a new collection based on the results.



    What you're looking for would be:



    func map(minRange:Int, maxRange:Int, minDomain:Int, maxDomain:Int, value:Int) -> Int 
    return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)


    print(map(minRange: 0, maxRange: 1800000, minDomain: 0, maxDomain: 3000, value: 200000))


    With only a little more work you can make it generic over all integer types:



    func map<T:IntegerArithmetic>(minRange:T, maxRange:T, minDomain:T, maxDomain:T, value:T) -> T 
    return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)



    Another option would be to take advantage of the Swift Range type to make calling more succinct:



    func map<T:IntegerArithmetic>(range:Range<T>, domain:Range<T>, value:T) -> T 
    return domain.lowerBound + (domain.upperBound - domain.lowerBound) * (value - range.lowerBound) / (range.upperBound - range.lowerBound)


    map(range:0..<3000, domain:0..<180000, value: 1500)





    share|improve this answer

























    • There's a substantial difference between dfri's answer and mine in that due to the order of operations mine will have more even distribution while his is less likely to result in overflows. All depends on what you're looking for.

      – David Berry
      Mar 15 '17 at 18:16






    • 1





      Wouldn't it be better to suggest a different name of the new function, to avoid confusion with the existing map?

      – Travis Griggs
      Mar 15 '17 at 18:25











    • Probably, I was just keeping his name intact.

      – David Berry
      Mar 15 '17 at 18:28











    • Combined with explicit parameter naming, it seems clear enough.

      – David Berry
      Mar 15 '17 at 18:28













    3












    3








    3







    The map function on collections is going to do something very different. It applies a mapping function to each element of a collection and returns a new collection based on the results.



    What you're looking for would be:



    func map(minRange:Int, maxRange:Int, minDomain:Int, maxDomain:Int, value:Int) -> Int 
    return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)


    print(map(minRange: 0, maxRange: 1800000, minDomain: 0, maxDomain: 3000, value: 200000))


    With only a little more work you can make it generic over all integer types:



    func map<T:IntegerArithmetic>(minRange:T, maxRange:T, minDomain:T, maxDomain:T, value:T) -> T 
    return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)



    Another option would be to take advantage of the Swift Range type to make calling more succinct:



    func map<T:IntegerArithmetic>(range:Range<T>, domain:Range<T>, value:T) -> T 
    return domain.lowerBound + (domain.upperBound - domain.lowerBound) * (value - range.lowerBound) / (range.upperBound - range.lowerBound)


    map(range:0..<3000, domain:0..<180000, value: 1500)





    share|improve this answer















    The map function on collections is going to do something very different. It applies a mapping function to each element of a collection and returns a new collection based on the results.



    What you're looking for would be:



    func map(minRange:Int, maxRange:Int, minDomain:Int, maxDomain:Int, value:Int) -> Int 
    return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)


    print(map(minRange: 0, maxRange: 1800000, minDomain: 0, maxDomain: 3000, value: 200000))


    With only a little more work you can make it generic over all integer types:



    func map<T:IntegerArithmetic>(minRange:T, maxRange:T, minDomain:T, maxDomain:T, value:T) -> T 
    return minDomain + (maxDomain - minDomain) * (value - minRange) / (maxRange - minRange)



    Another option would be to take advantage of the Swift Range type to make calling more succinct:



    func map<T:IntegerArithmetic>(range:Range<T>, domain:Range<T>, value:T) -> T 
    return domain.lowerBound + (domain.upperBound - domain.lowerBound) * (value - range.lowerBound) / (range.upperBound - range.lowerBound)


    map(range:0..<3000, domain:0..<180000, value: 1500)






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 15 '17 at 18:36

























    answered Mar 15 '17 at 18:09









    David BerryDavid Berry

    32.7k11 gold badges71 silver badges83 bronze badges




    32.7k11 gold badges71 silver badges83 bronze badges












    • There's a substantial difference between dfri's answer and mine in that due to the order of operations mine will have more even distribution while his is less likely to result in overflows. All depends on what you're looking for.

      – David Berry
      Mar 15 '17 at 18:16






    • 1





      Wouldn't it be better to suggest a different name of the new function, to avoid confusion with the existing map?

      – Travis Griggs
      Mar 15 '17 at 18:25











    • Probably, I was just keeping his name intact.

      – David Berry
      Mar 15 '17 at 18:28











    • Combined with explicit parameter naming, it seems clear enough.

      – David Berry
      Mar 15 '17 at 18:28

















    • There's a substantial difference between dfri's answer and mine in that due to the order of operations mine will have more even distribution while his is less likely to result in overflows. All depends on what you're looking for.

      – David Berry
      Mar 15 '17 at 18:16






    • 1





      Wouldn't it be better to suggest a different name of the new function, to avoid confusion with the existing map?

      – Travis Griggs
      Mar 15 '17 at 18:25











    • Probably, I was just keeping his name intact.

      – David Berry
      Mar 15 '17 at 18:28











    • Combined with explicit parameter naming, it seems clear enough.

      – David Berry
      Mar 15 '17 at 18:28
















    There's a substantial difference between dfri's answer and mine in that due to the order of operations mine will have more even distribution while his is less likely to result in overflows. All depends on what you're looking for.

    – David Berry
    Mar 15 '17 at 18:16





    There's a substantial difference between dfri's answer and mine in that due to the order of operations mine will have more even distribution while his is less likely to result in overflows. All depends on what you're looking for.

    – David Berry
    Mar 15 '17 at 18:16




    1




    1





    Wouldn't it be better to suggest a different name of the new function, to avoid confusion with the existing map?

    – Travis Griggs
    Mar 15 '17 at 18:25





    Wouldn't it be better to suggest a different name of the new function, to avoid confusion with the existing map?

    – Travis Griggs
    Mar 15 '17 at 18:25













    Probably, I was just keeping his name intact.

    – David Berry
    Mar 15 '17 at 18:28





    Probably, I was just keeping his name intact.

    – David Berry
    Mar 15 '17 at 18:28













    Combined with explicit parameter naming, it seems clear enough.

    – David Berry
    Mar 15 '17 at 18:28





    Combined with explicit parameter naming, it seems clear enough.

    – David Berry
    Mar 15 '17 at 18:28













    0














    It's not clear whether the OP simply wants to clamp (title seems to say that) or wants to interpolate from one bounding range to another. The title makes me think one, but the dual max/min values make me think they're after an interpolation. I answered the former. David Berry has a good answer for the latter.



    What you may want is min/max functions. Swift has these. To "clamp" a value between a low and high value, you usually combine the two:



    var bottom = 13
    var top = 42
    var tooLow = 7
    var clamped = min(top, max(bottom, tooLow)) -> 13
    var justRight = 23
    clamped = min(top, max(bottom, justRight)) --> 23
    var tooHigh = 99
    clamped = min(top, max(bottom, tooHigh)) --> 42


    This is usually the route most people go, and is probably good enough for most. I personally hate writing that again and again, and I get tired of having to think about which side to feed into the max and the min. And I don't like that it uses what looks like a free function, I'm an object oriented message sending sort of guy, so I do the following:



    precedencegroup MinMaxPrecedence 
    associativity: left
    higherThan: NilCoalescingPrecedence, AdditionPrecedence, MultiplicationPrecedence


    infix operator <> : MinMaxPrecedence

    func <><T:Comparable>(a:T, b:T) -> T
    return a < b ? a : b


    infix operator >< : MinMaxPrecedence

    func ><<T:Comparable>(a:T, b:T) -> T
    return a < b ? b : a



    Basically, this defines two new operators (<> and ><) that can be used between any type that adopts Comparable. They're easy for me to remember, the one that tucks in smaller wants the smaller value, and the one that opens up bigger returns the bigger value. What's nice is that you can then put them in simpler expressions:



    var bottom = 13
    var top = 42
    var tooLow = 7
    var justRight = 23
    var tooHigh = 99
    bottom >< tooLow <> top --> 13
    bottom >< justRight <> top --> 23
    bottom >< tooHigh <> top --> 42





    share|improve this answer

























    • Although I agree it's not absolutely clear, his map function takes two ranges which implies he's actually wanting to interpolate. Combine that with having seen a map function somewhere somewhen that does exactly that, it seems likely that's what they're actually wanting.

      – David Berry
      Mar 15 '17 at 18:26











    • Yup, realized that was likely after writing all of the above out. :(

      – Travis Griggs
      Mar 15 '17 at 18:27















    0














    It's not clear whether the OP simply wants to clamp (title seems to say that) or wants to interpolate from one bounding range to another. The title makes me think one, but the dual max/min values make me think they're after an interpolation. I answered the former. David Berry has a good answer for the latter.



    What you may want is min/max functions. Swift has these. To "clamp" a value between a low and high value, you usually combine the two:



    var bottom = 13
    var top = 42
    var tooLow = 7
    var clamped = min(top, max(bottom, tooLow)) -> 13
    var justRight = 23
    clamped = min(top, max(bottom, justRight)) --> 23
    var tooHigh = 99
    clamped = min(top, max(bottom, tooHigh)) --> 42


    This is usually the route most people go, and is probably good enough for most. I personally hate writing that again and again, and I get tired of having to think about which side to feed into the max and the min. And I don't like that it uses what looks like a free function, I'm an object oriented message sending sort of guy, so I do the following:



    precedencegroup MinMaxPrecedence 
    associativity: left
    higherThan: NilCoalescingPrecedence, AdditionPrecedence, MultiplicationPrecedence


    infix operator <> : MinMaxPrecedence

    func <><T:Comparable>(a:T, b:T) -> T
    return a < b ? a : b


    infix operator >< : MinMaxPrecedence

    func ><<T:Comparable>(a:T, b:T) -> T
    return a < b ? b : a



    Basically, this defines two new operators (<> and ><) that can be used between any type that adopts Comparable. They're easy for me to remember, the one that tucks in smaller wants the smaller value, and the one that opens up bigger returns the bigger value. What's nice is that you can then put them in simpler expressions:



    var bottom = 13
    var top = 42
    var tooLow = 7
    var justRight = 23
    var tooHigh = 99
    bottom >< tooLow <> top --> 13
    bottom >< justRight <> top --> 23
    bottom >< tooHigh <> top --> 42





    share|improve this answer

























    • Although I agree it's not absolutely clear, his map function takes two ranges which implies he's actually wanting to interpolate. Combine that with having seen a map function somewhere somewhen that does exactly that, it seems likely that's what they're actually wanting.

      – David Berry
      Mar 15 '17 at 18:26











    • Yup, realized that was likely after writing all of the above out. :(

      – Travis Griggs
      Mar 15 '17 at 18:27













    0












    0








    0







    It's not clear whether the OP simply wants to clamp (title seems to say that) or wants to interpolate from one bounding range to another. The title makes me think one, but the dual max/min values make me think they're after an interpolation. I answered the former. David Berry has a good answer for the latter.



    What you may want is min/max functions. Swift has these. To "clamp" a value between a low and high value, you usually combine the two:



    var bottom = 13
    var top = 42
    var tooLow = 7
    var clamped = min(top, max(bottom, tooLow)) -> 13
    var justRight = 23
    clamped = min(top, max(bottom, justRight)) --> 23
    var tooHigh = 99
    clamped = min(top, max(bottom, tooHigh)) --> 42


    This is usually the route most people go, and is probably good enough for most. I personally hate writing that again and again, and I get tired of having to think about which side to feed into the max and the min. And I don't like that it uses what looks like a free function, I'm an object oriented message sending sort of guy, so I do the following:



    precedencegroup MinMaxPrecedence 
    associativity: left
    higherThan: NilCoalescingPrecedence, AdditionPrecedence, MultiplicationPrecedence


    infix operator <> : MinMaxPrecedence

    func <><T:Comparable>(a:T, b:T) -> T
    return a < b ? a : b


    infix operator >< : MinMaxPrecedence

    func ><<T:Comparable>(a:T, b:T) -> T
    return a < b ? b : a



    Basically, this defines two new operators (<> and ><) that can be used between any type that adopts Comparable. They're easy for me to remember, the one that tucks in smaller wants the smaller value, and the one that opens up bigger returns the bigger value. What's nice is that you can then put them in simpler expressions:



    var bottom = 13
    var top = 42
    var tooLow = 7
    var justRight = 23
    var tooHigh = 99
    bottom >< tooLow <> top --> 13
    bottom >< justRight <> top --> 23
    bottom >< tooHigh <> top --> 42





    share|improve this answer















    It's not clear whether the OP simply wants to clamp (title seems to say that) or wants to interpolate from one bounding range to another. The title makes me think one, but the dual max/min values make me think they're after an interpolation. I answered the former. David Berry has a good answer for the latter.



    What you may want is min/max functions. Swift has these. To "clamp" a value between a low and high value, you usually combine the two:



    var bottom = 13
    var top = 42
    var tooLow = 7
    var clamped = min(top, max(bottom, tooLow)) -> 13
    var justRight = 23
    clamped = min(top, max(bottom, justRight)) --> 23
    var tooHigh = 99
    clamped = min(top, max(bottom, tooHigh)) --> 42


    This is usually the route most people go, and is probably good enough for most. I personally hate writing that again and again, and I get tired of having to think about which side to feed into the max and the min. And I don't like that it uses what looks like a free function, I'm an object oriented message sending sort of guy, so I do the following:



    precedencegroup MinMaxPrecedence 
    associativity: left
    higherThan: NilCoalescingPrecedence, AdditionPrecedence, MultiplicationPrecedence


    infix operator <> : MinMaxPrecedence

    func <><T:Comparable>(a:T, b:T) -> T
    return a < b ? a : b


    infix operator >< : MinMaxPrecedence

    func ><<T:Comparable>(a:T, b:T) -> T
    return a < b ? b : a



    Basically, this defines two new operators (<> and ><) that can be used between any type that adopts Comparable. They're easy for me to remember, the one that tucks in smaller wants the smaller value, and the one that opens up bigger returns the bigger value. What's nice is that you can then put them in simpler expressions:



    var bottom = 13
    var top = 42
    var tooLow = 7
    var justRight = 23
    var tooHigh = 99
    bottom >< tooLow <> top --> 13
    bottom >< justRight <> top --> 23
    bottom >< tooHigh <> top --> 42






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 15 '17 at 18:26

























    answered Mar 15 '17 at 18:20









    Travis GriggsTravis Griggs

    10.8k16 gold badges63 silver badges113 bronze badges




    10.8k16 gold badges63 silver badges113 bronze badges












    • Although I agree it's not absolutely clear, his map function takes two ranges which implies he's actually wanting to interpolate. Combine that with having seen a map function somewhere somewhen that does exactly that, it seems likely that's what they're actually wanting.

      – David Berry
      Mar 15 '17 at 18:26











    • Yup, realized that was likely after writing all of the above out. :(

      – Travis Griggs
      Mar 15 '17 at 18:27

















    • Although I agree it's not absolutely clear, his map function takes two ranges which implies he's actually wanting to interpolate. Combine that with having seen a map function somewhere somewhen that does exactly that, it seems likely that's what they're actually wanting.

      – David Berry
      Mar 15 '17 at 18:26











    • Yup, realized that was likely after writing all of the above out. :(

      – Travis Griggs
      Mar 15 '17 at 18:27
















    Although I agree it's not absolutely clear, his map function takes two ranges which implies he's actually wanting to interpolate. Combine that with having seen a map function somewhere somewhen that does exactly that, it seems likely that's what they're actually wanting.

    – David Berry
    Mar 15 '17 at 18:26





    Although I agree it's not absolutely clear, his map function takes two ranges which implies he's actually wanting to interpolate. Combine that with having seen a map function somewhere somewhen that does exactly that, it seems likely that's what they're actually wanting.

    – David Berry
    Mar 15 '17 at 18:26













    Yup, realized that was likely after writing all of the above out. :(

    – Travis Griggs
    Mar 15 '17 at 18:27





    Yup, realized that was likely after writing all of the above out. :(

    – Travis Griggs
    Mar 15 '17 at 18:27











    0














    Given that you are looking for mapping the relative position of a value in a given range to another range, you could do something along the lines:



    // dummy function name
    func transform(_ number: Int, fromRange: (Int, Int), toRange: (Int, Int)) -> Int?
    guard number >= fromRange.0 && number <= fromRange.1,
    toRange.0 <= toRange.1 else return nil
    return toRange.0 + (number-fromRange.0)*(toRange.1-toRange.0)/(fromRange.1-fromRange.0)


    // ex1
    let numberA = 3001
    let transformedNumberA = transform(numberA, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberA ?? -1) // 50

    // ex2
    let numberB = 134_000
    let transformedNumberB = transform(numberB, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberB ?? -1) // 2233

    // ex3
    let numberC = 200_000
    let transformedNumberC = transform(numberC, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberC ?? -1) // -1 (nil return)


    Just take care to notice that (number-fromRange.0)*(toRange.1-toRange.0) (left associativity of / and * operators) may overflow.






    share|improve this answer

























    • You need to subtract the minimum input range value before math, otherwise it only works if the input range starts at zero.

      – David Berry
      Mar 15 '17 at 18:15











    • @DavidBerry: you are right, thank you!

      – dfri
      Mar 15 '17 at 18:22















    0














    Given that you are looking for mapping the relative position of a value in a given range to another range, you could do something along the lines:



    // dummy function name
    func transform(_ number: Int, fromRange: (Int, Int), toRange: (Int, Int)) -> Int?
    guard number >= fromRange.0 && number <= fromRange.1,
    toRange.0 <= toRange.1 else return nil
    return toRange.0 + (number-fromRange.0)*(toRange.1-toRange.0)/(fromRange.1-fromRange.0)


    // ex1
    let numberA = 3001
    let transformedNumberA = transform(numberA, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberA ?? -1) // 50

    // ex2
    let numberB = 134_000
    let transformedNumberB = transform(numberB, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberB ?? -1) // 2233

    // ex3
    let numberC = 200_000
    let transformedNumberC = transform(numberC, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberC ?? -1) // -1 (nil return)


    Just take care to notice that (number-fromRange.0)*(toRange.1-toRange.0) (left associativity of / and * operators) may overflow.






    share|improve this answer

























    • You need to subtract the minimum input range value before math, otherwise it only works if the input range starts at zero.

      – David Berry
      Mar 15 '17 at 18:15











    • @DavidBerry: you are right, thank you!

      – dfri
      Mar 15 '17 at 18:22













    0












    0








    0







    Given that you are looking for mapping the relative position of a value in a given range to another range, you could do something along the lines:



    // dummy function name
    func transform(_ number: Int, fromRange: (Int, Int), toRange: (Int, Int)) -> Int?
    guard number >= fromRange.0 && number <= fromRange.1,
    toRange.0 <= toRange.1 else return nil
    return toRange.0 + (number-fromRange.0)*(toRange.1-toRange.0)/(fromRange.1-fromRange.0)


    // ex1
    let numberA = 3001
    let transformedNumberA = transform(numberA, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberA ?? -1) // 50

    // ex2
    let numberB = 134_000
    let transformedNumberB = transform(numberB, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberB ?? -1) // 2233

    // ex3
    let numberC = 200_000
    let transformedNumberC = transform(numberC, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberC ?? -1) // -1 (nil return)


    Just take care to notice that (number-fromRange.0)*(toRange.1-toRange.0) (left associativity of / and * operators) may overflow.






    share|improve this answer















    Given that you are looking for mapping the relative position of a value in a given range to another range, you could do something along the lines:



    // dummy function name
    func transform(_ number: Int, fromRange: (Int, Int), toRange: (Int, Int)) -> Int?
    guard number >= fromRange.0 && number <= fromRange.1,
    toRange.0 <= toRange.1 else return nil
    return toRange.0 + (number-fromRange.0)*(toRange.1-toRange.0)/(fromRange.1-fromRange.0)


    // ex1
    let numberA = 3001
    let transformedNumberA = transform(numberA, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberA ?? -1) // 50

    // ex2
    let numberB = 134_000
    let transformedNumberB = transform(numberB, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberB ?? -1) // 2233

    // ex3
    let numberC = 200_000
    let transformedNumberC = transform(numberC, fromRange: (0, 180_000), toRange: (0,3000))
    print(transformedNumberC ?? -1) // -1 (nil return)


    Just take care to notice that (number-fromRange.0)*(toRange.1-toRange.0) (left associativity of / and * operators) may overflow.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 15 '17 at 18:58

























    answered Mar 15 '17 at 17:54









    dfridfri

    37.4k4 gold badges66 silver badges106 bronze badges




    37.4k4 gold badges66 silver badges106 bronze badges












    • You need to subtract the minimum input range value before math, otherwise it only works if the input range starts at zero.

      – David Berry
      Mar 15 '17 at 18:15











    • @DavidBerry: you are right, thank you!

      – dfri
      Mar 15 '17 at 18:22

















    • You need to subtract the minimum input range value before math, otherwise it only works if the input range starts at zero.

      – David Berry
      Mar 15 '17 at 18:15











    • @DavidBerry: you are right, thank you!

      – dfri
      Mar 15 '17 at 18:22
















    You need to subtract the minimum input range value before math, otherwise it only works if the input range starts at zero.

    – David Berry
    Mar 15 '17 at 18:15





    You need to subtract the minimum input range value before math, otherwise it only works if the input range starts at zero.

    – David Berry
    Mar 15 '17 at 18:15













    @DavidBerry: you are right, thank you!

    – dfri
    Mar 15 '17 at 18:22





    @DavidBerry: you are right, thank you!

    – dfri
    Mar 15 '17 at 18:22











    0














    //Map function
    func mapy(n:Double, start1:Double, stop1:Double, start2:Double, stop2:Double) -> Double
    return ((n-start1)/(stop1-start1))*(stop2-start2)+start2;
    ;





    share|improve this answer



























      0














      //Map function
      func mapy(n:Double, start1:Double, stop1:Double, start2:Double, stop2:Double) -> Double
      return ((n-start1)/(stop1-start1))*(stop2-start2)+start2;
      ;





      share|improve this answer

























        0












        0








        0







        //Map function
        func mapy(n:Double, start1:Double, stop1:Double, start2:Double, stop2:Double) -> Double
        return ((n-start1)/(stop1-start1))*(stop2-start2)+start2;
        ;





        share|improve this answer













        //Map function
        func mapy(n:Double, start1:Double, stop1:Double, start2:Double, stop2:Double) -> Double
        return ((n-start1)/(stop1-start1))*(stop2-start2)+start2;
        ;






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 1:02









        omarojoomarojo

        5616 silver badges22 bronze badges




        5616 silver badges22 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42817020%2fhow-to-interpolate-from-number-in-one-range-to-a-corresponding-value-in-another%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해