开发者

C# Find the Next X and Previous Numbers in a sequence

I have a list of numbers, {1,2,3,4,...,End} where End is specified. I want to display the X closest numbers around a given number Find within the list. If x is odd I want the extra digit to go on the greater than side.

Example (Base Case)

End: 6
X: 2
Find: 3

The result should be: {2,3,4}

Another Example (Bound Case):

End: 6
X: 4
Find: 5

The result should be: {2,3,4,5,6}

Yet Another Example (Odd Case):

End: 6
X: 3
Find: 3

The result should be: {2,3,4,5}

I'm assuming it would be easier to simply find a start and stop value, rather than actually generating the list, but I don't really care one way or another.

I'm using C# 4.0 if that matters.

Edit: I can think of a way to do it, but it involves way too many if, else if 开发者_如何学Pythoncases.

if (Find == 1)
{
     Start = Find;
     Stop = (Find + X < End ? Find + X : End);
}
else if (Find == 2)
{
     if (X == 1)
     {
          Start = Find;
          End = (Find + 1 < End ? Find + 1 : End);
     }
     ...
 }

You can hopefully see where this is going. I assuming I'm going to have to use a (X % 2 == 0) for odd/even checking. Then some bound thats like less = Find - X/2 and more = Find + X/2. I just can't figure out the path of least if cases.

Edit II: I should also clarify that I don't actually create a list of {1,2,3,4...End}, but maybe I need to just start at Find-X/2.


I realise that you are learning, and out of respect from this I will not provide you with the full solution. I will however do my best to nudge you in the right direction.

From looking at your attempted solution, I think you need to figure out the algorithm you need before trying to code up something that may or may not solve your problem. As you say yourself, writing one if statement for every possible permutation on the input is not a manageble solution. You need to find an algorithm that is general enough that you can use it for any input you get, and still get the right results out.

Basically, there are two questions you need to answer before you'll be able to code up a working solution.

  1. How do I find the lower bound of the list I want to return?
  2. How do I find the upper bound of the list I want to return?

Considering the example base case, you know that the given parameter X contains a number that tells you how many numbers around Find you should display. Therefore you need to divide X equally on both sides of Find.

Thus:

  1. If I get an input X = 4 and Find = 3, the lower bound will be 3 - 4/2 or Find - X/2.
  2. The higher bound will be 3 + 4/2 or Find + X/2.

Start by writing a program that runs and works for the base case. Once that is done, sit down and figure out how you would find the higher and lower bounds for a more complicated case.

Good luck!


You can look at Extension methods. skip and take.

x.Skip(3).Take(4);

this will help u in what u r trying to do

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