找出0到20(包括20)之间的数字,分别在以下范围内:
2-5 -> "a"
6-7 -> "b"
9-11 -> "c"
12-12 -> "d"
15-18 -> "e"
19-19 -> "f"
在一个循环中执行1000000次,包括1次RangeCollection的创建和初始化:仅需3秒钟!
你需要做的就是准备一个Tuple的IEnumerable,其中第一个int是最小IP int值,第二个是最大值,TValue是与该min~max范围相关联的数据。
这是我的实现:
public class RangeCollection<TValue>
{
private readonly int[] _mins;
private readonly int[] _maxs;
private readonly TValue[] _values;
public RangeCollection(params Tuple<int, int, TValue>[] input)
: this((IEnumerable<Tuple<int, int, TValue>>)input)
{
}
public RangeCollection(IEnumerable<Tuple<int, int, TValue>> input)
{
var tuples = input.OrderBy(tuple => tuple.Item1).ToArray();
for (var i = 1; i < tuples.Length; i++)
{
if (tuples[i].Item1 <= tuples[i - 1].Item2)
{
throw new ArgumentException("Ranges should not overlap.");
}
}
this._mins = new int[tuples.Length];
this._maxs = new int[tuples.Length];
this._values = new TValue[tuples.Length];
for (var i = 0; i < tuples.Length; i++)
{
var tuple = tuples[i];
this._mins[i] = tuple.Item1;
this._maxs[i] = tuple.Item2;
this._values[i] = tuple.Item3;
}
}
public bool TryGetValue(int key, out TValue value)
{
if (this.Contains(key, out key))
{
value = this._values[key];
return true;
}
value = default(TValue);
return false;
}
public bool Contains(int key)
{
return this.Contains(key, out key);
}
private bool Contains(int key, out int index)
{
index = 0;
if (this._mins.Length == 0 || key < this._mins[0] || key > this._maxs[this._maxs.Length - 1])
{
return false;
}
var low = 0;
var high = this._mins.Length - 1;
while (high >= low)
{
index = (low + high) / 2;
var cmp = this._mins[index].CompareTo(key);
if (cmp == 0)
{
return true;
}
if (cmp == 1)
{
high = index - 1;
}
else
{
low = index + 1;
}
}
if (this._mins[index] > key)
{
index--;
}
else if (this._mins[index + 1] <= key)
{
index++;
}
return this._maxs[index] >= key;
}
}
使用方法:
var collection = new RangeCollection<string>(new Tuple<int, int, string>(2, 5, "a"),
new Tuple<int, int, string>(6, 7, "b"),
new Tuple<int, int, string>(9, 11, "c"),
new Tuple<int, int, string>(12, 12, "d"),
new Tuple<int, int, string>(15, 18, "e"),
new Tuple<int, int, string>(19, 19, "f"));
for (var i = 0; i <= 20; i++)
. Value: ", i, val);
}
else
}
/* Output:
Doesn't contain 0
Doesn't contain 1
Contains 2. Value: a
Contains 3. Value: a
Contains 4. Value: a
Contains 5. Value: a
Contains 6. Value: b
Contains 7. Value: b
Doesn't contain 8
Contains 9. Value: c
Contains 10. Value: c
Contains 11. Value: c
Contains 12. Value: d
Doesn't contain 13
Doesn't contain 14
Contains 15. Value: e
Contains 16. Value: e
Contains 17. Value: e
Contains 18. Value: e
Contains 19. Value: f
Doesn't contain 20
*/