popcorn
popcorn
CC#
Created by popcorn on 3/18/2024 in #help
Delegate function with params
Hello, is it possible to somehow have "named" parameters in the delegate function? Right now I have:
public delegate bool ValidatorF<T>(params T[] args);

// Usage
public static class IntValidator
{
public static ValidatorF<int> IsExact = args => args[0] == args[1];
}
public delegate bool ValidatorF<T>(params T[] args);

// Usage
public static class IntValidator
{
public static ValidatorF<int> IsExact = args => args[0] == args[1];
}
But that way you have to remember that the first argument is the actual number and the second argument is the expected value for example (In this case it doesn't matter, but let's say we have 3+ args..) My question is: Is it possible to have the usage like this somehow? Or using some other approach?
public static ValidatorF<int> IsExact = (val, expected)=> val == expected;
public static ValidatorF<int> IsExact = (val, expected)=> val == expected;
21 replies
CC#
Created by popcorn on 3/18/2024 in #help
Fluent Syntax - generic methods
Hi, I have a structure as follows:
public abstract class Control { }

public sealed class Image : Control {
public Image WithUrl(string url) { Url = url; return this; }
public Image WithZoomFactor(float zoomFactor) { ZoomFactor = zoomFactor; return this; }
}

public sealed class Label : Control {
public Label WithText(string text) { Text = text; return this; }
}

public class StackPanel: Control {
public void AddChild(Control control) { }
}

public class Canvas: Control {
public void AddChild(Control control, Point point) { }
}
public abstract class Control { }

public sealed class Image : Control {
public Image WithUrl(string url) { Url = url; return this; }
public Image WithZoomFactor(float zoomFactor) { ZoomFactor = zoomFactor; return this; }
}

public sealed class Label : Control {
public Label WithText(string text) { Text = text; return this; }
}

public class StackPanel: Control {
public void AddChild(Control control) { }
}

public class Canvas: Control {
public void AddChild(Control control, Point point) { }
}
and I want to be able to do :
new Image()
.WithZoomFactor(0.75f)
.PlacedIn(canvas1).At(0, 0)
.WithUrl("flower2.jpg");

new Image()
.WithZoomFactor(0.75f)
.PlacedIn(stackPanel2)
.WithUrl("flower1.jpg");

new Label()
.WithText("Dandelion (lat. Taraxacum officinale)")
.PlacedIn(canvas2).At(50, 200);

// This should not compile - PlaceIn() is in canvas and is not followed by .At()..
// new Image().PlacedIn(canvas2).WithUrl("flower2.jpg");
new Image()
.WithZoomFactor(0.75f)
.PlacedIn(canvas1).At(0, 0)
.WithUrl("flower2.jpg");

new Image()
.WithZoomFactor(0.75f)
.PlacedIn(stackPanel2)
.WithUrl("flower1.jpg");

new Label()
.WithText("Dandelion (lat. Taraxacum officinale)")
.PlacedIn(canvas2).At(50, 200);

// This should not compile - PlaceIn() is in canvas and is not followed by .At()..
// new Image().PlacedIn(canvas2).WithUrl("flower2.jpg");
So the rule is that the method .PlacedIn(canvas) must be either last to be called or must be followed by .At(). And .PlacedIn(stackPanel) can be anywhere and followed by any method. The second problem I solved quite easily by:
public static T PlacedIn<T>(this T control, StackPanel stackPanel) where T : Control {
return control;
}
public static T PlacedIn<T>(this T control, StackPanel stackPanel) where T : Control {
return control;
}
But I'm not sure about the .PlacedIn(canvas). I think it should return some other type than the generic T where : Control but then the information about the type is lost and I don't know how to return the proper type (Label, Image, ...) In the .At() method afterwards. How can I do this?
29 replies
CC#
Created by popcorn on 11/6/2023 in #help
❔ query all items that match both properties.
I have a list of tuples as:
List<Tuple<int, string>> desiredValues = new List<Tuple<int, string>>() {};

desiredValues.Add(new Tuple(5, "abc"));
desiredValues.Add(new Tuple(8, "xyz"));
desiredValues.Add(new Tuple(10, "hjk"));


class MyCollectionItem {
public int Score {get; set;}
public string PlayerName {get; set;}
}
List<Tuple<int, string>> desiredValues = new List<Tuple<int, string>>() {};

