How to creare ArrayList and skip it through the loop - c#

I want to write a card exchange game. I have an Arraylist of Colors in which values start from -1 to 6. Each element of this array implies id colors. There is also an ArrayList Player Properties in which cards with colors are stored. I need to create an ArrayList with eight zeros that will imply id Colors. Next, skip the ArrayList Player Properties through this array and if there is some element in the array, then increase the ArrayList Colors index by +1.
Eg:
ArrayList Colors =new ArrayList(){-1,0,1,2,3,4,5,6};
ArrayList Player Properties = new ArrayList(){0,4,6};
This array should imply that its element is an element of the Colors array
ArrayList buffer = new ArrayList(){0,0,0,0,0,0,0,0};
If an array comes to the input in this form: {0,4,6};
Then the index of this array is added by +1, like this: {0,1,0,0,0,1,0,1};
How do I implement this in code?
I don't have any code examples because I don't know how to implement it, sorry in advance that I didn't provide more code, I really need help, thank you all in advance for your help

You can use the Linq function Contains to check if a value is present in an array. Something like this:
var colors = new int[] { -1, 0, 1, 2, 3, 4, 5, 6 };
var playerProperties = new int[] { 0, 4, 4, 6 };
var result = colors.Select(c => playerProperties.Where(x => x == c).Count());
Console.WriteLine(string.Join(", ", result));
prints 0, 1, 0, 0, 0, 2, 0, 1

What you want is a histogram of the card values that you accumulate.
Since this is C# you better start thinking of a data model for each player. There are two arrays to consider, one with the card values: -1,0,..6 and one with the card counts, how many of each card a player has.
Here is how this would play out:
static class Program
{
static void Main(string[] args)
{
var player1 = new Player("Player1");
Console.WriteLine(player1);
// Player1 : 0,0,0,0,0,0,0,0
player1.Hand(0,4,6);
Console.WriteLine(player1);
// Player1: 0,1,0,0,0,1,0,1
}
}
You can to this point with the following Player class that handles the logic inside the .Hand() method.
public class Player
{
public static readonly int[] CardValues = { -1, 0, 1, 2, 3, 4, 5, 6 };
public Player(string name)
{
CardCounts = new int[CardValues.Length];
Name = name;
}
public int[] CardCounts { get; }
public string Name { get; }
public void Hand(params int[] cards)
{
foreach (var card in cards)
{
int index = Array.IndexOf(CardValues, card);
if (index >= 0)
{
CardCounts[index] += 1;
}
}
}
public override string ToString()
{
return $"{Name} : {string.Join(",", CardCounts)}";
}
}
Note that ArrayList is really old technology, and not type safe. In it place there is List<>, but in this case the length of the array is fixed since there is a finite set of card values, and that does not change, so no need for a collection, as a plain old Array would suffice.

Because your array is a fixed representation:
var Colors = new []{-1,0,1,2,3,4,5,6};
var PlayerProperties = new []{0,4,6};
var buffer = new []{0,0,0,0,0,0,0,0};
You can calculate which indexes in the buffer should be set to 1
foreach(var pp in PlayerProperties)
buffer[pp+1] += 1;
Value 0 always occurs at index 1. Value 4 always occurs at index 5. Value 6 always occurs at index 7. Thus the formula is value+1..

Related

SortedSet.Remove () not working with custom comparer class

