How to resolve the algorithm Map range step by step in the Icon and Unicon programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Map range step by step in the Icon and Unicon programming language

Table of Contents

Problem Statement

Given two ranges:   where:

Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range   [0, 10]   to the range   [-1, 0].

Show additional idiomatic ways of performing the mapping, using tools available to the language.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Map range step by step in the Icon and Unicon programming language

Source code in the icon programming language

record Range(a, b)

# note, we force 'n' to be real, which means recalculation will 
# be using real numbers, not integers
procedure remap (range1, range2, n : real)
  if n < range2.a | n > range2.b then fail # n out of given range
  return range1.a + (n - range2.a) * (range1.b - range1.a) / (range2.b - range2.a)
end
  
procedure range_string (range)
  return "[" || range.a || ", " || range.b || "]"
end

procedure main ()
  range1 := Range (0, 10)
  range2 := Range (-1, 0)
  # if i is out of range1, then 'remap' fails, so only valid changes are written
  every i := -2 to 12 do {
    if m := remap (range2, range1, i)
      then write ("Value " || i || " in " || range_string (range1) || 
                  " maps to " || m || " in " || range_string (range2))
  }
end


procedure remap (range1, range2, n)
  n *:= 1.0
  if n < range2.a | n > range2.b then fail # n out of given range
  return range1.a + (n - range2.a) * (range1.b - range1.a) / (range2.b - range2.a)
end


  

You may also check:How to resolve the algorithm Sleep step by step in the Zoomscript programming language
You may also check:How to resolve the algorithm Arbitrary-precision integers (included) step by step in the Scheme programming language
You may also check:How to resolve the algorithm Hamming numbers step by step in the REXX programming language
You may also check:How to resolve the algorithm Scope modifiers step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Smith numbers step by step in the MAD programming language