desiredValues.Add(new Tuple(5, "abc"));
desiredValues.Add(new Tuple(8, "xyz"));
desiredValues.Add(new Tuple(10, "hjk"));


class MyCollectionItem {
public int Score {get; set;}
public string PlayerName {get; set;}
}
And I want to retrieve all items that match the int to score and string to PlayerName. How can I do that using LINQ? I don't want all the possible combinations of pair values.
19 replies
CC#
Created by popcorn on 8/8/2023 in #help
❔ Find values which are not present in hashsets
I have multiple hashsets of integers and one "main". I want to find all values from "main" hashset which are not present in some of the other hashets, what's the easiest/best way to do this? a) Combine all the other hashsets into one and then do like
HashSet<int> mainH;
HashSet<int> combinedOther

mainH.ExceptWith(combinedOther);
HashSet<int> mainH;
HashSet<int> combinedOther

mainH.ExceptWith(combinedOther);
b) Do it one by one c) Some other way?
3 replies
CC#
Created by popcorn on 7/20/2023 in #help
Full outer join two different structures - LINQ
Hello, is it possible to do following?
class Item
{
public DateTime Date {get; set;}
public decimal Price {get; set;}
public string Name {get; set;}
}

class Request
{
public DateTime Date {get; set;}
public decimal PayedAmount {get; set;}
}

class MergedItem
{
public DateTime Date {get; set;}
public decimal Price {get; set;}
public string Name {get; set;}
public decimal PayedAmount {get; set;}
}

List<Item> items;
List<Request> requests;
// How can I do something like
var final = items.UnionOnKey(requests, "Date").Select(x => new MergedItem()
{
Date = x.item != null ? x.item.Date : x.request.Date,
Price = x.item ? x.item.Price : 0m,
Name = x.item ? x.item.Name : "",
PayedAmount x.request ? x.request.PayedAmount : 0m
});
class Item
{
public DateTime Date {get; set;}
public decimal Price {get; set;}
public string Name {get; set;}
}

class Request
{
public DateTime Date {get; set;}
public decimal PayedAmount {get; set;}
}

class MergedItem
{
public DateTime Date {get; set;}
public decimal Price {get; set;}
public string Name {get; set;}
public decimal PayedAmount {get; set;}
}

List<Item> items;
List<Request> requests;
// How can I do something like
var final = items.UnionOnKey(requests, "Date").Select(x => new MergedItem()
{
Date = x.item != null ? x.item.Date : x.request.Date,
Price = x.item ? x.item.Price : 0m,
Name = x.item ? x.item.Name : "",
PayedAmount x.request ? x.request.PayedAmount : 0m
});
I simply need to include both a and b if the other one is null as well as match the two together
2 replies
CC#
Created by popcorn on 7/19/2023 in #help
❔ Anonymous function in LINQ Select
I have a code as following:
class Item {
int price {get;set;}
}

bool showMax;
bool showMin;

if (showMax)
var myLinqQuery = queryGroup.Select(x => new Item(price= x.Max(y => y.Price), otherFields...));
else if (showMin)
var myLinqQuery = queryGroup.Select(x => new Item(price= x.Min(y => y.Price), otherFields...));
else
var myLinqQuery = queryGroup.Select(x => new Item(price= x.Average(y => y.Price), otherFields...));
class Item {
int price {get;set;}
}

bool showMax;
bool showMin;

if (showMax)
var myLinqQuery = queryGroup.Select(x => new Item(price= x.Max(y => y.Price), otherFields...));
else if (showMin)
var myLinqQuery = queryGroup.Select(x => new Item(price= x.Min(y => y.Price), otherFields...));
else
var myLinqQuery = queryGroup.Select(x => new Item(price= x.Average(y => y.Price), otherFields...));
Is there a way to somehow pass just the LINQ Max/Min/Average function so I don't have to repeat the rest?
22 replies
CC#
Created by popcorn on 5/18/2023 in #help
✅ abstract class - default value
Hello, I have a simple code:
public abstract class Vehicle
{
public int speed = 1;

public void PrintSpeed()
{
Console.WriteLine(speed);
}
}

public class Car : Vehicle
{
public int speed = 9;

public void DoSomething()
{
// ....
PrintSpeed(); // Here it prints 1, but I want it to print 9
}
}
public abstract class Vehicle
{
public int speed = 1;

public void PrintSpeed()
{
Console.WriteLine(speed);
}
}

