Efficient method to find a value in a table "C #
I need to find a value in a "table" where the table can be an array or whatever. On paper, it looks like this (abbreviated and summarized):
Size 500 750 1000 1250 1500 (speed)
--------------------------------------------
6x5 0.1 0.5 0.55 0.58 0.8
6x4 0.01 0.1 0.4 0.5 0.9
8x5 0.5 0.9 1.1 1.5 2.0
10x5 1.2 1.5 2.0 2.7 3.0
12x6 2.6 3.0 4.4 5.1 7.0 (pressure)
I need to extract pressure somehow when I have variable size and speed.
I have put each line in a separate array right now, but I would like to avoid a bunch of if else, but I really don't know a better way. Thanks for the help.
a source to share
Assuming your size and speed are always specific values and do not fall between the values given in your example (for example, no size 780
or 598
), the fastest way to perform a speed and size search is to have Dictionary<SizeAndSpeed, double>
, where SizeAndSpeed
is a class like this:
public class SizeAndSpeed : IEquatable<SizeAndSpeed>
{
public string Size { get; set; }
public int Speed { get; set; }
public bool Equals(SizeAndSpeed other)
{
return Size == other.Size && Speed == other.Speed;
}
}
I suppose it Size
can be string
, but of course a more complex object can be used.
a source to share
Create a structure to keep the size and speed of the pair:
public struct SizeSpeedKey
{
public string Size;
public int Speed;
public SizeSpeedKey(string size, int speed)
{
Size = size;
Speed = speed;
}
}
Then this would be the search code:
using System;
using System.Collections.Generic;
namespace LookupTable
{
internal class Program
{
private static readonly Dictionary<SizeSpeedKey, double> lookupTable =
new Dictionary<SizeSpeedKey, double>
{
{new SizeSpeedKey("6x5", 500), 0.1},
{new SizeSpeedKey("6x5", 750), 0.5},
{new SizeSpeedKey("6x4", 500), 0.01},
{new SizeSpeedKey("6x4", 750), 0.1},
{new SizeSpeedKey("8x5", 500), 0.5},
{new SizeSpeedKey("8x5", 750), 0.9},
};
private static void Main(string[] args)
{
// these will of course need to be read from the user
var size = "6x4";
var speed = 500;
Console.WriteLine("For size = {0} and speed = {1}, the pressure will be {2}", size, speed, lookupTable[new SizeSpeedKey(size, speed)]);
Console.ReadLine();
}
}
}
a source to share