asmgx
asmgx

Reputation: 7994

find range in a range list C#

I have this price range, formed in a string like this:

100:105 , 110:120 , 150:200 , 240:245

This means the prices range from

100 to 105

and

110 to 120

and

150 to 200

and

240 to 245

I want to check if a new price range is within our acceptable price range. Here is my code so far:

int ibegin = 110
int iend = 115

string BeginEnd = "100:105,110:120,150:200,240:245";
string[] strBeginEnd = BeginEnd.Split(',');

int pos = Array.IndexOf(strBeginEnd, ibegin+":"+ iend);
if (pos > -1)
      {
          RepText = RepText + ScriptBefore + TextIn + ScriptAfter + TextAfter;
      } 

This code works if the price start and end matches the start and end of the range.

For example, if ibegin = 110 and iend = 120 then my code will find it based on if 110:120 exists in the list.

However, if the iend = 115 it won't find it.

Upvotes: 0

Views: 253

Answers (3)

Falah H. Abbas
Falah H. Abbas

Reputation: 512

 public static void Main(string[] args) {
            string BeginEnd = "100:105,110:120,150:200,240:245";
            Dictionary<string, int[]> data = new Dictionary<string, int[]>();
            foreach (var val in BeginEnd.Split(",")) {
                var start = int.Parse(val.Split(":")[0]);
                var end = int.Parse(val.Split(":")[1]);
                var range = new int[end - start+1];
                for (var i = 0; i < range.Length; i++) {
                    range[i] = start + i;
                }
                data.Add(val, range);
            }

            var test1 = check(110);
            var test2 = check(115);
            var test3 = check(200);
            var test4 = check(240);

            Console.WriteLine("test1 {0} ,test2 {1} ,test3 {2} ,test4 {3}  ",test1,test2,test3,test4);
            string check(int value) => data.FirstOrDefault(pair => pair.Value.Contains(value)).Key;
        }

Upvotes: 1

Andrew Arthur
Andrew Arthur

Reputation: 1603

bool IsInRange(int ibegin, int iend, string BeginEnd)
{
    string[] strBeginEnd = BeginEnd.Split(',');

    foreach (var range in strBeginEnd)
    {
        var rangeArray = range.Split(':');
        if (ibegin >= int.Parse(rangeArray[0]) && iend <= int.Parse(rangeArray[1]))
        {
            return true;
        }
    }
    return false;
}

Upvotes: 1

Andrei Tătar
Andrei Tătar

Reputation: 8295

You need to split the ranges, parse the numbers and check them:

var search = new {from = 110, to= 115};
var found = "100:105,110:120,150:200,240:245"
    .Split(',') //split in parts like 100:105
    .Select(p => {
        var parts = p.Split(':'); // split the range from/to
        var from = int.Parse(parts[0]); //convert from/to to ints
        var to = int.Parse(parts[1]);
        return new { from, to };
    })
    //check if any range matches the search values
    .Any(range => search.from >= range.from && search.to <= range.to);

Console.WriteLine($"Found: {found}");

Upvotes: 1

Related Questions