I am trying to solve a leetcode problem, where I want to get top k frequent numbers. I am trying to solve it using SortedSet for O(log n) time complexity.
My code is working for all inputs except one particular input.
public class FreqNode
{
public int number;
public int freq;
public FreqNode(int n, int f)
{
number = n;
freq = f;
}
}
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 3, 2, 3, 1, 2, 4, 5, 5, 6, 7, 7, 8, 2, 3, 1, 1, 1, 10, 11, 5, 6, 2, 4, 7, 8, 5, 6};
TopKFrequent(arr, 10);
Console.Read();
}
static void TopKFrequent(int[] nums, int k)
{
SortedSet<FreqNode> sl = new SortedSet<FreqNode>(new MyComparer());
Dictionary<int, FreqNode> ht = new Dictionary<int, FreqNode>();
foreach (int i in nums)
{
if (ht.ContainsKey(i))
{
sl.Remove(ht[i]);
ht[i].freq += 1;
}
else
{
ht[i] = new FreqNode(i, 1);
}
sl.Add(ht[i]);
}
for (int i = 0; i < k; i++)
{
FreqNode f = sl.ElementAt(i);
Console.WriteLine(f.number);
}
}
}
public class MyComparer : IComparer<FreqNode>
{
public int Compare(FreqNode fn1, FreqNode fn2)
{
//Remove entry with same number
//Retain entries with same frequencies.
if (fn1.number == fn2.number)
{
return 0;
}
else
{
int res = fn2.freq.CompareTo(fn1.freq);
if (res == 0)
{
return 1;
}
else
{
return res;
}
}
}
}
It prints output as - 1,2,5,3,7,6,6,4,8,10
instead of - 1,2,5,3,6,7,4,8,10,11
During debugging, I noticed that Comparer code does not compare with existing entry of number 6. After further investigation, I found that, SortedSet is implemented using Red-Black tree, but I could not resolve this bug in my code.
This problem was interesting to me because I thought it might be a SortedSet bug and had me stepping through the SortedSet source. Alas, not a SortedSet bug...sorry but your IComparer is a bit wonky.
Your IComparer implementation does weird things to the comparison by first changing the criteria of sort comparison, then by inverting the comparison objects, then by changing the return value.
First your comparer is saying,
if "number" properties are equal, the nodes are equal (this is fine)
if (fn1.number == fn2.number)
{
return 0;
}
then it's saying
sort on the inverse of the freq property (switching fn2 with fn1 is probably not a good idea, and the criteria of sort has changed to the 'freq' property (probably ok))
int res = fn2.freq.CompareTo(fn1.freq);
then it's changing equal freqs to not be equal
if the result of the 'freq' comparison was equal, let's pretend like it's not equal (probably not a good idea)
if (res == 0)
{
return 1;
}
The poor SortedSet's root must be rotating!! (HAHAHA!! I made a Data Structures joke!! get it "root"? "rotating"?)
In the end, the Remove algorithm looks for the '6' as a right child because your IComparer tells it that's where it should be, meanwhile '6' is actually a left child, so the Remove algorithm misses it.
As an aside, keep in mind that the 2 '6' nodes in your SortedSet and the '6' node in your dictionary are all actually the same FreqNode reference, so you can change all of them at the same time if you needed to.
You can look at (and download) the .NET source here
then set up Visual Studio to debug sources by following the instructions here
Lastly, if you insist solving the top-k problem this way, try this comparer:
public class MyComparer : IComparer<FreqNode>
{
public int Compare(FreqNode fn1, FreqNode fn2)
{
return fn1.number == fn2.number ? fn1.freq.CompareTo(fn2.freq) : fn1.number.CompareTo(fn2.number);
}
}
Cheers and thanks for a fun debug!

In c# - Arrays in set and get method implement

I am strugling with the int[Array] since yesterday.
I have the following code:
public int[] Numbers
{
get
{
return class.intNumbers();
}
set
{
int[] Number = class.intNumbers();
Number[Number.Length + 1] = value;
writer.NumberValue("Name", "Id", "Here goes the Array");
}
}
What I want the code to do is to take the array from other class and on the next index to put my value.(Fails at Number[Number + 1] = value;) The get method is succesfully finished, all I have to do now is "set". Do you have any ideas?
P.S I only want to use array and not arraylist :)
You can use ArrayResizer, although I don't know why you do not want to use List here.
int[] arr = { 1, 2, 3 };
Array.Resize(ref arr , 5);
https://msdn.microsoft.com/en-us/library/bb348051(v=vs.110).aspx
You could also implement private List<int> numberList
Then return numberList.ToArray(); in getter.

How to pass enum as method parameter?

