Finding all possible paths - c#

I have a problem to find all possible paths.
a a a b
b a a a
a b b a
Traveling from starting point at 0,0 to end point at 2,3.
I need to get all possible paths.
Possible moves that I can do are moving down and moving right.
Let me tell you where I am stuck.
I am trying to do with a recursive function . Starting with point at 0,0 and moving towards right whenever I can and moving down only when I must.
My recursive function :
public static move(int i,int j)
{
if(possible(x,y+1))
{
move(x,y+1);
move(x+1,y);
}
}
public static bool possible(int i,int j)
{
if((i >=0 && i<3 ) && (j>=0 && j<4))
return true;
else
return false;
}
Not sure about my recursive move function. Still need to expand it . I am not getting exactly how I should implement .
I am able to traverse upto the corner node using that move method but I need that function to retrace back whenever all possible moves from the corner top right point(0,4) is reached.

You need to stop and take a big step back.
The first step should be coming up with the signature of the method. What is the problem statement?
Find all possible paths
Not mentioned: starting from a particular coordinate.
So the method needs to return a set of paths:
static Set<Path> AllPaths(Coordinate start) { /* a miracle happens */ }
OK, now we're getting somewhere; now it is clear what we need. We need a set of things, and we need a path, and we need coordinates.
What's a coordinate? a pair of integers:
struct Coordinate
{
public int X { get; }
public int Y { get; }
public Coordinate(int x, int y) : this()
{
this.X = x;
this.Y = y;
}
}
Done. So pop the stack; what is a path? A path can be empty, or it can be a first step followed by a path:
sealed class Path
{
private Path() { }
private Path(Coordinate first, Path rest)
{
this.first = first;
this.rest = rest;
}
public static readonly Path Empty = new Path();
private Coordinate first;
private Path rest;
public bool IsEmpty => this == Empty;
public Coordinate First
{
get
{
if (this.IsEmpty) throw new Exception("empty!");
return first;
}
}
public Path Rest
{
get
{
if (this.IsEmpty) throw new Exception("empty!");
return rest;
}
}
public Path Append(Coordinate c) => new Path(c, this);
public IEnumerable<Coordinate> Coordinates()
{
var current = this;
while(!current.IsEmpty)
{
yield return current;
current = current.Rest;
}
}
}
Done.
Now you implement Set<T>. You will need to have the operations "all items" and "union this set with another to produce a third". Make sure that sets are immutable. You don't want to change a set when you add new items to it; you want a different set. The same way you don't change 3 into 4 when you add 1; 3 and 4 are different numbers.
Now you have all the tools you need to actually solve the problem; now you can implement
static Set<Path> AllPaths(Coordinate start)
{
/* a miracle happens */
}
So how does this work? Remember that all recursive functions have the same form:
Solve the trivial case
If we're not in a trivial case, reduce the problem to a smaller case, solve it recursively, and combine solutions.
So what is the trivial case?
static Set<Path> AllPaths(Coordinate start)
{
/* Trivial case: if the start coordinate is at the end already
then the set consists of one empty path. */
Implement that.
And what is the recursive case?
/* Recursive case: if we're not at the end then either we can go
right, go down, or both. Solve the problem recursively for
right and / or down, union the results together, and add the
current coordinate to the top of each path, and return the
resulting set. */
Implement that.
The lessons here are:
Make a list of all the nouns in the problem: set, path, coordinate, and so on.
Make a type that represents each one. Keep it simple, and make sure you implement exactly the operations each type needs.
Now that you have an abstraction implemented for each noun you can start designing algorithms that use the abstractions, with confidence that they will work.
Remember the basic rules of recursion: solve the base case if you can; if not, solve the smaller recursive cases and combine the solutions.

public void MoveUp(Object sender, MoveEventArgs e)
{
if (CanMoveUp(e.CurrentPosition.Y)) ...
}
public void MoveDown(Object sender, MoveEventArgs e)
{
if (CanMoveDown(e.CurrentPosition.Y)) ...
}
public void MoveLeft(Object sender, MoveEventArgs e)
{
if (CanMoveLeft(e.CurrentPosition.X)) ...
}
public void MoveRight(Object sender, MoveEventArgs e)
{
if (CanMoveRight(e.CurrentPosition.X)) ...
}
private bool CanMoveUp(double y) => (y - 1) > 0;
private bool CanMoveDown(double y) => (y + 1) < 4;
private bool CanMoveLeft(double x) => (x - 1) > 0;
private bool CanMoveRight(double x) => (x + 1) < 4;
These Values may not be right, but the code is reusable and easily maintainable in the event you would want to add any other possible barriers to movement you could easily add the additions to each method.

It's hard not to give away the farm and be helpful. You should break down the decision logic to 3 boundary functions
inBoundsX x
// return true if x is in bounds, false otherwise
inBoundsY y
// return true if y is in bounds, false otherwise
inBoundsXY x,y
// return true if x and y are in bounds, false otherwise
Your recursive function should always validate the initial state it's given, then decide which way to move next.
move x,y
if inBoundsXY x,y
print I am here x,y
// use InboundsX, InboundsY to decide next move.

Related

Why does List<T>.Sort() where T:IComparable<T> produce a different order than List<T>.Sort(IComparer<T>)?

List<T>.Sort() where T:IComparable<T> produces a different order than List<T>.Sort(IComparer<T>), with equal inputs.
Note the comparer is not really correct - it does not return 0 for equality.
Both orders are valid (because the difference lies in the equal elements), but I'm wondering where the difference arises from, having looked through the source, and if it is possible to alter the IComparable.CompareTo to match the behavior of the IComparer.Compare when passed into the list.
The reason I'm looking at this is because IComparable is far faster than using an IComparer (which I'm guessing is why there are two different implementations in .NET), and I was hoping to improve the performance of an open source library by switching the IComparer to IComparable.
A full example is at: https://dotnetfiddle.net/b7s6my
Here's the class/comparer:
public class Point : IComparable<Point>
{
public int X { get; }
public int Y { get; }
public int UID { get; set; } //Set by outside code
public Point(int x, int y)
{
X = x;
Y = y;
}
public int CompareTo(Point b)
{
return PointComparer.Default.Compare(this, b);
}
}
public class PointComparer : IComparer<Point>
{
public readonly static PointComparer Default = new PointComparer();
public int Compare(Point a, Point b)
{
if (a.Y == b.Y)
{
return (a.X < b.X) ? -1 : 1;
}
return (a.Y > b.Y) ? -1 : 1;
}
}
Note the comparer is not mine (so I can't really change it) - and changing the sort order causes the surrounding code to fail.
As mentioned in comments problem is with IComparer<Point>, which for two equal objects a and b (ones that have same X and Y) returns Compare(a, b) = 1, and Compare(b, a) = 1.
However, question arose why are the sorts still different.
Checking source of ArraySortHelper (see comment of #Sweeper) showed two versions of quick sort algorithm implementations (one of explicit IComparer and one for implicit).
Algorithms are mostly the same, however, function PickPivotAndPartition is a bit different. One function is PickPivotAndParition(Span<T> keys), another is PickPivotAndPartition(Span<T> keys, Comparison<T> comparer).
In first function there's line:
while (... && GreaterThan(ref pivot, ref leftRef = ref Unsafe.Add(ref leftRef, 1))) ;
And in second function similar line looks like:
while (comparer(keys[++left], pivot) < 0) ;
So, that looks to be a point - first function line can be thought as Compare(pivot, left) > 0, while second line as Compare(left, pivot) < 0, so when you have Compare(left, pivot) = 1 and Compare(pivot, left) = 1, condition in first function will be true, while in second - false.
This means that two algorithm implementations can select different array slices and hence have different output.

How to check whether a collection of ints contains an element within a certain range of another given int?

I'm trying to see if any element in a list of integers is within, say, 0.5 of a given int in either direction.
In the interest of accounting for the XY Problem, the program is for editing Midi files; I'm trying to make it so the end point of any note is not too close to the start point of any other note in the file.
Currently what I have (or rather a simplified representation what I have) is this:
List<Note> notesCache = {...};
List<int> noteStartPointsCache = {...};
static bool CheckForElementWithinRange(int endPoint, float range)
{
foreach (int startPoint in noteStartPointsCache)
{
if (Math.Abs(startPoint - endPoint) < range)
return true;
}
return false;
}
void ProcessAllNotes()
{
foreach (Note note in notesCache)
{
if (CheckForElementWithinRange(note.endPoint, 0.5f))
{
ShortenNote(note);
}
}
}
But this feels quite expensive for a check - especially since the functions used to calculate the ints in my actual code are rather expensive themselves. Is there any more graceful way to do this, or is this as good as it's gonna get?
Only other solution I was thinking of was this:
int val = noteStartPointsCache.First(x => Math.Abs(x - note.endTime) < 0.5);
if (val != null)
ShortenNote();
But the logic is kind of the same as the first method; I don't think it would save me anything in terms of performance.

Validate object/struct without failing

Assume we have a huge list of numeric cartesian coordinates (5;3)(1;-9) etc. To represent a point in oop I created a struct/object (c#):
public struct Point
{
public int X, Y { get; }
public Point(int x, int y)
{
// Check if x,y falls within certain boundaries (ex. -1000, 1000)
}
}
It might be wrong of how I am using struct. I guess normally you would not use a constructor but this is not the point.
Suppose I want to add a list of 1000 points and there is no guarantee that these coordinates fall within boundaries. Simply if the point is not valid, move to the next one without failing and inform user about it. As for object, I would think that Point should be responsible for instantiation and validation by itself but I am not sure how to deal with it in this particular case. Checking x, y beforehand by the caller would be the simplest approach but it does not feel right because caller would have to handle logic that should reside in Point.
What would the most appropriate approach to validate and handle incorrect coordinates without failing and violating SRP?
You can't do this in the constructor; the constructor either runs succesfully or it doesn't. If it doesn't its because an exception is raised, so, so much for silently failing. You could catch exceptions but that woul basically mean you are using exceptions as a control flow mechanism and that is a big no no, don't do that!
One solution similar to what you are thinking is to use a static factory method:
public struct Point
{
public static bool TryCreatePoint(int x, int y, Bounds bounds, out Point point)
{
if (x and y are inside bounds)
{
point = new Point(x, y);
return true;
}
point = default(Point);
return false;
}
//...
}
And the code adding points to the list should act based upon creation success.
Fun fact: if you are using C# 7 the code could look a lot cleaner:
public static (bool Succesful, Point NewPoint) TryCreatePoint(int x, int y, Bounds bounds)
{
if (x and y are inside bounds)
return (true, new Point(x, y));
return (false, default(Point));
}
I can think of three options:
Have the constructor throw an exception that you catch. This is not really great if you are expecting a lot of failures.
Have an IsValid property on the struct that you can use to filter it out once created.
Have the thing loading the data take responsibility for validating the data as well. This would be my preferred option. You say "it does not feel right because caller would have to handle logic that should reside in Point" but I would argue that the responsibility for checking that loaded data is correct is with the thing loading the data, not the data type. You could also have it throw an ArgumentOutOfRangeException in the constructor if the inputs are not valid now that you are no longer expecting anything invalid to be passed as a belt and bracers approach to things.
What you want to do is simply not posible, an instance of a class is either fully created or not at all. If the constructor has been called the only way to not instantiate an instance is by throwing an exception.
So you have these two opportunities to do this:
Extract a method Validate that returns a bool and can be called from the caller of your class.
public struct Point
{
public int X, Y { get; }
public Point(int x, int y)
{
}
}
public bool Validate() { return -1000 <= X && X <= 1000 && -1000 <= Y and Y <= 1000; }
Of course you could do the same using a property.
Throw an exception in the constructor
public Point(int x, int y)
{
if(x > 1000) throw new ArgumentException("Value must be smaller 1000");
// ...
}
However the best solution IMHO is to validate the input before you even think about creating a point, that is check the arguments passed to the constructor beforehand:
if(...)
p = new Point(x, y);
else
...
To be honest, Point shouldn't check boundaries, so the caller should do that. A point is valid in the range that their X and Y can operate (int.MinValue and int.MaxValue). So a -1000000,2000000 is a valid point. The problem is that this point isn't valid for YOUR application, so YOUR application (the caller), the one who is using point, should have that logic, not inside the point constructor.
Structs in C# are funny so I'll add another "funny" way to check:
struct Point
{
int _x;
public int X
{
get { return _x; }
set { _x = value; ForceValidate(); }
} // simple getter & setter for X
int _y;
public int Y
{
get { return _y; }
set { _y = value; ForceValidate(); }
} // simple getter & setter for Y
void ForceValidate()
{
const MAX = 1000;
const MIN = -1000;
if(this.X >= MIN && this.X <= MAX && this.Y >= MIN && this.Y <= MAX)
{
return;
}
this = default(Point); // Yes you can reasign "this" in structs using C#
}
}

Should I use Int32[,] or System.Drawing.Point when all I want is the x,y coordinates?

I am building an app that lets me control my Android devices from my PC. It's running great so now I want to start cleaning up my code for release. I'm trying to clean up solution references that I don't need so I took a look at the using System.Drawing; that I have for implementing the Point class. The thing is, I don't really need it if I switch to using a two-dimensional Int32 array.
So I could have: new Int32[,] {{200, 300}}; instead of new Point(200, 300); and get rid of the System.Drawing namespace altogether. The question is: does it really matter? Am I realistically introducing bloat in my app by keeping the System.Drawing namespace? Is Int32[,] meaningfully more lightweight?
Or, should I not use either and just keep track of the x,y coordinates in individual Int32 variables?
EDIT: I got rid of the original idea I wrote: Int32[200, 300] and replaced it with new Int32[,] {{200, 300}}; because as #Martin Mulder pointed out Int32[200, 300] "creates a two-dimensional array with 60000 integers, all of them are 0."
EDIT2: So I'm dumb. First of all I was trying to fancify too much by using the multi-dimensional array. Utter, overboard silliness. Secondly, I took the advice to use a struct and it all worked flawlessly, so thank you to the first four answers; every one of them was correct. But, after all that, I couldn't end up removing the System.Drawing reference because I was working on a WinForms app and the System.Drawing is being used all over in the designer of the app! I suppose I could further refactor it but I got the size down to 13KB so it's good enough. Thank you all!
Just create your own:
public struct Point : IEquatable<Point>
{
private int _x;
private int _y;
public int X
{
get { return _x; }
set { _x = value; }
}
public int Y
{
get { return _y; }
set { _y = value; }
}
public Point(int x, int y)
{
_x = x;
_y = y;
}
public bool Equals(Point other)
{
return X == other.X && Y == other.Y;
}
public override bool Equals(object other)
{
return other is Point && Equals((Point)other);
}
public int GetHashCode()
{
return unchecked(X * 1021 + Y);
}
}
Better yet, make it immutable (make the fields readonly and remove the setters), though if you'd depended on the mutability of the two options you consider in your question then that'll require more of a change to how you do things. But really, immutability is the way to go here.
You are suggesting very ill advised:.
new Point(200, 300) creates a new point with two integers: The X and Y property with values 200 and 300.
new Int32[200,300] creates a two-dimensional array with 60000 integers, all of them are 0.
(After your edit) new Int32[,] {{200, 300}} also creates a two-dimensional array, this time with 2 integers. To retrieve the first value (200), you can access it like this: array[0,0] and the second value (300) like array[0,1]. The second dimension is not required or needed or desired.
If you want to get rid of the reference to the library there are a few other suggestions:
new Int32[] {200, 300} creates an one-dimensional array of two integers with values 200 and 300. You can access them with array[0] and array[1].
As Ron Beyer suggested, you could use Tuple<int, int>.
Create your own Point-struct (pointed out by Jon Hanna). It makes your applicatie a bit larger, but you prevent the reference and you prevent the library System.Drawing is loaded into memory.
If I wanted to remove that reference, I would go for the last option since it is more clear to what I am doing (a Point is more readable than an Int32-array or Tuple). Solution 2 and 3 are slightly faster that solution 1.
Nothing gets "embedded" in your application by just referencing a library. However, if the Point class really is all you need, you could just remove the reference and implement you own Point struct. That may be more intuitive to read instead of an int array.
Int32[,] is something different by the way. It's a two-dimensional array, not a pair of two int values. You'll be making things worse by using that.
You could use Tuple<int, int>, but I'd go for creating your own structure.
As some people have suggested implementations here. So just wrap your two integers, I'd just use this:
public class MyPoint
{
public int X;
public int Y;
}
Add all other features only if needed.
As #Glorin Oakenfoot said, you should implement your own Point class. Here's an example:
public class MyPoint // Give it a unique name to avoid collisions
{
public int X { get; set; }
public int Y { get; set; }
public MyPoint() {} // Default constructor allows you to use object initialization.
public MyPoint(int x, int y) { X = x, Y = y }
}

C# dynamic logic gate

I am working on a program that would allow the user to build digital circuits from virtual logic gates. Every gate would be an instance of a class that represents particular gate type, for example here's how AND class looks:
public class andgate
{
public andgate()
{
inputs = new bool[7];
for (int i = 0; i < 7; i++) inputs[i] = true;
output = (inputs[0] && inputs[1] && inputs[2] && inputs[3] && inputs[4] && inputs[5] && inputs[6]);
}
public bool[] inputs;
public bool output;
}
Every gate has seven inputs but not all of them have to be used (i.e. for a gate with three imputs the remaining four will just be "1" which is AND's neutral element anyway). Each input is a reference to an output of another gate or to an element of bool array (which stores the input vector) so that signal generated by one gate automatically is sent to the following gate. The problem is I also need the signal to be transmitted dynamically within the gate, i.e. if one of the input signals in AND gate is set to 0 then the output automatically has a 0 value. Therefore when you feed a binary vector to the inputs of the cirtuit, it changes the values of the circuit's outputs. Or maybe there's an easier way to simulate a circuit than building it from individual gates? I need it for test pattern generating.
Make the output property read-only:
public bool output
{
get
{
return inputs.All(i => i);
}
}
Instead of ANDing all the inputs, just check if there is any input that is false.
Of course you have to remove the assignment to output in the constructor. This should make your output property "dynamic".
You may also want to change the inputs to bool?[] instead, so that a null value would signify that there is no signal. You will then have to remove the initialization of the input array to all true and change the output return to:
return inputs.All(i => i.GetValueOrDefault(true));
Edited with Tim S's suggestions in the comments
For this, you should use a properties to set/get the inputs, as you can perform additional computations in a property. The state variables you're holding should be private.
public bool[] Inputs {
set {
inputs = value;
}
}
public bool Output {
get {
return inputs[0] && inputs[1] ...
}
}
I would avoid doing this for the Inputs property, since exposing arrays is really exposing information about how the class stores things, which should be avoided where possible for good OOP. A ReadOnlyCollection might be more suitable, for example.
However, I would rethink the design in general, and avoid having some arbitrary # of inputs, 7. Where have you conjured that value from?
A more simplistic approach would be to assume that a gate takes 2 values - A and B, for which you can set the values in the constructor or individual properties.
You then take advantage of the fact that operations on binary logic gates are associative, so an AND gate taking a, b, c, is equivalent to one taking a, b, feeding it's output to another which also takes c. This is how you'd build a circuit in practice anyway - the issue you need to consider is the latency of the gate though.
It sounds like you should add events into your gates, such that when their state changes they're able to notify dependant objects; something like this:
public class AndGate
{
private bool[] inputs;
private bool output;
public bool[] Inputs
{
get
{
return this.inputs;
}
set
{
this.inputs = value;
UpdateOutput();
}
}
public bool Output
{
get
{
return this.output;
}
}
public AndGate()
{
inputs = new bool[7];
for (int i = 0; i < 7; i++) inputs[i] = true;
UpdateOutput();
}
private void UpdateOutput()
{
bool original = output;
output = true;
for(int i=0; i<inputs.Length; i++)
{
output = output && inputs[i];
}
if (original != output)
{
OnChanged(EventArgs.Empty);
}
}
public event GateStateChangedEventHandler StateChanged;
protected virtual void OnChanged(EventArgs e)
{
if (StateChanged != null)
{
StateChanged(this, e);
}
}
}

Categories