How do I swap 2 elements in a list [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Swap two items in List<T>
Edit: Maybe this will work for getting the 'b' value?
for (int i = 0; i < inventory.Count; i++)
{
if (inventory[a].ItemRectangle.Intersects(inventory[i].ItemRectangle))
{
itemB = inventory[i];
}
}
Edit: Here's my progress.
Item itemA;
Item itemB;
int a = -1;
int b = -1;
if (a != -1 && b != -1)
{
itemA = inventory[a];
itemB = inventory[b];
Swap(ref itemA, ref itemB);
inventory[a] = itemA;
inventory[b] = itemB;
}
And here's is where I'm getting the 'a' value.
if (item.ItemSelected == true)
{
a = item.ItemIndex;
}
else
a = -1;
I haven't figured out how to get the 'b' value because I would have to check for an item colliding with another item that are both in the same list. If anybody know how I can do this, please tell me. It would look something like this I guess:
if (item.ItemRectangle.Intersects(//the other item.ItemRectangle)
{
b = item.ItemIndex;
}
else
b = -1;
I've made a List < Item > called inventory. So now I want to implement a swap function, like this:
foreach (Item item in inventory)
{
if (mouseRectangle.Intersects(item.ItemRectangle))
{
if (Input.EdgeDetectLeftMouseDown())
{
switch (item.ItemSelected)
{
case false:
item.ItemSelected = true;
break;
case true:
item.ItemSelected = false;
break;
}
}
}
else if (Input.EdgeDetectLeftMouseDown())
{
switch (item.ItemSelected)
{
case true:
item.ItemSelected = false;
break;
}
}
else if (item.ItemSelected == true)
{
item.ItemPosition = new Vector2(mouseRectangle.X, mouseRectangle.Y);
item.ItemRectangle = new Rectangle(mouseRectangle.X, mouseRectangle.Y, 32, 32);
}
else if (item.ItemSelected == false && //a lot of checks to determine it is not intersecting with an equip slot
{
item.ItemPosition = item.OriginItemPosition;
item.ItemRectangle = item.OriginItemRectangle;
}
else if (item.ItemRectangle.Intersects(item.ItemRectangle))
{
//SwapItem(inventory, item, item);
}
So that's the part of the code I need help with. I want any item in the list to be able to swap with any other item in the list. My SwapItem method is just a placeholder, I dont actually have a SwapItem method yet.
I want the arguments that you pass in to the method to be related to the items I want to swap. So the first item would be the item that I have selected with my mouse, and the other item should be the item that the first item is intersecting with.

To swap an element of the list you can write an extension method as.
public static class ExtensionMethods
{
public static void Swap<T>(this List<T> list, int index1, int index2)
{
T temp = list[index1];
list[index1] = list[index2];
list[index2] = temp;
}
}
Remember to put the extension method inside a static class.
then you can do:
yourList.Swap(0,1); // swap element at index 0 with element at index 1

To swap the values of two variables, the easiest method is using references. This is a classic pointer exercise in c++, but it can apply to C# as well.
// Replace int with any data type / class you need
void Swap (ref int a, ref int b)
{
int c = a;
a = b;
b = c;
}
The algorithm used is very simple, and the explanation is usually done like this: you have two glasses, one with water, and one with oil. To put the oil in the first glass, you will need to use a third glass, put the water inside, then put the oil in the first glass, and the water in the second one.
Here is what I had in mind. Look for the comments, so you can understand what's going on.:
// Unlike foreach, with for I can change the values in the list
for (int i = 0; i < inventory.Count; i++)
{
if (mouseRectangle.Intersects(inventory[i].ItemRectangle))
{
if (Input.EdgeDetectLeftMouseDown())
{
// You can replace the switch with this shorter structure
// if A is a bool value, !A will have the opposite value
inventory[i].ItemSelected = !inventory[i].ItemSelected;
}
}
else if (Input.EdgeDetectLeftMouseDown())
{
// You don't need a case-switch for a single condition. An if should suffice
if (inventory[i].ItemSelected)
inventory[i].ItemSelected = false;
}
else if (inventory[i].ItemSelected == true)
{
inventory[i].ItemPosition = new Vector2(mouseRectangle.X, mouseRectangle.Y);
inventory[i].ItemRectangle = new Rectangle(mouseRectangle.X, mouseRectangle.Y, 32, 32);
}
else if (inventory[i].ItemSelected == false && //a lot of checks to determine it is not intersecting with an equip slot
{
inventory[i].ItemPosition = inventory[i].OriginItemPosition;
inventory[i].ItemRectangle = inventory[i].OriginItemRectangle;
}
// Something definitely wrong with this line, a rectangle to instersect with itself??
else if (inventory[i].ItemRectangle.Intersects(inventory[PROBABLY_SOMETHING_ELSE].ItemRectangle))
{
Swap (ref inventory[i], ref inventory[PROBABLY_SOMETHING_ELSE])
}
}

Related

Skip foreach X positions

I want skip my in foreach. For example:
foreach(Times t in timeList)
{
if(t.Time == 20)
{
timeList.Skip(3);
}
}
I want "jump" 3 positions in my list.. If, in my if block t.Id = 10 after skip I want get t.Id = 13
How about this? If you use a for loop then you can just step the index forward as needed:
for (var x = 0; x < timeList.Length; x++)
{
if (timeList[x].Time == 20)
{
// option 1
x += 2; // 'x++' in the for loop will +1,
// we are adding +2 more to make it 3?
// option 2
// x += 3; // just add 3!
}
}
You can't modify an enumerable in-flight, as it were, like you could the index of a for loop; you must account for it up front. Fortunately there are several way to do this.
Here's one:
foreach(Times t in timeList.Where(t => t.Time < 20 || t.Time > 22))
{
}
There's also the .Skip() option, but to use it you must break the list into two separate enumerables and then rejoin them:
var times1 = timeList.TakeWhile(t => t.Time != 20);
var times2 = timeList.SkipeWhile(t => t.Time != 20).Skip(3);
foreach(var t in times1.Concat(times2))
{
}
But that's not exactly efficient, as it requires iterating over the first part of the sequence twice (and won't work at all for Read Once -style sequences). To fix this, you can make a custom enumerator:
public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> items, Predicate<T> SkipTrigger, int SkipCount)
{
bool triggered = false;
int SkipsRemaining = 0;
var e = items.GetEnumerator();
while (e.MoveNext())
{
if (!triggered && SkipTrigger(e.Current))
{
triggered = true;
SkipsRemaining = SkipCount;
}
if (triggered)
{
SkipsRemaining--;
if (SkipsRemaining == 0) triggered = false;
}
else
{
yield return e.Current;
}
}
}
Then you could use it like this:
foreach(Times t in timeList.SkipAt(t => t.Times == 20, 3))
{
}
But again: you still need to decide about this up front, rather than inside the loop body.
For fun, I felt like adding an overload that uses another predicate to tell the enumerator when to resume:
public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> items, Predicate<T> SkipTrigger, Predicate<T> ResumeTrigger)
{
bool triggered = false;
var e = items.GetEnumerator();
while (e.MoveNext())
{
if (!triggered && SkipTrigger(e.Current))
{
triggered = true;
}
if (triggered)
{
if (ResumeTrigger(e.Current)) triggered = false;
}
else
{
yield return e.Current;
}
}
}
You can use continue with some simple variables.
int skipCount = 0;
bool skip = false;
foreach (var x in myList)
{
if (skipCount == 3)
{
skip = false;
skipCount = 0;
}
if (x.time == 20)
{
skip = true;
skipCount = 0;
}
if (skip)
{
skipCount++;
continue;
}
// here you do whatever you don't want to skip
}
Or if you can use a for-loop, increase the index like this:
for (int i = 0; i < times.Count)
{
if (times[i].time == 20)
{
i += 2; // 2 + 1 loop increment
continue;
}
// here you do whatever you don't want to skip
}

SortedSet inserting element out of sort

I’ve written an implementation of A* that relies on sorting nodes by their F score in a sortedSet.
The sorting, in some cases, seems to insert a Node object at the 'Min' value when its compared 'F' value is actually the second lowest rather than the Min, as described. I'm completely baffled as to why this is happening. I believe it's causing the knock-on effect of causing nodeTree.Remove and nodeTree.RemoveWhere to fail, but that might be the actual cause of the issue, I'm honestly not sure - though I wouldn't know how to fix it if it is.
This is the comparer used. I assume it's relatively obvious that I'm not exactly sure how to implement these, but I think this should work as I intend.
public class FValueFirst : Comparer<PathfindingAgent.Node>
{
public override int Compare(PathfindingAgent.Node x, PathfindingAgent.Node y)
{
int result = x.F.CompareTo(y.F);
if (result == 0)
{
result = y.G.CompareTo(x.G);
}
if(x == y)
{
result = 0;
}
return result;
}
}
This is the Node object, for reference.
public class Node
{
public Cell cell;
public float G;
public float H;
public bool Opened;
public bool Closed;
public Node Previous;
public float F { get => G + H; }
}
This is the function it all occurs in. The result is deterministic, thankfully. Depending on the current destID and the particular layout of the grid's obstacles it will always get out of sort on the same iteration.
public void PathTo(Vector3Int destID)
{
SortedSet<Node> nodeTree = new SortedSet<Node>(new FValueFirst());
Vector3Int radius = PathfindingGrid.Instance.GridRadius;
NodeGrid = new Node[radius.x * 2 + 1, radius.y * 2 + 1, radius.z * 2 + 1];
Node startNode = new Node()
{
cell = PathfindingGrid.Cells[CurrentID.x, CurrentID.y, CurrentID.z],
G = 0,
H = 0
};
Node endNode = new Node()
{
cell = PathfindingGrid.Cells[destID.x, destID.y, destID.z],
G = 0,
H = 0
};
Vector3Int sID = startNode.cell.ID;
Vector3Int eID = endNode.cell.ID;
NodeGrid[sID.x, sID.y, sID.z] = startNode;
NodeGrid[eID.x, eID.y, eID.z] = endNode;
if (endNode.cell.IsOccupied) return;
nodeTree.Add(startNode);
int iterations = 0;
while(true)
{
Node node;
node = nodeTree.Min;
node.Closed = true;
nodeTree.RemoveWhere(n => n == node);
if(node == nodeTree.Min)
{
throw new Exception($"Incorrect node was removed from the tree");
}
if (node == endNode)
{
List<Node> chain = BacktraceChain(node);
Debug.Log($"Path found from {CurrentID} to {destID} with score {endNode.G} traversing {chain.Count} cells in {iterations} iterations");
DrawLine(chain, Color.white);
break;
}
List<Node> neighbours = GetNeighbours(node);
foreach(Node neighbour in neighbours)
{
if (neighbour == startNode || neighbour.Closed) continue;
float newg = Vector3Int.Distance(node.cell.ID, neighbour.cell.ID) + node.G;
if (!neighbour.Opened || newg < neighbour.G)
{
neighbour.G = newg;
neighbour.H = ManhattanHeuristic(neighbour, endNode);
neighbour.Previous = node;
if(!neighbour.Opened)
{
nodeTree.Add(neighbour);
neighbour.Opened = true;
}
else
{
nodeTree.RemoveWhere(n => n == neighbour);
nodeTree.Add(neighbour);
}
}
}
iterations++;
}
}
For posterity, I solved the issue - it was due to my inexperience with the SortedList type.
This code, found near the end of the function was to blame
if (!neighbour.Opened || newg < neighbour.G)
{
neighbour.G = newg;
neighbour.H = ManhattanHeuristic(neighbour, endNode);
neighbour.Previous = node;
if(!neighbour.Opened)
{
nodeTree.Add(neighbour);
neighbour.Opened = true;
}
else
{
nodeTree.RemoveWhere(n => n == neighbour);
nodeTree.Add(neighbour);
}
Specifically, an item in a tree cannot have its compared values modified to the point where it no longer compares correctly in that index. The item must first be removed from the list, modified, and readded.
My guess in hindsight is that, though removed immediately after modification, the tree is unable to be sufficiently traversed to access the target item due to the modification.
Thus my solution was to simply re-arrange the block so that the removal and addition occured on either side of the modification respectively, like so:
if (!neighbour.Opened || newg < neighbour.G)
{
if (neighbour.Opened)
{
if (!nodeTree.Remove(neighbour)) throw new Exception($"{neighbour} was not removed from tree");
}
else
{
neighbour.Opened = true;
}
neighbour.G = newg;
neighbour.H = ManhattanHeuristic(neighbour, endNode);
neighbour.Previous = node;
nodeTree.Add(neighbour);
}

Reference where non should be

I have a class called Board. It has multiple columns and you can add Stones to a column by Calling AddStoneToColumn(column c). The method shouldnt modify the objet itselft but only create a new Board Object with the added stone but somehow it keeps changing itself too.
Heres my relevant Code:
public Board AddStoneToColumn(int column)
{
Board resultBoard = new Board(this);
Boolean isPlaced = false;
for (int i = 0; i < height; i++)
{
if (resultBoard.GetStone(column, i) == StoneEnum.EMPTY)
{
resultBoard.SetExactCoords(column, i, turn);
isPlaced = true;
break;
}
}
if (!isPlaced)
{
throw new InvalidOperationException("Spalte voll");
}
if (turn == StoneEnum.BLUE)
resultBoard.turn = StoneEnum.RED;
if (turn == StoneEnum.RED)
resultBoard.turn = StoneEnum.BLUE;
return resultBoard;
}
private void SetExactCoords(int x, int y, StoneEnum stone)
{
if (stone == StoneEnum.EMPTY)
throw new NotSupportedException("Empty stone ??");
this.stones[x, y] = stone;
}
public Board(Board board)
{
this.stones = board.stones;
this.turn = board.turn;
}
You are only copying references in your cloning constructor, not creating a copy of the data. You will have to duplicate those arrays/collections.
Maybe you can use a struct instead of a class?
But for your example, i would use
ICloneable Interface.
Also, you can watch this discussion too.

Merging two lists which are already sorted in c#

So i have two sorted lists with deliverable's and I want to Merge them. I never did this operation before and i can not really make it work. You can see method below that i wrote. I can not figure out while statement because it fires exception all the time. I dont know what to do...
public void MergeLists(List<Deliverable> a, List<Deliverable> b)
{
int index1 = 0;
int index2 = 0;
while (a.Count() >= index1 || b.Count() >= index2)
{
if (a[index1].ID> b[index2].ID)
{
FinalDeliverables.Add(a[index1]);
index1++;
}
else if (a[index1].ID < b[index2].ID)
{
FinalDeliverables.Add(a[index2]);
index2++;
}
else if (a[index1].ID == b[index2].ID)
{
FinalDeliverables.Add(a[index1]);
FinalDeliverables.Add(a[index2]);
index1++;
index2++;
}
}
}
I believe that the exceptions you are getting are coming from null pointers. This would occur if, for example, you already reached the end of one of the lists, yet your while loop is still trying to compare values. One workaround to this is to simply add a check before the if statements to see if one (or both) of the ends of the lists have been reached. If so, then simply add the remainder of the items from the other list.
public void MergeLists(List<Deliverable> a, List<Deliverable> b)
{
int index1 = 0;
int index2 = 0;
while (true)
{
// if the end of the 'a' list has been reached, then add
// everything from the 'b' list and break from the loop
if (index1 >= a.Count()) {
for (int i=index2; i < b.Count(); ++i) {
FinalDeliverables.Add(b[i]);
}
break;
}
// if the end of the 'b' list has been reached, then add
// everything from the 'a' list and break from the loop
if (index2 >= b.Count()) {
for (int i=index1; i < a.Count(); ++i) {
FinalDeliverables.Add(a[i]);
}
break;
}
if (a[index1].ID > b[index2].ID)
{
FinalDeliverables.Add(a[index1]);
index1++;
}
else if (a[index1].ID < b[index2].ID)
{
FinalDeliverables.Add(a[index2]);
index2++;
}
else if (a[index1].ID == b[index2].ID)
{
FinalDeliverables.Add(a[index1]);
FinalDeliverables.Add(a[index2]);
index1++;
index2++;
}
}
}
Note that a side effect of this refactor is that your original while loop no longer has to check boundaries. Instead, the loop will be terminated when one of the lists has been exhausted.
Also note that this solution assumes that your input lists are sorted in descending order.
You can use the LINQ Extension methods for this purpose, The Method signature for MergeLists will be like the following:
public void MergeLists(List<Deliverable> a, List<Deliverable> b)
{
var finalList = a.Concat(b);
List<Deliverable> FinalSortedList = finalList.OrderBy(x => x.ID).ToList();
}
Or else you can modify your own method as like the following: Before that Let me assume the following, The Count of elements in the Input list a will always be Greater than that of b. SO what you need to do is Check the count of elements before calling the method as well. So the call will be like the following:
if(a.Count>b.Count)
MergeLists(a,b);
else
MergeLists(b,a);
You mentioned that the two inputs ware sorted, Let me assume those lists are sorted in ascending order. Now consider the following code:
public void MergeLists(List<Deliverable> a, List<Deliverable> b)
{
int largeArrayCount = a.Count;
int currentBIndex = 0;
List<Deliverable> FinalResult = new List<Deliverable>();
for (int i = 0; i < largeArrayCount; i++)
{
if (i < b.Count)
{
if (a[i].ID >= b[i].ID)
{
// Add All elements of B Which is smaller than current element of A
while (a[i].ID <= b[currentBIndex].ID)
{
FinalResult.Add(b[currentBIndex++]);
}
}
else
{
FinalResult.Add(a[i]);
}
}
else
{
// No more elements in b so no need for checking
FinalResult.Add(a[i]);
}
}
}

Most efficient method for averaging list<int>

I am keeping a rolling accumulator for a graphing application, that one of the features is providing a running average of the sample.
The size of the accumulator is variable, but essentially the end goal is achieved like this.
The accumulator class (ugly but functional)
public class accumulator<t>
{
private int trim;
List<t> _points = new List<t>();
List<string> _labels = new List<string>();
List<t> _runAvg = new List<t>();
List<t> _high = new List<t>();
List<t> _low = new List<t>();
public List<t> points { get { return _points; } }
public List<string> labels { get { return _labels; } }
public List<t> runAvg { get { return _runAvg; } }
public List<t> high { get { return _high; } }
public List<t> low { get { return _low; } }
public delegate void onChangeHandler(accumulator<t> sender, EventArgs e);
public event onChangeHandler onChange;
public accumulator(int trim)
{
this.trim = trim;
}
public void add(t point, string label)
{
if (_points.Count == trim)
{
_points.RemoveAt(0);
_labels.RemoveAt(0);
_runAvg.RemoveAt(0);
_high.RemoveAt(0);
_low.RemoveAt(0);
}
_points.Add(point);
_labels.Add(label);
if (typeof(t) == typeof(System.Int32))
{
int avg = 0;
if (_high.Count == 0)
{
_high.Add(point);
}
else
{
t v = (Convert.ToInt32(point) > Convert.ToInt32(_high[0])) ? point : _high[0];
_high.Clear();
for (int i = 0; i < _points.Count; i++) _high.Add(v);
}
if (_low.Count == 0)
{
_low.Add(point);
}
else
{
t v = (Convert.ToInt32(point) < Convert.ToInt32(_low[0])) ? point : _low[0];
_low.Clear();
for (int i = 0; i < _points.Count; i++) _low.Add(v);
}
foreach (t item in _points) avg += Convert.ToInt32(item);
avg = (avg / _points.Count);
_runAvg.Add((t)(object)avg);
//_runAvg.Add((t)(object)_points.Average(a => Convert.ToInt32(a)));
}
if (typeof(t) == typeof(System.Double))
{
double avg = 0;
if (_high.Count == 0)
{
_high.Add(point);
}
else
{
t v = (Convert.ToDouble(point) > Convert.ToDouble(_high[0])) ? point : _high[0];
_high.Clear();
for (int i = 0; i < _points.Count; i++) _high.Add(v);
}
if (_low.Count == 0)
{
_low.Add(point);
}
else
{
t v = (Convert.ToDouble(point) < Convert.ToDouble(_low[0])) ? point : _low[0];
_low.Clear();
for (int i = 0; i < _points.Count; i++) _low.Add(v);
}
foreach (t item in _points) avg += Convert.ToDouble(item);
avg = (avg / _points.Count);
_runAvg.Add((t)(object)avg);
//_runAvg.Add((t)(object)_points.Average(a => Convert.ToDouble(a)));
}
onChangeHappen();
}
private void onChangeHappen()
{
if (onChange != null) onChange(this, EventArgs.Empty);
}
}
As you can see essentially I want to keep a running average, a High/Low mark (with the same count of data points so it binds directly to the chart control in an extended series class)
The average is I think what is killing me, to have to add every element of the list to a sum / divide by the count is of course how an average is achieved, but is the loop the most efficient way to do this?
I took a stab at a lambda expression (commented out) but figured on some level it had to be doing the same. (Sort of like using the generic list VS array, I figure it has to be re declaring an array somewhere and moving elements around, but it is likely being done as or more efficient than I would have, so let it do it for convenience's sake)
The ultimate goal and final question being really, given a list of generic values...
The most efficient way to average the whole list.
*Note: I DO realize the pedantic nature of typing the int/floats, this is because of type checking in the consumer of this class over which I have no control, it actually looks to see if it is double/int otherwise I would have treated it ALL as floats ;)
Thanks in advance...
Keeping a running average is actually really easy. You don't need to sum the whole list every time, because you already have it!
Once you have a current average (from your loop), you just do the following:
((oldAverage * oldCount) + newValue) / newCount
This will give you the average of the old set with the new value(s) included.
To get the initial average value, consider using the Average function from LINQ:
double average = listOfInts.Average();

Categories

Resources