How can I make my PokerHand class randomly deal a thousand hands? - poker

public class PokerHand
{
// ArrayList for cards
private ArrayList<Card> cards;
/**
* Constructor for class Pokerhand
*/
public PokerHand()
{
cards = new ArrayList<Card>(); // arrayList of cards
}
/**
* Add cards to list
*/
public void addCard(Card card1, Card card2, Card card3)
{
cards.add(card1);
cards.add(card2);
cards.add(card3);
}
}
This is my Card Class
public class Card()
{
private int value;
private int suit;
private static String[] suits = { "hearts", "spades", "diamonds", "clubs" };
private static String[] values = { "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King" };
public static String valueAsString( int value ) {
return values[value];
}
Card(int suit, int rank)
{
this.value=value;
this.suit=suit;
}
public String toString()
{
return values[value] + " of " + suits[suit];
}
public int getValue() {
return value;
}
public int getSuit() {
return suit;
}
}
How can I deal a 1000 three card hands? I am stuck on how a variety of things, including what additional methods I need. How can I construct a deal method and how can I make the deal method dish out a thousand random hands while shuffling every time a hand is dealt?

All of these are implementations are based on code from my card library.
Shuffle
public Card[] shuffle(Card[] deck) {
Random gen = new Random();
boolean[] added = new boolean[deck.length];
int positionToAdd = gen.nextInt(deck.length);
Card[] newDeck = new Card[deck.length];
for (int i = 0; i < deck.length; i++) {
while (newDeck[i] == null) {
if (!added[positionToAdd]) {
newDeck[i] = deck[positionToAdd];
positionToAdd = gen.nextInt(deck.length);
added[i] = true;
} else {
positionToAdd = gen.nextInt(deck.length);
}
}
}
return newDeck;
}
Implementation
ArrayList<Card> dealFrom = new ArrayList<Card>();
PokerHand[] hands = new PokerHand[1000];
/*Populate the "dealFrom" yourself here*/
dealFrom = Array.asList(shuffle(dealFrom.toArray()));
for (int i = 0; i < 3000; i += 3) {
//Write your deal method here
hands[i] = new PokerHand(dealFrom[i], dealFrom[i + 1], dealFrom[i + 2]);
}
Hope this helps.

Related

AutomationPeer.GetChildrenCore () only reports first child to VisualStudio.TestTools

