简体   繁体   中英

Get Numbers between range having 'x' digit(s) at 'n' position

How can we get all the number between the range of numbers which all have the 'x' digit at their 'nth' digit position.

Example: I need to find all the tickets having number between range 1000 to 100000 which have digit 5 at 3rd digit position and 8 at 5th digit position.

I believe there should be a better option than looping over all the tickets to match the correct tickets or is it the only way which I have been doing?

Also a loop but hidden:

var allNumbers = Enumerable.Range(1000, 100000 - 1000 + 1) // +1 to include 100000
    .Select(i => new { Number = i, String = i.ToString() })
    .Where(x => x.String.Length >= 5 && x.String[2] == '5' && x.String[4] == '8')
    .Select(x => x.Number)
    .ToList();

So you want to find out all the tickets that are in form

0a5bc8

where a , b , c are digits [0..9] . You can easily generate all the items with

  List<int> tickets = new List<int>(1000); // we know that there're 1000 such values

  for (int a = 0; a < 10; ++a) 
    for (int b = 0; b < 10; ++b) 
      for (int c = 0; c < 10; ++c) 
        tickets.Add(a * 10000 + b * 100 + c * 10 + 5008);

No loops and filtering out - only generations (if you're looking for an efficient implementation )

As a string is nothing but a list of characters you may query those elements that have the desired characters at the given indices:

var range = Enumerable.Range(lowerBound, upperBound - lowerBound + 1)
    .Select(x => x.ToString().PadLeft(6, '0'))

var result = range.Where(x => x[2] == '5' && x[4] ='8');

EDIT: Be aware that this appraoch changes the semantics of what the third or fifth digit within your number is, as PadLeft will add zero-characters in front.

You could inject those known numbers in the correct positions:

change "nnnnn" into "nn5n8nn"

You will then need to loop through 1/100th of the numbers. Convert to string, split in three parts (substring) and combine again with these numbers added.

Enumerable.Range(100,900)
  .Select(i => i.ToString())
  .Select(s => new { 
         p1 = s.Substring(0, 2), 
         p2 = s.Substring(2, 1), 
         p3 = s.Substring(3)})
  .Select(p => Int32.Parse(p.p1 + "5" + p.p2 + "8" + p.p3))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM