Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a preexisting function that will return a set of numbers based on a base number and an "offset"?

Tags:

c#

algorithm

int

I don't want to reinvent the wheel: If I want to get every integer within a range of N from a given number, what is the most efficient way to do it?

What I mean is something like this:

public List<int> getIntsWithinN(int BaseInt, int Offset)

...so that if the args passed in were 7 and 3, the result would be 4..10; if the args passed in were 42 and 7, the result would 35..49, etc.

UPDATE

Okay, I've finally gotten around to trying to implement this. But I don't know if I should pass my List to the ToList() like so:

List<int> listInts = new List<int>();
. . .
Enumerable.Range(lineNum - Offset, Offset * 2 + 1).ToList(listInts);

...or do it like so:

listInts = Enumerable.Range(lineNum - Offset, Offset * 2 + 1).ToList();

...but what I need to do is call this several times, so the Intellisense description doesn't seem like what I really need. It says, "Creates a ... List..."

But I don't want a new one to be created each time, I want to append to an existing list, and preferably simultaneously disregarding duplicates.

like image 408
B. Clay Shannon-B. Crow Raven Avatar asked Jun 01 '12 01:06

B. Clay Shannon-B. Crow Raven


2 Answers

I don't think there's going to be a function for exactly this, but I think this is the shortest and simplest:

Enumerable.Range(BaseInt - Offset, Offset * 2 + 1).ToList()
like image 87
TheEvilPenguin Avatar answered Nov 14 '22 23:11

TheEvilPenguin


preferably simultaneously disregarding duplicates

In that you should consider HashSet<int>.

var hashSet = new HashSet<int>();
hashSet.UnionWith(Enumerable.Range(lineNum - offset, offset * 2 + 1));

If you want a list, you can call ToList() on hashSet in the end. You might also want to sort it when converting to list, since HashSet<T> keeps the items in an undefined order.

var list = hashSet.OrderBy(i=>i).ToList();
like image 37
CodesInChaos Avatar answered Nov 14 '22 21:11

CodesInChaos