I'm not able to override GetChildrenCore correctly. I use this for a Canvas to get information about it's children (Line, Rectangle).
The output correctly indicates the first child but misses the second. Even though the Canvas already contains both.
Custom Canvas
Custom Line Childs of Canvas parent: 2
Instead it should be like this:
Custom Canvas
Custom Line Childs of Canvas parent: 2
Custom Rectangle Childs of Canvas parent: 2
App side side:
public class ElementAP : FrameworkElementAutomationPeer
{
private FrameworkElement Owner = null;
private Int32 Count = 0;
public ElementAP(FrameworkElement owner, Int32 count) : base (owner)
{
Owner = owner;
Count = count;
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.Custom;
}
protected override string GetClassNameCore()
{
return $"{Owner.GetType().Name} Childs of Canvas parent: {Count}";
}
}
public class CanvasAP : FrameworkElementAutomationPeer
{
public CanvasAP(Windows.UI.Xaml.Controls.Canvas owner) : base(owner)
{
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.Custom;
}
protected override string GetClassNameCore()
{
return "Canvas";
}
protected override IList<AutomationPeer> GetChildrenCore()
{
var owner = (Windows.UI.Xaml.Controls.Canvas)Owner;
var list = new List<AutomationPeer> ();
foreach (var child in owner.Children)
{
var peer = new ElementAP(child as FrameworkElement, owner.Children.Count);
list.Add(peer);
}
return list;
}
}
UI Testing side:
private static string WalkTree(UITestControl element, Int32 level = 0)
{
var children = element.GetChildren();
var str = "";
foreach (var c in children)
{
str += GetElementString(c, level);
str += WalkTree(c, level + 1);
}
return str;
}
private static string GetElementString(UITestControl element, Int32 level = 0)
{
var xaml = element as XamlControl;
var str = "";
for (var i = 0; i < level; i++)
str += " ";
str += $"{element.ControlType} {element.ClassName} {element.Name} {xaml?.AutomationId ?? ""}\n";
return str;
}
I finally found an answer. When using a cache for the children`s AutomationPeers it works perfectly.
public class ElementAP : FrameworkElementAutomationPeer
{
public UIElement Element { get { return Owner; } }
public ElementAP(FrameworkElement owner) : base(owner)
{
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.Custom;
}
protected override string GetClassNameCore()
{
return Owner.GetType().Name;
}
}
public class CanvasAP : FrameworkElementAutomationPeer
{
private List<ElementAP> _cachedAutomationPeers = new List<ElementAP>();
public CanvasAP(Windows.UI.Xaml.Controls.Canvas owner) : base(owner)
{
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.Custom;
}
protected override string GetClassNameCore()
{
return "Canvas";
}
protected override IList<AutomationPeer> GetChildrenCore()
{
var owner = (Windows.UI.Xaml.Controls.Canvas)Owner;
if (owner.Children.All(c => c is CanvasA))
return base.GetChildrenCore();
var list = new List<ElementAP>();
foreach (var child in owner.Children)
{
var peer = _cachedAutomationPeers.FirstOrDefault(p => p.Element == child) ?? new ElementAP(child as FrameworkElement);
list.Add(peer);
}
_cachedAutomationPeers = list;
return list.Cast<AutomationPeer>().ToList();
}
}

For Loop Returning A Range

my BlueJ project has 2 classes: StateProvince and Country. Below is the StateProvince class first, then the Country class where I'm at. I'm stuck on a method: "public int howManyHaveThisPopulation(int min, int max)" which takes the population in millions(e.g. 4, 6) and returns how many StateProvinces there are with populations in that range(e.g. 4-6 million, inclusive). I am not able to set it up and return the right answer. I would like help on how I can do this please. With how my method is now, the error message is that I'm missing a return statement. I know my method isn't correct. I have listed the class below and my progress on the method:
public class StateProvince
{
private String name; //e.g. "British Columbia" or "California"
private String capital; //e.g. "Victoria or "Sacramento"
private int populationInMillions; //e.g. 4 or 38
private final static int DEFAULT_POPULATION_MILLIONS = 4;
private final static String DEFAULT_STATE_PROVINCE = "British Columbia";
private final static String DEFAULT_CAPITAL = "Victoria";
public StateProvince()
{
}
/**
* constructor that takes in all 3 parameters and assigns them if they follow the rules:
* name: must be one of the 50 Unites States or 10 Canadian Provinces
* capital: must be the name of the capital city
* populationInMillions: must be between 0 and 38
*/
public StateProvince(String name, String capital, int populationInMillions)
{
if(isValidPopulation(populationInMillions) && (isValidStateProvince(name) &&
(isValidCapitalCity(capital))))
{
this.populationInMillions = populationInMillions;
this.name = name;
this.capital = capital;
}else
{
this.populationInMillions = DEFAULT_POPULATION_MILLIONS; //
this.name = DEFAULT_STATE_PROVINCE; //"British Columbia"
this.capital = DEFAULT_CAPITAL; //"Victoria"
}
}
//StateProvince p1 = new StateProvince("British Columbia", "Victoria", 5);
private boolean isValidStateProvince(String name)
{
String[] provinces = new String[10];
provinces[0] = "British Columbia";
provinces[1] = "Alberta";
provinces[2] = "Saskatchewan";
provinces[3] = "Manitoba";
provinces[4] = "Ontario";
provinces[5] = "Quebec";
provinces[6] = "PEI";
provinces[7] = "Newfoundland";
provinces[8] = "New Brunswick";
provinces[9] = "Nova Scotia";
for(int index = 0; index < provinces.length; index++)
{
if(provinces[index].equalsIgnoreCase(name))
{
return true;
}
index++;
}
return false;
}
private boolean isValidCapitalCity(String capital)
{
String[] capitals = new String[10];
capitals[0] = "Victoria";
capitals[1] = "Edmonton";
capitals[2] = "Regina";
capitals[3] = "Winnipeg";
capitals[4] = "Toronto";
capitals[5] = "Quebec City";
capitals[6] = "Charlottetown";
capitals[7] = "St. John's";
capitals[8] = "Fredericton";
capitals[9] = "Halifax";
for(int index = 0; index < capitals.length; index++)
{
if(capitals[index].equalsIgnoreCase(capital))
{
return true;
}
index++;
}
return false;
}
private boolean isValidPopulation(int populationInMillions)
{
if(populationInMillions >= 4 || populationInMillions <= 38)
{
return true;
}else
{
return false;
}
}
public void setName()
{
this.name = name;
}
public void setCapital()
{
this.capital = capital;
}
public String getName()
{
return name;
}
public String getCapital()
{
return capital;
}
public int getPopulationInMillions()
{
return populationInMillions;
}
public String getDetails()
{
return ("The capital of " + getName() + " (pop. " + populationInMillions + " million) is " + getCapital());
}
}
public class Country
{
private String country;
private StateProvince[] Canada;
public Country()
{
Canada = new StateProvince[10];
Canada[0] = new StateProvince("British Columbia", "Victoria", 4);
Canada[1] = new StateProvince("Alberta", "Edmonton", 3);
Canada[2] = new StateProvince("Saskatchewan", "Regina", 1);
Canada[3] = new StateProvince("Manitoba", "Winnipeg", 1);
Canada[4] = new StateProvince("Ontario", "Toronto", 13);
Canada[5] = new StateProvince("Quebec", "Quebec City", 8);
Canada[6] = new StateProvince("PEI", "Charlottetown", 0);
Canada[7] = new StateProvince("Newfoundland", "St. John's", 0);
Canada[8] = new StateProvince("New Brunswick", "Fredericton", 1);
Canada[9] = new StateProvince("Nova Scotia", "Halifax", 1);
}
public void displayAllStates()
{
for(int index = 0; index < Canada.length; index++)
{
if(Canada[0] != null)
{
System.out.println(Canada[index].getDetails());
}
index++;
}
}
public void addStateProvince(StateProvince stateProvince)
{
if(Canada != null)
{
for(int i = 0; i < Canada.length; i++)
{
if(Canada[i] == null)
{
Canada[i] = stateProvince;
return;
}
}
}
}
public int howManyHaveThisPopulation(int min, int max)
{
for(int i = 0; i < Canada.length; i++)
{
if(i > min && i < max)
{
return Canada[i].getPopulationInMillions();
}
}
}

Generate list from treeitem using c#

we have a list of the class
public class DummyClass
{
public string Text { get; set; }
public int LevelNo { get; set; }
public List<DummyClass> Children { get; set; }
}
we want to add this list to another list with class.
public class FragmentLevel
{
public int currentLevelNo { get; set; }
public int ParentLevelNo { get; set; }
public string Text { get; set; }
}
we need the result like
var list = new List<FragmentLevel>
{
new FragmentLevel{ id = 1, text = "Root" },
new FragmentLevel{ id = 2, parent= 1, text = "Node-1.1" },
new FragmentLevel{ id = 3, parent= 2, text = "Node-1.1.1" }
};
For getting result we are doing like
for (int i = 0; i < DummyClassList.Count; i++)
{
list.Add(new FragmentLevel
{
currentLevelNo = DummyClassList[i].LevelNo,
Text = DummyClassList[i].Text,
});
do
{
for (int j = 0; j < DummyClassList[i].Children.Count; j++)
{
list1.Add(new FragmentLevel
{
LevelNo = DummyClassList[i].Children[j].LevelNo,
Text = DummyClassList[i].Children[j].Text,
});
}
} while (DummyClassList[i].Children[i].Children != null);
}
But this will give wrong result. How we can get the result?
Try this way of filling the fragments recursively,
private static void FillFragments(List<DummyClass> DummyClassList, List<FragmentLevel> list)
{
for (int i = 0; i < DummyClassList.Count; i++)
{
list.Add(new FragmentLevel
{
currentLevelNo = DummyClassList[i].LevelNo,
Text = DummyClassList[i].Text,
});
if (DummyClassList[i].Children != null && DummyClassList[i].Children.Count > 0)
{
FillFragments(DummyClassList[i].Children, list);
}
}
}
and the main method would look like this
static void Main(string[] args)
{
var DummyClassList = new List<DummyClass>
{
new DummyClass
{
Children = new List<DummyClass>
{
new DummyClass{
Children = null,
LevelNo=2,
Text = "two"
}
},
LevelNo = 1,
Text = "one"
}
};
var list = new List<FragmentLevel>();
FillFragments(DummyClassList, list);
}

Help with linq query. many to many

I have a collection(people) that has a many-to-many reference to another collection(dogs). Suspend your disbelief on how there can be more than one people per dog. People just contains member which is an List<Dog>
I would like to select all the people where the people have a certain property(specified in an IList) and pets have a certain property(specified in an IList).
E.g. I have an IList (used for this query only) with the dog’s property value.
public enum EnumLikesToBite
{
No,
Yes,
Sometimes
}
IList <<EnumLikesToBite>> listDogsMayBite =
{ { EnumLikesToBite.Yes},
{ EnumLikesToBite.Sometimes}};
Then another list for the peoples property:
public enum EnumKeepsPetWith
{
Chain,
String,
Rubberband
}
IList <EnumKeepsPetWith> listPeopleWhoDontRestrainDog =
{ { EnumKeepsPetWith.String },
{ EnumKeepsPetWith.Rubberband}};
How can I query out all the people who have a dog that may bite and don’t restrain dog.
Like this pseudo code:
Var result = from p in People where p.KeepsPet in listPeopleWhoDontRestrainDog and dog.LikesToBite in listDogsMayBite.
Result has all the people. Of course if I could get all the dogs who may bite under those people that would be great.
List<int> mayBite = new List<int>()
{
(int) EnumLikesToBite.Yes,
(int) EnumLikesToBite.Maybe
}
List<int> poorRestraint = new List<int>()
{
(int) EnumKeepsPetWith.String,
(int) EnumKeepsPetWith.RubberBand
}
IQueryable<Person> query =
from p in db.People
where poorRestraint.Contains(p.KeepsPetWith)
where p.DogPeople.Any(dp => mayBite.Contains(dp.Dog.DoesBite))
select p;
var query =
from p in db.People
where poorRestraint.Contains(p.KeepsPetWith)
let bitingDogs =
from dp in p.DogPeople
let d = dp.Dog
where mayBite.Contains(d.DoesBite)
where bitingDogs.Any()
select new {Person = p, BitingDogs = bitingDogs.ToList()};
Maybe this code will help.. One of the possible solution are:
var result =
peoples.Where(y => dontRestrainDog.Contains(y.KeepsPetWith) && y.Dogs.Any(x => dogsMayBite.Contains(x.LikesToBite))).ToList();
result.ForEach(y => y.Dogs = y.Dogs.Where(x => dogsMayBite.Contains(x.LikesToBite)).ToList());
which you can see an example of here:
class Program
{
static void Main(string[] args)
{
IList<EnumLikesToBite> dogsMayBite = new List<EnumLikesToBite>
{
{ EnumLikesToBite.Yes }, { EnumLikesToBite.Sometimes }
};
IList<EnumKeepsPetWith> dontRestrainDog = new List<EnumKeepsPetWith>
{
{ EnumKeepsPetWith.String }, { EnumKeepsPetWith.Rubberband }
};
var peoples = new List<People>();
var dogs = new List<Dog>();
Random gen = new Random(2);
for(int i = 0; i < 10; i++)
{
People p = new People
{
PeopleId = i,
KeepsPetWith = (EnumKeepsPetWith) (gen.Next(10)%3),
Dogs = new List<Dog>()
};
Dog d = new Dog
{
DogId = i,
LikesToBite = (EnumLikesToBite) (gen.Next(10)%3),
Peoples = new List<People>()
};
peoples.Add(p);
dogs.Add(d);
}
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
if (gen.Next(10)>7)
{
peoples[i].Dogs.Add(dogs[j]);
}
if (gen.Next(10)>7)
{
dogs[i].Peoples.Add(peoples[j]);
}
}
}
PrintDogs(dogs);
PrintPeoples(peoples);
var result =
peoples.Where(y => dontRestrainDog.Contains(y.KeepsPetWith) && y.Dogs.Any(x => dogsMayBite.Contains(x.LikesToBite))).ToList();
result.ForEach(y => y.Dogs = y.Dogs.Where(x => dogsMayBite.Contains(x.LikesToBite)).ToList());
Console.WriteLine("===================");
PrintPeoples(result);
Console.ReadLine();
}
private static void PrintPeoples(List<People> peoples)
{
Console.WriteLine("=Peoples=");
foreach (var people in peoples)
{
Console.WriteLine("Id: {0}", people.PeopleId);
Console.WriteLine("KeepsPetWith: {0}", people.KeepsPetWith);
Console.WriteLine("Dogs: ");
foreach (var dog in people.Dogs)
{
Console.Write("{0}, ", dog.DogId);
}
Console.WriteLine();
}
}
private static void PrintDogs(List<Dog> dogs)
{
Console.WriteLine("=Dogs=");
foreach (var dog in dogs)
{
Console.WriteLine("Id: {0}", dog.DogId);
Console.WriteLine("LikesToBite: {0}", dog.LikesToBite);
Console.WriteLine("Peoples: ");
foreach (var people in dog.Peoples)
{
Console.Write("{0}, ", people.PeopleId);
}
Console.WriteLine();
}
}
}
public class People
{
public int PeopleId { get; set; }
public EnumKeepsPetWith KeepsPetWith { get; set; }
public IList<Dog> Dogs { get; set; }
}
public class Dog
{
public int DogId { get; set; }
public EnumLikesToBite LikesToBite { get; set; }
public IList<People> Peoples { get; set; }
}
public enum EnumLikesToBite
{
No,
Yes,
Sometimes
}
public enum EnumKeepsPetWith
{
Chain,
String,
Rubberband
}

LinQ distinct with custom comparer leaves duplicates

I've got the following classes:
public class SupplierCategory : IEquatable<SupplierCategory>
{
public string Name { get; set; }
public string Parent { get; set; }
#region IEquatable<SupplierCategory> Members
public bool Equals(SupplierCategory other)
{
return this.Name == other.Name && this.Parent == other.Parent;
}
#endregion
}
public class CategoryPathComparer : IEqualityComparer<List<SupplierCategory>>
{
#region IEqualityComparer<List<SupplierCategory>> Members
public bool Equals(List<SupplierCategory> x, List<SupplierCategory> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(List<SupplierCategory> obj)
{
return obj.GetHashCode();
}
#endregion
}
And i'm using the following linq query:
CategoryPathComparer comparer = new CategoryPathComparer();
List<List<SupplierCategory>> categoryPaths = (from i in infoList
select
new List<SupplierCategory>() {
new SupplierCategory() { Name = i[3] },
new SupplierCategory() { Name = i[4], Parent = i[3] },
new SupplierCategory() { Name = i[5], Parent = i[4] }}).Distinct(comparer).ToList();
But the distinct does not do what I want it to do, as the following code demonstrates:
comp.Equals(categoryPaths[0], categoryPaths[1]); //returns True
Am I using this in a wrong way? why are they not compared as I intend them to?
Edit:
To demonstrate the the comparer does work, the following returns true as it should:
List<SupplierCategory> list1 = new List<SupplierCategory>() {
new SupplierCategory() { Name = "Cat1" },
new SupplierCategory() { Name = "Cat2", Parent = "Cat1" },
new SupplierCategory() { Name = "Cat3", Parent = "Cat2" }
};
List<SupplierCategory> list1 = new List<SupplierCategory>() {
new SupplierCategory() { Name = "Cat1" },
new SupplierCategory() { Name = "Cat2", Parent = "Cat1" },
new SupplierCategory() { Name = "Cat3", Parent = "Cat2" }
};
CategoryPathComparer comp = new CategoryPathComparer();
Console.WriteLine(comp.Equals(list1, list2).ToString());
Your problem is that you didn't implement IEqualityComparer correctly.
When you implement IEqualityComparer<T>, you must implement GetHashCode so that any two equal objects have the same hashcode.
Otherwise, you will get incorrect behavior, as you're seeing here.
You should implement GetHashCode as follows: (courtesy of this answer)
public int GetHashCode(List<SupplierCategory> obj) {
int hash = 17;
foreach(var value in obj)
hash = hash * 23 + obj.GetHashCode();
return hash;
}
You also need to override GetHashCode in SupplierCategory to be consistent. For example:
public override int GetHashCode() {
int hash = 17;
hash = hash * 23 + Name.GetHashCode();
hash = hash * 23 + Parent.GetHashCode();
return hash;
}
Finally, although you don't need to, you should probably override Equals in SupplierCategory and make it call the Equals method you implemented for IEquatable.
Actually, this issue is even covered in documentation:
http://msdn.microsoft.com/en-us/library/bb338049.aspx.

Resources