I am developing weight matrix for a directed weighted graph. and I have to insert infinity as well according to the rules of weight matrix.
So far i am sticking with with int.MaxValue
builtin function of C#...
After this I am using this weight matrix for FloydWarshall algorithm, but due to int.MaxValue I get very big numbers in output. I am looking for an alternative that can be understood as infinity but it does not give big value... WHAT CAN BE THE ALTERNATIVE...? remember using int.
You could use Nullable<int>
(int?
for short) and just use null
to mean "infinity". Technically, this would likely be fine, but it's not an ideal semantic representation of what you're trying to do. Also note that if you use mathematical operations (addition, multiplication, etc) the semantics for null
values probably won't always match up with what you want when representing infinity, so be careful about when you use such operators, and what you actually want them to do when values are null/infinite.
You could use double
, which supports non-numeric values such as Infinity
. Of course, you'd then be storing floating point values, not integers. This may or may not be a drawback that you can live with in your application, depending on the number of significant figures you need, and how sensitive you are to memory/performance concerns.
Create your own type that wraps an integer (or a nullable integer), but also has a representation for infinity. This would basically look just like Nullable
, and would probably have a very similar public API, but would simply be using a boolean to track whether or not the value is infinite, rather than whether or not it has a value. It'd basically just be a way of renaming portions of the public API of int?
to be in line with your intended usage. It could look something similar to this:
public struct InfiniteInteger
{
private int? value;
public InfiniteInteger()
{
this.value = null;
}
public InfiniteInteger(int value)
{
this.value = value;
}
public int Value { get { return value.Value; } }
public bool IsInfinite { get { return value.HasValue; } }
//todo explicit/implicit conversion operators as you see fit
//todo override math operators (+, -, *, %, etc.) as you see fit
//todo override equality/comparison operators;
// these can just be passed down directly to the wrapped value's implementation
}
Note that you may want to handle infinite values differently when performing different operators than nullable values are handled, or you may not, it depends on what you're doing, so just take some time to think about what should happen.