The task is to write a simple method that can sort int array (in ascending or descending order - should be set as enum type parameter of this method). I have written the method itself and enum, but I have no idea how to set enum as method parameter:(
Would be great to get any help from you, guys, cause I am completely new to coding.
class Program
{
public enum options
{
UpSortOption,
DownSortOption
}
public static void Main(string[] args)
{
int[] arr = new int[] { 3, 8, 0, 2, 16 };
}
static void orderArray(int [] array, options op)
{
switch(op)
{
case options.UpSortOption:
Array.Sort(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
break;
case options.DownSortOption:
Array.Sort(array);
Array.Reverse(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
break;
}
}
}
The signature of the method looks fine, Now you wanted to call this method by passing the first parameter of type integer array and the second parameter of type options for that you can use the following code:
orderArray(arr,options.UpSortOption);
Or else you can declare a variable of type options and pass that variable, the change you have to make for that case will be:
options optionsVariable = options.DownSortOption;
orderArray(arr,optionsVariable);
Let's take a step back to see if it helps your understanding.
If you have a method that takes a string and an int like this
string MyMethod(string str, int num)
{
// Do something
}
You'd use it like this
string rslt = MyMethod("Hello", 123);
What you've got here is something that takes in some stuff, does something to it, and gives you something in return. In this case MyMethod takes a string and an int, does something with them and returns a string which you then call rslt.
Your example follows the same basic pattern so you need to take your method - orderArray and give it the two things it wants - an int array and an option like this
int[] arr = new int[] { 3, 8, 0, 2, 16 };
orderArray(arr, options.UpSortOption);
Alternatively, you could create an options much like you'd create a string and then call your method like this
int[] arr = new int[] { 3, 8, 0, 2, 16 };
options myOption = options.UpSortOption;
orderArray(arr, myOption);
To fully illustrate the point that an enum as a parameter isn't any different from say a string you could modify your method like this
static void orderArray(int[] array, string op)
{
if (op == "UpSortOption")
{
Array.Sort(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
}
else
{
Array.Sort(array);
Array.Reverse(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
}
}
Then call it like this
int[] arr = new int[] { 3, 8, 0, 2, 16 };
string myOption = "UpSortOption";
orderArray(arr, myOption);
This is how you pass it as a parameter
orderArray(int [] array, typeof(options)){
//Beep bap boop
}
Hope this aids you.
Exactly that's how you set up Enum as a method parameter.
To call this method use:
orderArray(arr, options.UpSortOption);
You can also assign enum value to a variable and use this to call a method:
options sortOpt = options.UpSortOption;
orderArray(arr, sortOpt);
You can also cast integer to an enum:
orderArray(arr, (options)0);
OR
int opt = 0;
orderArray(arr, (options)opt);
Remembering, that if not specified otherwise, first element is 0, second is 1 and so on.
By the way, you should rather use PascalCase to name an enum type, like:
public enum Options
{ ... }

Display set of items in array(list of type X)

How can I display a specific set of items in an array?
I want to print 25 items to screen from index 0 to 24 and another 25 starting from index 25, in that order.
I can display all items, but how can I display from a specific index in the array to another specific index?
Example: I have 100 items in my array.
And I want to show from 0 to 3 and from 4 to 7 and so on.
For Example: String of letters: A B C D E F G etc.
And I want to show only A B C. But when I do something it show next 3 in array.
Since im using B_items as object in an array. I wanna show only 0, 1, 2 in array and again form 3, 4, 5 and so on.
public class B_items
{
public string Name {get; set;}
public int Value { Get; set;}
}
B_items[,] items;
public Inventory(Backpack Bpack, int Columns, int Rows, int SlotWidth, int SlothHeight, Vector2 Pos)
{
items = new B_items[Columns, Rows];
pos = Pos;
slotWight = SlotWidth;
slotHeight = SlothHeight;
backpack = Bpack;
this.Columns = Columns;
this.Rows = Rows;
LoadItems(Bpack);
}
for(int i = 0; i < items.Length; i++)
{
Console.WritleLine(Items[i].Name;
}
}
if (items[X, Y] != null)
{
spriteBatch.Draw(items[X, Y].Texure, new Rectangle(DrawX, DrawY, slotWight, slotHeight),new Rectangle(0,0,64,64),Color.White);
if (items[X, Y].StackSize > 1)
{
spriteBatch.DrawString(AssetManager.GetInstance().font["Arial8"], items[X, Y].StackSize.ToString(), new Vector2(DrawX + 24, DrawY + 22), Color.White);
}
}
This will write all and I want to do 5 of those. While I have 100 and each time I press a button it shows next 5 in that list.
How can I show specific list of items...form index 0 to 10 and form 11 to 20 and so on.
var stats = items.Skip(5).Take(5)
I can't do this... I do not see .Take(param) or .Skip(param)
I am using
using System.Linq;
using System;
I'm sorry for not being specific. I can't nor sometimes know how to ask a valid question. My English is not my first language so fix my grammar and delete this line
And I want to show from 0 to 3 and from 4 to 7 and so on.
You can use a normal for-loop and specify the step size that you want to increment. Every step you would skip the items that you have already processed and take each time only the specified step size (in your case 3).
This should do the trick:
// test array
int[] array = Enumerable.Range(1, 100).ToArray();
int stepsize = 3;
for (int i = 0; i < array.Length; i += stepsize)
{
string s = String.Join(" ", array.Skip(i).Take(stepsize));
Console.WriteLine(s);
}
You can use LINQ to access ranges of your array. Skip lets you decide where you start your range and Take how many entries you want.
If you want D E F from your example you can use:
var subRange = items.Skip(3).Take(3);
foreach (string item in subRange) {
Console.WriteLine(item);
}

in C#, how do I order items in a list where the "largest" values are in the middle of the list

I have been stumped on this one for a while. I want to take a List and order the list such that the Products with the largest Price end up in the middle of the list. And I also want to do the opposite, i.e. make sure that the items with the largest price end up on the outer boundaries of the list.
Imagine a data structure like this.. 1,2,3,4,5,6,7,8,9,10
In the first scenario I need to get back 1,3,5,7,9,10,8,6,4,2
In the second scenario I need to get back 10,8,6,4,2,1,3,5,7,9
The list may have upwards of 250 items, the numbers will not be evenly distributed, and they will not be sequential, and I wanted to minimize copying. The numbers will be contained in Product objects, and not simple primitive integers.
Is there a simple solution that I am not seeing?
Any thoughts.
So for those of you wondering what I am up to, I am ordering items based on calculated font size. Here is the code that I went with...
The Implementation...
private void Reorder()
{
var tempList = new LinkedList<DisplayTag>();
bool even = true;
foreach (var tag in this) {
if (even)
tempList.AddLast(tag);
else
tempList.AddFirst(tag);
even = !even;
}
this.Clear();
this.AddRange(tempList);
}
The Test...
[TestCase(DisplayTagOrder.SmallestToLargest, Result=new[]{10,14,18,22,26,30})]
[TestCase(DisplayTagOrder.LargestToSmallest, Result=new[]{30,26,22,18,14,10})]
[TestCase(DisplayTagOrder.LargestInTheMiddle, Result = new[] { 10, 18, 26, 30, 22, 14 })]
[TestCase(DisplayTagOrder.LargestOnTheEnds, Result = new[] { 30, 22, 14, 10, 18, 26 })]
public int[] CalculateFontSize_Orders_Tags_Appropriately(DisplayTagOrder sortOrder)
{
list.CloudOrder = sortOrder;
list.CalculateFontSize();
var result = (from displayTag in list select displayTag.FontSize).ToArray();
return result;
}
The Usage...
public void CalculateFontSize()
{
GetMaximumRange();
GetMinimunRange();
CalculateDelta();
this.ForEach((displayTag) => CalculateFontSize(displayTag));
OrderByFontSize();
}
private void OrderByFontSize()
{
switch (CloudOrder) {
case DisplayTagOrder.SmallestToLargest:
this.Sort((arg1, arg2) => arg1.FontSize.CompareTo(arg2.FontSize));
break;
case DisplayTagOrder.LargestToSmallest:
this.Sort(new LargestFirstComparer());
break;
case DisplayTagOrder.LargestInTheMiddle:
this.Sort(new LargestFirstComparer());
Reorder();
break;
case DisplayTagOrder.LargestOnTheEnds:
this.Sort();
Reorder();
break;
}
}
The appropriate data structure is a LinkedList because it allows you to efficiently add to either end:
LinkedList<int> result = new LinkedList<int>();
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Array.Sort(array);
bool odd = true;
foreach (var x in array)
{
if (odd)
result.AddLast(x);
else
result.AddFirst(x);
odd = !odd;
}
foreach (int item in result)
Console.Write("{0} ", item);
No extra copying steps, no reversing steps, ... just a small overhead per node for storage.
C# Iterator version
(Very simple code to satisfy all conditions.)
One function to rule them all! Doesn't use intermediate storage collection (see yield keyword). Orders the large numbers either to the middle, or to the sides depending on the argument. It's implemented as a C# iterator
// Pass forward sorted array for large middle numbers,
// or reverse sorted array for large side numbers.
//
public static IEnumerable<long> CurveOrder(long[] nums) {
if (nums == null || nums.Length == 0)
yield break; // Nothing to do.
// Move forward every two.
for (int i = 0; i < nums.Length; i+=2)
yield return nums[i];
// Move backward every other two. Note: Length%2 makes sure we're on the correct offset.
for (int i = nums.Length-1 - nums.Length%2; i >= 0; i-=2)
yield return nums[i];
}
Example Usage
For example with array long[] nums = { 1,2,3,4,5,6,7,8,9,10,11 };
Start with forward sort order, to bump high numbers into the middle.
Array.Sort(nums); //forward sort
// Array argument will be: { 1,2,3,4,5,6,7,8,9,10,11 };
long[] arrLargeMiddle = CurveOrder(nums).ToArray();
Produces: 1 3 5 7 9 11 10 8 6 4 2
Or, Start with reverse sort order, to push high numbers to sides.
Array.Reverse(nums); //reverse sort
// Array argument will be: { 11,10,9,8,7,6,5,4,3,2,1 };
long[] arrLargeSides = CurveOrder(nums).ToArray();
Produces: 11 9 7 5 3 1 2 4 6 8 10
Significant namespaces are:
using System;
using System.Collections.Generic;
using System.Linq;
Note: The iterator leaves the decision up to the caller about whether or not to use intermediate storage. The caller might simply be issuing a foreach loop over the results instead.
Extension Method Option
Optionally change the static method header to use the this modifier public static IEnumerable<long> CurveOrder(this long[] nums) { and put it inside a static class in your namespace;
Then call the order method directly on any long[ ] array instance like so:
Array.Reverse(nums); //reverse sort
// Array argument will be: { 11,10,9,8,7,6,5,4,3,2,1 };
long[] arrLargeSides = nums.CurveOrder().ToArray();
Just some (unneeded) syntactic sugar to mix things up a bit for fun. This can be applied to any answers to your question that take an array argument.
I might go for something like this
static T[] SortFromMiddleOut<T, U>(IList<T> list, Func<T, U> orderSelector, bool largestInside) where U : IComparable<U>
{
T[] sortedArray = new T[list.Count];
bool add = false;
int index = (list.Count / 2);
int iterations = 0;
IOrderedEnumerable<T> orderedList;
if (largestInside)
orderedList = list.OrderByDescending(orderSelector);
else
orderedList = list.OrderBy(orderSelector);
foreach (T item in orderedList)
{
sortedArray[index] = item;
if (add)
index += ++iterations;
else
index -= ++iterations;
add = !add;
}
return sortedArray;
}
Sample invocations:
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] sortedArray = SortFromMiddleOut(array, i => i, false);
foreach (int item in sortedArray)
Console.Write("{0} ", item);
Console.Write("\n");
sortedArray = SortFromMiddleOut(array, i => i, true);
foreach (int item in sortedArray)
Console.Write("{0} ", item);
With it being generic, it could be a list of Foo and the order selector could be f => f.Name or whatever you want to throw at it.
The fastest (but not the clearest) solution is probably to simply calculate the new index for each element:
Array.Sort(array);
int length = array.Length;
int middle = length / 2;
int[] result2 = new int[length];
for (int i = 0; i < array.Length; i++)
{
result2[middle + (1 - 2 * (i % 2)) * ((i + 1) / 2)] = array[i];
}
Something like this?
public IEnumerable<int> SortToMiddle(IEnumerable<int> input)
{
var sorted = new List<int>(input);
sorted.Sort();
var firstHalf = new List<int>();
var secondHalf = new List<int>();
var sendToFirst = true;
foreach (var current in sorted)
{
if (sendToFirst)
{
firstHalf.Add(current);
}
else
{
secondHalf.Add(current);
}
sendToFirst = !sendToFirst;
}
//to get the highest values on the outside just reverse
//the first list instead of the second
secondHalf.Reverse();
return firstHalf.Concat(secondHalf);
}
For your specific (general) case (assuming unique keys):
public static IEnumerable<T> SortToMiddle<T, TU>(IEnumerable<T> input, Func<T, TU> getSortKey)
{
var sorted = new List<TU>(input.Select(getSortKey));
sorted.Sort();
var firstHalf = new List<TU>();
var secondHalf = new List<TU>();
var sendToFirst = true;
foreach (var current in sorted)
{
if (sendToFirst)
{
firstHalf.Add(current);
}
else
{
secondHalf.Add(current);
}
sendToFirst = !sendToFirst;
}
//to get the highest values on the outside just reverse
//the first list instead of the second
secondHalf.Reverse();
sorted = new List<TU>(firstHalf.Concat(secondHalf));
//This assumes the sort keys are unique - if not, the implementation
//needs to use a SortedList<TU, T>
return sorted.Select(s => input.First(t => s.Equals(getSortKey(t))));
}
And assuming non-unique keys:
public static IEnumerable<T> SortToMiddle<T, TU>(IEnumerable<T> input, Func<T, TU> getSortKey)
{
var sendToFirst = true;
var sorted = new SortedList<TU, T>(input.ToDictionary(getSortKey, t => t));
var firstHalf = new SortedList<TU, T>();
var secondHalf = new SortedList<TU, T>();
foreach (var current in sorted)
{
if (sendToFirst)
{
firstHalf.Add(current.Key, current.Value);
}
else
{
secondHalf.Add(current.Key, current.Value);
}
sendToFirst = !sendToFirst;
}
//to get the highest values on the outside just reverse
//the first list instead of the second
secondHalf.Reverse();
return(firstHalf.Concat(secondHalf)).Select(kvp => kvp.Value);
}
Simplest solution - order the list descending, create two new lists, into the first place every odd-indexed item, into the other every even indexed item. Reverse the first list then append the second to the first.
Okay, I'm not going to question your sanity here since I'm sure you wouldn't be asking the question if there weren't a good reason :-)
Here's how I'd approach it. Create a sorted list, then simply create another list by processing the keys in order, alternately inserting before and appending, something like:
sortedlist = list.sort (descending)
biginmiddle = new list()
state = append
foreach item in sortedlist:
if state == append:
biginmiddle.append (item)
state = prepend
else:
biginmiddle.insert (0, item)
state = append
This will give you a list where the big items are in the middle. Other items will fan out from the middle (in alternating directions) as needed:
1, 3, 5, 7, 9, 10, 8, 6, 4, 2
To get a list where the larger elements are at the ends, just replace the initial sort with an ascending one.
The sorted and final lists can just be pointers to the actual items (since you state they're not simple integers) - this will minimise both extra storage requirements and copying.
Maybe its not the best solution, but here's a nifty way...
Let Product[] parr be your array.
Disclaimer It's java, my C# is rusty.
Untested code, but you get the idea.
int plen = parr.length
int [] indices = new int[plen];
for(int i = 0; i < (plen/2); i ++)
indices[i] = 2*i + 1; // Line1
for(int i = (plen/2); i < plen; i++)
indices[i] = 2*(plen-i); // Line2
for(int i = 0; i < plen; i++)
{
if(i != indices[i])
swap(parr[i], parr[indices[i]]);
}
The second case, Something like this?
int plen = parr.length
int [] indices = new int[plen];
for(int i = 0; i <= (plen/2); i ++)
indices[i] = (plen^1) - 2*i;
for(int i = 0; i < (plen/2); i++)
indices[i+(plen/2)+1] = 2*i + 1;
for(int i = 0; i < plen; i++)
{
if(i != indices[i])
swap(parr[i], parr[indices[i]]);
}

Categories

Resources