Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metric Convertions Algorithm without "if-else" or "switch-case"

Tags:

java

algorithm

I want to write a program which can converts one unit to another unit. Let's say I have 2 methods.First method can do metric conversions, second method can do weight conversitons. For example;

1. long km=metricConvLength(long mil,Enum.mil,Enum.km);//first method

2. long agirlik=metricConvWeight(long kg,Enum.mil,Enum.km);//second method

I want to use Enum struct for these variables. My program can convert these things and opposites;

  • sea mile-km
  • sea mile-mile
  • feet- km
  • feet- mil
  • pound- kg
  • ons- gr
  • inc - cm
  • yard - m
  • knot- km

My Question: I don't want to use if-else or switch-case structs for conversions.(Because if I use if-else struct,my code looks like so bad, much easy and slow.And I need more then 50 if-else struct when if I use these struct.This is grind.)

Can I write an algorithm for these conversions without using if-else or switch-case. My purpose is less code, more work. Any tips about algorithm?

like image 929
TeachMeJava Avatar asked Jul 09 '13 12:07

TeachMeJava


People also ask

What is the easiest way to convert metrics?

To convert from one unit to another within the metric system usually means moving a decimal point. If you can remember what the prefixes mean, you can convert within the metric system relatively easily by simply multiplying or dividing the number by the value of the prefix.

What strategies do you use when converting metric units?

Metric units of measurement differ by powers of 10 - 10, 100, 1,000, and so on. Thus, converting from one metric unit to another is always accomplished by multiplying or dividing your initial measurement by the appropriate power of ten.


1 Answers

You do not need an if-then-else - in fact, you do not need control statements in your program. All you need is a lookup table - a Map that translates your unit enum to a double conversion factor, such that multiplying the measure in units by the conversion factor you get meters for units of space, and kilos for units of weight. Conversely, dividing meters by that factor gives you the desired units.

With this map in hand, you can do conversions for all pairs of units:

  • Look up the conversion factor Cs for the source units
  • Look up the conversion factor Cd for the destination units
  • Return value * Cs / Cd as your result.

For example, let's say that you want to deal with meters, yards, inches, and feet. Your map would look like this:

  • m - 1.0
  • y - 0.9144
  • in - 0.0254
  • ft - 0.3048

Now let's say you want to convert 7.5 yards to feet:

  • Look up Cs = 0.9144
  • Look up Cd = 0.3048
  • Compute and return Res = 7.5 * 0.9144 / 0.3048 = 22.5
like image 82
Sergey Kalinichenko Avatar answered Nov 15 '22 07:11

Sergey Kalinichenko