declare object in c# with x,y paramateres [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to create object "A" which will have x, y parameters.
and A must be an array. What's best practice of declaring and constructing such object ? for example something like this:
A[0].x=5
A[0].y=3
A[1].x=6
A[1].y=4
Update
I've done this way:
public class PersonalWaypoints
{
public float x { get; set; }
public float y { get; set; }
}
public class MainClass:MonoBehaviour
{
then in void Start() {
PersonalWaypoints[] pw = new PersonalWaypoints[waypoints.Length];
pw[0].x = waypoints[0].transform.position.x ;
pw[0].y = waypoints[0].transform.position.y ;
but then I cannot use pw in Update() { because it doesn't exist in current context.
And to have it in context I cannot move PersonalWaypoints[] pw = new PersonalWaypoints[waypoints.Length]; to class definition because waypoints.Length is unknown while defining class.

You question is a bit vague, if you want autoexpanding array-like collection you have to have two objects: one for point
//TODO: think over, may be you want a struct, not class
// May be you want just a standard Point struct
public class Item {
public int x {get; set;}
public int y {get; set;}
}
and one for "array" (which is an indexer in fact)
//TODO: you may want to implement IEnumerable<Item>
public class MyClass {
private List<Item> m_Items = new List<Item>();
private void Expand(int index) {
if (index < 0)
throw new ArgumentOutOfRangeException("index");
for (int i = m_Items.Count; i <= index; ++i)
m_Items.Add(new Item());
}
// indexer: mimics auto expanding array
public Item this[int index] {
get {
Expand(index);
return m_Items[index];
}
}
public int Count {
get {
return m_Items.Count;
}
}
}
...
MyClass test = new MyClass();
// test will be expanded to have 1 item: test[0]
test[0].y = 456;
// test will be expanded to have 6 items [0..5]
test[5].x = 123;

Define a Point type which has your fields:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
Then create an array of Points (or a List<Point>):
var A = new[] {
new Point { X = 5, Y = 3 },
new Point { X = 6, Y = 4 }
};
You can, of course, get there from values for x and y which are not hard-coded into the object creation. For example, say that you have a list xs with integers that should be the x coordinates, and a simliar (and of equal length!) list ys wity y-values. Then, you'll get a list of Points from
var points = xs.Zip(ys, (x,y) => new Point { X = x, Y = y });
Then access the coordinates just the way you wanted: points[1].x is the x-coordinate of the second point.

You can create a class with your parameters for it and then create an Array or List of the class:
public class _A
{
public int x;
public int y;
}
_A[] A;
Or
List<_A> = new List<_A>();

public class A
{
int x;
int y;
}
A[] numbers = new A[10];

sealed class A {
readonly int m_x;
readonly int m_y;
internal A(int x, int y) {
m_x = x;
m_y = y;
}
internal int X {
get {
return m_x;
}
}
internal int Y {
get {
return m_y;
}
}
}
And then to get array of objects:
var myVar = new A[1]; // Array size between []

First you must make a class Coordinate
class Coordinate{
public int x;
public int y;
public Coordinate(int x, int y){
this.x=x;
this.y=y;
}
After that you create an array of Coordinates
Coordinate[]A=new Coordinate[10];
A[0]=new Coordinate(0,0);
A[1]=new Coordinate(5,4);

Related

Linking instances of two classes together

Programming newbie here and I've been breaking my head over this for several hours now.
I can make a coordinate object but then I want to make a dot object that can access the coordinate fields from a Coordinate object. How do I "link" these two classes together? And do you have any recommendations for good YouTube videos that explain what I'm missing here? Thanks!
class Coordinate
{
public int X { get; private set; } = 0;
public int Y { get; private set; } = 0;
public Coordinate(int x, int y)
{
x = X;
y = Y;
}
}
class Dot
{
public string color { get; set; }
public Dot(string color, Dot dot)
{
this.Color = color;
}
}
class Program
{
static void Main(string[] args)
{
Coordinate coor1 = new Coordinate(2, 3);
Dot dot1 = new Dot("Blue", coor1);
}
Here is what you are searching for a "linking" your classes. In object-oriented programming this is called composition.
That way you can use functionality and data of Coordinate-instance inside your Dot class.
class Coordinate
{
public int X { get; private set; }
public int Y { get; private set; }
public Coordinate(int x, int y)
{
X = x;
Y = y;
}
}
class Dot
{
public Coordinate coord { get; private set; }
public string color { get; set; }
public Dot(string color, Coordinate coord)
{
this.color = color;
this.coord = coord;
}
}
class Program
{
static void Main(string[] args)
{
Coordinate coor1 = new Coordinate(2, 3);
Dot dot1 = new Dot("Blue", coor1);
Console.WriteLine(dot1.coord.X);
}
}
Note: I also fixed possible typo in Coordinate-constructor (setting X=x and Y=y..)

Data Structure like a Dictionary returns a string when point is in a range

I have an SQL Query which returns the following table with 3 columns:
I am searching a data structure, in which I can store the table, that delivers me back the phasename when the dot is between.
I.e. 300 returns Project Management, 360 returns Controlling.
"Project Management"=givePhaseNameFor (300);
"Controlling"=givePhaseNameFor (360);
In SQL I would write
WHERE point IS BETWEEN y1 AND y2
public string givePhaseNameFor(int point)
{
return "Project Management
}
Is there a data structure (like a Dictionary) for this?
No there is not, but you could use something like this:
public class RangeList<T>
{
private List<T> list = new List<T>();
public abstract int GetLower(T item);
public abstract int GetUpper(T item);
public T this[int index]
{
get
{
return list.SingleOrDefault(x => index >= GetLower(x) && index <= GetUpper(x));
}
}
public void Add(T item)
{
if (list.Any(x => GetUpper(item) >= GetLower(x) && GetLower(item) <= GetUpper(x)))
throw new Exception("Attempt to add item with overlapping range");
}
}
public class Phase
{
public int y1;
public int y2;
public string phasename;
}
public class PhaseList : RangeList<Phase>
{
public override int GetLower(Phase item)
{
return item.y1;
}
public override int GetUpper(Phase item)
{
return item.y1;
}
}
Usage:
PhaseList phaseList = GetPhaseListFromDB();
return phaseList[300]?.phasename;
EDIT: An alternate to this would be to create an interface that classes useable in a 'RangeList' must implement. This will mean you don't need a separate inherited list class for each type you want to use.
public interface IRangeable
{
int Lower { get; }
int Upper { get; }
}
public class Phase : IRangeable
{
public int y1;
public int y2;
public string phasename;
int IRangeable.Lower => y1;
int IRangeable.Upper => y2;
}
public class RangeList<T> where T : IRangeable
{
private List<T> list = new List<T>();
public T this[int index]
{
get
{
return list.SingleOrDefault(x => index >= ((IRangeable)x).Lower && index <= ((IRangeable)x).Upper);
}
}
public void Add(T item)
{
if (list.Any(x => ((IRangeable)item).Higher >= ((IRangeable)x).Lower && ((IRangeable)item).Lower <= ((IRangeable)x).Upper))
throw new Exception("Attempt to add item with overlapping range");
}
}
Usage:
RangeList<Phase> phaseList = GetPhaseListFromDB();
return phaseList[300]?.phasename;
class Row
{
public Y1 {get;set;}
public Y2 {get;set;}
public Name {get;set;}
}
var list = new List<Row>();
//fill list
var result = list.Where(o => o.Y1 <= x && x < o.Y2).First();
if you want speed, I would make two arrays:
One containing the start ranges
Another containing the names
Then you would first populate the arrays:
int nbRanges = //Get this info from the number of rows in you table
int[] range = new int[nbRanges];
string[] rangeNames = new string[nbRanges];
for (int i = 0; i < nbRanges; i++)
{
range[i] = //Table.y1;
rangeNames[i] = //Table.phasename;
}
After that, to look for the name is straightforward :
public string givePhaseNameFor(int point)
{
int index = 0;
while (index + 1 < nbRanges)
{
if (point <= range[index + 1])
{
//This means that your point is in the current range
break;
}
else
{
index++; //The point is not in this range
}
}
//If we exit without having it found, index == nbRanges and we return the last value
return rangeNames[index];
}

C# Poker How to check if players have different hands

I'm developing a Poker Texas Hold'Em app I have all the combinations working but i cant seem to find a compact way to check which player has the highest combination and the type of it here's some of my code
void Rules(int current,int Power)
{
//checking if the player has any pair
{
Power = 1;
current = 1;
}
}
current = the type of the hand (pair=1,two pair =2..straight flush=8)
Power = the power of the hand (pair of deuces=2....pair of kings=13)
and so on.. I'm updating current and Power with each new combination and since they are parameters of the void each player has his own "current" and "Power" so they don't get messed up.This is what i have so far and my question is how do i check which player has the highest hand without using 20-30 repetitive if statements i was thinking about :
List <int> Arr = new List <int>();
void Rules(int current,int Power)
{
//checking if the player has any pair
{
Power = 1;
current = 1;
Arr.Add(Power);
Arr.Add(current);
}
}
but like this i have no idea which type belongs to which player so it's not use i also tried with strings but than i wont be able to compare them that easily.What should i do ? What's the right approach ?
You might want to make a class for reach rule, to encapsulate the logic. Something like this:
public class Card
{
public string Name { get; private set; }
/* cards have a value of 2-14 */
public int Value { get; private set; }
}
public abstract class Rule()
{
public abstract string Name { get; }
/* hands are calculated in powers of 100, when the card value is added you will get something like 335 */
public abstract int Value { get; }
public abstract bool HasHand(IReadonlyList<Card> cards);
}
public class PairRule() : Rule
{
public override string Name
{
get { return "Pair"; }
}
public override int Value
{
get { return 100; }
}
public override bool HasHand(IReadonlyList<Card> cards)
{
/* implement rule here */
return Enumerable.Any(
from x in cards
group x by x.Value into g
where g.Count() == 2
select g
);
}
}
...
public class Player
{
public IReadonlyList<Card> Hand { get; private set; }
public int GetHandValue(IReadonlyList<Rule> rules)
{
/* get value of hand 100, 200, 300 etc. */
var handValue = Enumerable.Max(
from x in rules
where x.HasHand(Hand)
select x.Value
);
/* get value of cards */
var cardValue = Hand
.OrderByDescending(x => x.Value)
.Take(5)
.Sum();
return handValue + cardValue;
}
}
public class Pot
{
public int Value { get; private set; }
public IReadonlyList<Player> Players { get; private set; }
public IReadonlyList<Player> GetWinners(IReadonlyList<Rule> rules)
{
var playerHands = Enumerable.ToList(
from x in players
select new {
Player = x,
HandValue = x.GetHandValue(rules)
}
);
var maxHand = playerHands.Max(x => x.HandValue);
return Enumerable.ToList(
from x in playerHands
where x.HandValue == maxHand
select x.Player
);
}
}

Covariant Collection not working

Sorry if the question is redundant, but I couldn't find a solution for my particular case.
Please consider this block of code:
public interface IPoint {}
public class GazePoint : IPoint {}
public Point AvgPoint(IEnumerable<IPoint> locations) {}
List<GazePoint> gazePoints = new List<GazePoint>();
//...
// this doesn't work:
Point avg = AvgPoint(gazePoints);
Could you please explain why it doesn't work (I was assuming C# 4.0 has solved this issue) and how can I change the signature of AvgPoint() method to make it possible to receive different implementations of IPoint. (I don't want to cast gazePoints collection to another type of collection, because it is in a big loop, and I'm concern about the performance.
[Update]: I had defined GazePoint as struct, and that was the source of problem. Still, I don't know why struct is not working here.
I'm not sure what the exact problem is you're having, but here's how it worked for me:
First, some actual class implementations:
public interface IPoint
{
int X { get; set; }
int Y { get; set; }
}
public class Point : IPoint
{
public int X { get; set; }
public int Y { get; set; }
public Point()
{
}
public Point(int x, int y)
{
X = x;
Y = y;
}
}
public class GazePoint : IPoint
{
public int X { get; set; }
public int Y { get; set; }
public GazePoint()
{
}
public GazePoint(int x, int y)
{
X = x;
Y = y;
}
}
Then an actual AvgPoint method implementation:
public static Point AvgPoint(IEnumerable<IPoint> locations)
{
if (locations == null || !locations.Any()) return new Point(0, 0);
return new Point((int) locations.Average(l => l.X),
(int) locations.Average(l => l.Y));
}
And finally a few tests:
public static void Main()
{
var points = new List<Point>
{
new Point(1, 2),
new Point(3, 4)
};
var gazePoints = new List<GazePoint>
{
new GazePoint(1, 2),
new GazePoint(3, 4)
};
Point avgPoint = AvgPoint(points);
Point avgGazePoint = AvgPoint(gazePoints);
Console.WriteLine("Average Point = {0}, {1}", avgPoint.X, avgPoint.Y);
Console.WriteLine("Average GazePoint = {0}, {1}", avgGazePoint.X, avgGazePoint.Y);
}
If your goal is to have the method return the average in the same type that was passed in, you can make it generic like so:
public static T AvgPoint<T>(IEnumerable<T> locations) where T : IPoint, new()
{
if (locations == null || !locations.Any()) return new T {X = 0, Y = 0};
return new T {X = (int) locations.Average(l => l.X),
Y = (int) locations.Average(l => l.Y)};
}

Get the index in a multidimensional class

Sorry for the title i will put here an example of what i want to accomplish:
namespace mdclass
{
class pClass
{
static void Main()
{
tiles<int> tl = new tiles<int>();
tl[0].X = 0;
}
}
class tiles<T> : List<T>
{
public int X
{
//get/set the X-coordonate
}
public int Y
{
//get/set the Y-coordonate
}
}
}
how can i transfer the [0] from the tl[0] in the public int X and work with it?
Create a class for x and y coordinates:
public sealed class Point {
public int X { get; set; }
public int Y { get; set; }
}
Use the Point class to store the coordinates into the list:
public sealed class Program {
public static void Main() {
var tiles = new List<Point>();
tiles.Add(new Point { X = 5, Y = 10 });
tiles[0].X = 15;
}
}
Could you not just make tl public?
Then myInt = mypClass.tl[0].X
A data heirachy like this might work for you (no time to add actual code, sorry!). Then you could implement appropriate getters and setters.
Public class Grid {
List<Row>
}
Public class Row{
List<Point>
}
Public Class Point{
public int X { get; set; }
public int Y { get; set; }
}

Categories

Resources