public class Car : Vehicle
{
public int speed = 9;

public void DoSomething()
{
// ....
PrintSpeed(); // Here it prints 1, but I want it to print 9
}
}
Is it possible to have an abstract class hold default parameter but when I override that then when I call the function it will use the overridden parameter in the child class?
7 replies
CC#
Created by popcorn on 4/1/2023 in #help
❔ Dynamic programming
Hello, I have a task, where I need to find the least keystrokes required to print a word. I have a table sized X*Y filled with letters that can repeat and I have a string s that can contain letters which are not in the table and should be skipped. We cannot move diagonally in the table. We always start at the left top corner. How do I solve this using dynamic programming? I have created a Dict where each letter gets List of positions it is in the table. But then I don't know how to look ahead. Let's say we have table:
ABC
BFE
CDF
ABC
BFE
CDF
and string = ABCDEFA Then when choosing F from E, how do I choose the middle one because it is closer to the next character (A) and not the right lower F
12 replies
CC#
Created by popcorn on 3/1/2023 in #help
✅ Why is my bfs so slow?
private const int BOARD_SIZE = 8;
private static readonly List<Point> KING_MOVES = new List<Point>() { new Point(-1, 0), new Point(-1, 1), new Point(0, 1), new Point(1, 1), new Point(1, 0), new Point(1, -1), new Point(0, -1), new Point(-1, -1) };

class Point
{
public int x;
public int y;

public Point(int x, int y)
{
this.x = x;
this.y = y;
}

public Point(Point p)
{
this.x = p.x;
this.y = p.y;
}

public override bool Equals(object? obj)
{
Point p = obj as Point;
return this.x == p.x && this.y == p.y;
}

public void Add(Point p)
{
this.x = this.x + p.x;
this.y = this.y + p.y;
}
}

static bool PointInBounds(Point p)
{
if (p.x < 1 || p.y < 1)
{
return false;
}

if (p.x > BOARD_SIZE || p.y > BOARD_SIZE)
{
return false;
}
return true;
}
private const int BOARD_SIZE = 8;
private static readonly List<Point> KING_MOVES = new List<Point>() { new Point(-1, 0), new Point(-1, 1), new Point(0, 1), new Point(1, 1), new Point(1, 0), new Point(1, -1), new Point(0, -1), new Point(-1, -1) };

class Point
{
public int x;
public int y;

public Point(int x, int y)
{
this.x = x;
this.y = y;
}

public Point(Point p)
{
this.x = p.x;
this.y = p.y;
}

public override bool Equals(object? obj)
{
Point p = obj as Point;
return this.x == p.x && this.y == p.y;
}

public void Add(Point p)
{
this.x = this.x + p.x;
this.y = this.y + p.y;
}
}

static bool PointInBounds(Point p)
{
if (p.x < 1 || p.y < 1)
{
return false;
}

if (p.x > BOARD_SIZE || p.y > BOARD_SIZE)
{
return false;
}
return true;
}
Here are my "support" classes and method
26 replies
CC#
Created by popcorn on 12/30/2022 in #help
❔ Which algorithm should I use, CP
Hi, I have a task:
Find maximum possible reward and number of eliminated opponents each round after k rounds, when you have 100 opponents and you have to eliminate at least 1 in each round. The reward for eliminating opponents is 100.000 * (e / c).
Where e is number of opponents that are being eliminated in the round
c is number of remaining opponents.
Find maximum possible reward and number of eliminated opponents each round after k rounds, when you have 100 opponents and you have to eliminate at least 1 in each round. The reward for eliminating opponents is 100.000 * (e / c).
Where e is number of opponents that are being eliminated in the round
c is number of remaining opponents.
What algorithm should I use?
8 replies
CC#
Created by popcorn on 10/23/2022 in #help
Keep Model instances without RelatedModel in query
Hi, how do I keep records that do not have related model value in my query? I have a query like:
var rows = context.MyModel.
Select(x => new
{
Field1 = MyModel.Field1,
RelatedField1 = MyModel.RelatedModel.RelatedField1
})
var rows = context.MyModel.
Select(x => new
{
Field1 = MyModel.Field1,
RelatedField1 = MyModel.RelatedModel.RelatedField1
})
And all MyModel instances that do not have the RelatedModel will be excluded in that query. How can I include them and just let the value be null?
1 replies