C# dynamic logic gate - c#

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);
}
}
}

Related

TopCoder Alogirithm System Test Failure

I am doing a problem from Top-Coder.The problem statement is-
One day, Jamie noticed that many English words only use the letters A
and B. Examples of such words include "AB" (short for abdominal),
"BAA" (the noise a sheep makes), "AA" (a type of lava), and "ABBA" (a
Swedish pop sensation).
Inspired by this observation, Jamie created a simple game. You are
given two Strings: initial and target. The goal of the game is to find
a sequence of valid moves that will change initial into target. There
are two types of valid moves:
Add the letter A to the end of the string. Reverse the string and then
add the letter B to the end of the string. Return "Possible" (quotes
for clarity) if there is a sequence of valid moves that will change
initial into target. Otherwise, return "Impossible".
Below is my solution of the problem which passed all the tests in the Panel but failed in system test.But,I did not get any specific information about which test case failed.Please check if my code will not work in some scenario.
class ABBA
{
public string canObtain(string initial,string target)
{
string s = "Impossible";
if (initial.Length > target.Length)
return "Impossible";
if (initial.Equals(target))
return "Possible";
if (CheckFirstWay(target,initial))
{
s=canObtain(initial+"A",target);
}
if (s.Equals("Impossible") && CheckSecondWay(target,initial))
{
s=canObtain(ReverseStringDirect(initial) + "B",target);
}
return s;
}
public static string ReverseStringDirect(string s)
{
char[] array = new char[s.Length];
int forward = 0;
for (int i = s.Length - 1; i >= 0; i--)
{
array[forward++] = s[i];
}
return new string(array);
}
private static bool CheckSecondWay(string final, string initial)
{
if (final.Contains(ReverseStringDirect(initial) + "B") || final.Contains("B"+initial))
{
return true;
}
else
{
return false;
}
}
private static bool CheckFirstWay(string final1, string initial)
{
if (final1.Contains(initial + "A") || final1.Contains(ReverseStringDirect(initial+"A")))
{
return true;
}
else
{
return false;
}
}
}
You can check on which test failed by following procedure,
Go to the specified room.
Open the problem.
Compile.
Submit it.
Then go to run system test.
you will see the error test there.
OR
Select the match from here.
Then in the page as shown you will see set of blue coders and red coders who topped the match.
Select any one player as per your division. [.] --> this logo beside name.
Then check their solution you will see those tests.
Here are the test cases..check it out.
You have to type system tests here. You can check the image below. Image credit : Google

Finding all possible paths

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.

Multiple objects with same hash code in a C# HashSet?

I'm using a Syncfusion grid control's selections to get a list of our data objects. When we multi-select objects, for some reason the objects are being double reported. The below code returns one entry for a single selection, four (!) for two selected objects, six (!) for three, etc.
There seems to be a minor bug in the selection code that is causing a multi-selection to be reported twice in this.BaseGridControl.Model.Selections. Yes, the bug should be fixed. But for now, I can work around that; since the objects these rows represent are going into a HashSet anyway, they should be deduplicated there.
HashSet<Bean> selectedBeanSet = new HashSet<Bean>();
for (int i = this.BaseGridControl.Model.Selections.Count - 1; i >= 0; i--) {
selection = this.BaseGridControl.Model.Selections.Ranges[i];
topRow = selection.Top;
bottomRow = selection.Bottom;
for (int j = bottomRow; j >= topRow; j--) {
selectedBeanSet.Add(GetObjectAtRow(j));
}
}
But even after doing this, I still have four rows when there should only be two. Interrogating in the immediate window, I can learn a little about what's there:
selectedBeanSet.Take(4).ToList()[3].GetHashCode()
5177447
selectedBeanSet.Take(4).ToList()[1].GetHashCode()
5177447
These are still the same object! I wrote the .GetHashCode() myself — I know it's referring to properties of Bean and not any kind of reference.
And in case there was any doubt:
selectedBeanSet.GetType().Name
"HashSet`1"
How can the same object be in a HashSet twice? Is the .GetHashCode() I'm calling in the immediate window not the one being used as a key in the HashSet? What's going on here?
EDIT: Here's my .GetHashCode() implementation. I've put a breakpoint in here and stepped through so I know it's getting hit.
public override int GetHashCode() {
return this.Property1.GetHashCode() ^ this.Property2.GetHashCode() ^ this.Property3.GetHashCode();
}
And .Equals():
public override bool Equals(Bean other) {
return this.Property1 == other.Property1 && this.Property2 == other.Property2 && this.Property3 == other.Property3;
}
EDIT 2: The Bean class, sanitized for public consumption. It's a bit strange since for persistence reasons we're storing everything in structs behind the scenes. I believe that fact is immaterial to this problem, however.
public class Bean : AbstractBean<Bean, BeanStruct> {
BeanStruct myStruct;
public int Property1 {
get {
return this.myStruct.property1;
}
set {
this.myStruct.property1 = value;
RaisePropertyChanged("Property1");
}
}
public string Property2 {
get {
return this.myStruct.property2;
}
set {
this.myStruct.property2 = EngineUtils.FillOrTruncate(value, Bean.Length);
RaisePropertyChanged("Property2");
}
}
public string Property3 {
get {
return this.myStruct.property3;
}
set {
this.myStruct.property3 = EngineUtils.FillOrTruncate(value, Bean.Length);
RaisePropertyChanged("Property3");
}
}
}

alternative FizzBuzz example error

Been trying to solve this for 2 days now and I just can't get it to work! The programs layout has to stay the same (part of the challenge). Really bugging me and hoping somebody could shed some light...
I keep getting the following error:
Use of unassigned local variable 'countOfFizz'
Use of unassigned local variable 'countOfBuzz'
Use of unassigned local variable 'countOfFizzBuzz'
Use of unassigned local variable 'countOfPrime'
On these lines:
fb.IsFizz(input, countOfFizz);
fb.IsFizz(input, countOfBuzz);
fb.IsFizz(input, countOfFizzBuzz);
fb.IsFizz(input, countOfPrime);
and here is the full code. (again apologies if its poor coding, its basics and the layout has been supplied already).
class FizzBuzz
{
public static void Main()
{
int input;
string enter;
int countOfFizz;
int countOfBuzz;
int countOfFizzBuzz;
int countOfPrime;
Console.WriteLine("Please enter a number: ");
enter = Console.ReadLine();
input = int.Parse(enter);
while (input != 0)
{
Console.WriteLine("Please enter a number: ");
enter = Console.ReadLine();
input = int.Parse(enter);
FizzBuzz fb = new FizzBuzz();
fb.IsFizz(input, countOfFizz);
FizzBuzz fb1 = new FizzBuzz();
fb1.IsBuzz(input, countOfBuzz);
FizzBuzz fb2 = new FizzBuzz();
fb2.IsFizzBuzz(input, countOfFizzBuzz);
FizzBuzz fb3 = new FizzBuzz();
fb3.IsPrime(input, countOfPrime);
FizzBuzz fb4 = new FizzBuzz();
fb4.TotalFizz(countOfFizz);
FizzBuzz fb5 = new FizzBuzz();
fb5.TotalBuzz(countOfBuzz);
FizzBuzz fb6 = new FizzBuzz();
fb6.TotalFizzBuzz(countOfFizzBuzz);
FizzBuzz fb7 = new FizzBuzz();
fb7.TotalPrime(countOfPrime);
}
Console.WriteLine("Finished.");
}
public bool IsFizz(int input, int countOfFizz)
{
if (input % 9 == 0)
{
Console.WriteLine("Fizz");
countOfFizz++;
return true;
}
return false;
}
public bool IsBuzz(int input, int countOfBuzz)
{
if (input % 13 == 0)
{
Console.WriteLine("Buzz");
countOfBuzz++;
return true;
}
return false;
}
public bool IsFizzBuzz(int input, int countOfFizzBuzz)
{
if (input % 9 == 0 && input % 13 == 0)
{
Console.WriteLine("FizzBuzz");
countOfFizzBuzz++;
return true;
}
return false;
}
public bool IsPrime(int input, int countOfPrime)
{
for (int i = 2; i < input; i++)
{
if (input % i == 0 && i != input)
{
return false;
}
}
Console.WriteLine("Prime");
countOfPrime++;
return true;
}
public void BeginTesting(int countOfFizz, int countOfBuzz, int countOfFizzBuzz, int countOfPrime)
{
countOfFizz = 0;
countOfBuzz = 0;
countOfFizzBuzz = 0;
countOfPrime = 0;
}
public int TotalFizz(int countOfFizz)
{
Console.WriteLine("Number of Fizz: ");
return countOfFizz;
}
public int TotalBuzz(int countOfBuzz)
{
Console.WriteLine("Number of Buzz: ");
return countOfBuzz;
}
public int TotalFizzBuzz(int countOfFizzBuzz)
{
Console.WriteLine("Number of FizzBuzz: ");
return countOfFizzBuzz;
}
public int TotalPrime(int countOfPrime)
{
Console.WriteLine("Number of Prime: ");
return countOfPrime;
}
}
The problem is that you are passing ints to the methods, when an int (or float, bool, etc.) is passed to a method it is copied, it is not passed as a reference variable. Therefore, the countOfBuzz you change within a method is not the same as the one in the main method.
To solve this, don't pass those parameters to the methods. Instead, change the scope of those variables to be inside the class instead of inside the main method.
Also, it is good practice to initialize the variables to zero (local variables within methods need to be initialized, otherwise you get that message you asked about).
As Simon already explained in his answer, integers are value types and all value types are always passed by value (by default). This means that when you call for example IsFizz with the countOfFizz then all that happens is that the value of that variable is passed to the function which then has its own variable with a copy of the value. So when the function changes the value, then only that local variable’s value changed but that change will never make it to the original variable.
One way to solve this would be to explicitely pass those variables by reference. You can do this by using ref int countOfFizz in the function signature for the parameter (i.e. add the ref keyword). However, I do not recommend you to do this as it will not provide a state the FizzBuzz class was likely to have.
So, in object oriented programming, you create objects which hold a state. In your case, the FizzBuzz is the class, the type of those objects. Now if we think about it, and take into account that you apparently want to keep count of the number of Fizz/Buzz/FizzBuzz cases, it makes sense to have those counts contained within the object.
So first of all, you should make those countOfX variables instance variables that are bound to the object.
Looking at the IsFizz etc. methods, they are all supposed to return a boolean value. So it’s likely that they were originally only meant to check the input and return true or false depending on if the check succeeded or not. Here we can also increment our counters when we find a falue. So in the end, those methods should only take the input, perform the check, increment their counter and return the check result.
The TotalX methods can then simply return the current counter results, while the BeginTesting method can reset them to zero (without taking any parameters).
Finally, in the Main function you want to create only a single instance of FizzBuzz so we can share the state during the whole duration of the program. You should check the return values for the IsX methods and print the appropriate response here (often you don’t want class types to arbitrarily print stuff but handle that in a different layer—in your case the console application that happens in the Main function).
As a final note, I would like you to know that I’m interpreting a lot into the original task here and cannot perfectly say what the original intention behind this code was. From my point of view it looks a bit ridiculous to do it like that. The FizzBuzz problem, even in this changed instance, is a simple problem aimed to show if a person is capable of basic programming-related thinking. It’s not necessarily meant to be a problem to work on in a complex object oriented manner, but just like the typical “Hello World” there seem to be people who like over-generalizing it in a way to make it terribly complex for fun or practice. I’m not really agreeing that this FizzBuzz instance with that predefined base code is either generalized nor fun nor a good practice. But again, this is just my opinion.
And finally a last hint to complete this “correctly”: The output “FizzBuzz” is the combination of both conditionals for “Fizz” and ”Buzz”. Meaning that if a number qualifies for “FizzBuzz” it also does so for the individual ones. So you should make sure that the check for the individual ones either explicitely prevent the “FizzBuzz” combination to match, or you check for the combined one first and abort further checks if it matches.
Initialize the variables might do the trick for you:
int countOfFizz = 0;
int countOfBuzz = 0;
int countOfFizzBuzz = 0;
int countOfPrime = 0;
Remove the parameter (countOfFizz) from IsFizz, and it should work. Do the same for other similar methods.
public bool IsFizz(int input)
{
if (input % 9 == 0)
{
Console.WriteLine("Fizz");
countOfFizz++;
return true;
}
return false;
}

Basic locking question in C#

The classes:
public class SomeCollection
{
public void IteratorReset()
{
index = -1;
}
public bool IteratorNext()
{
index++;
return index < Count;
}
public int Count
{
get
{
return floatCollection.Count;
}
}
public float CurrentValue
{
get
{
return floatCollection[index];
}
}
public int CurrentIndex
{
get
{
return intCollection[index];
}
}
}
Class that holds reference to 'SomeCollection':
public class ThreadUnsafeClass
{
public SomeCollection CollectionObj
{
get
{
return collectionObj;
}
}
}
Classes ClassA, ClassB and ClassC contain the following loop that iterates over CollectionObj:
for (threadUnsafeClass.CollectionObj.IteratorReset(); threadUnsafeClass.CollectionObj.IteratorNext(); )
{
int currentIntIndex = threadUnsafeClass.CollectionObj.CurrentIndex;
float currentfloatValue = threadUnsafeClass.CollectionObj.CurrentValue;
// ...
}
Since I'm only reading CollectionObj in the 3 classes, I'm using multithreading for speedup, but I'm not quite sure how to enforce thread safety. I added a lock in ThreadUnsafeClass when retrieving CollectionObj, but the application throws an out of range exception.
Any help is appreciated.
Thank you !
You're only reading the CollectionObj property, but then you're mutating the object that the value refers to. See this bit:
for (threadUnsafeClass.CollectionObj.IteratorReset();
threadUnsafeClass.CollectionObj.IteratorNext(); )
Both IteratorReset and IteratorNext mutate SomeCollection by changing the value of index. Basically, you can't do this safely with your current code. Several threads could all call IteratorNext() at the same time, for example. The first call returns true, but before that thread gets a chance to read the values, the other threads make the index invalid.
Why are you using the collection itself for iteration? Typically you'd implement IEnumerable<T> and return a new object in GetEnumerator. That way different threads could each get a different object representing "their" cursor over the same collection. They could all iterate over it, and all see all the values.
The SomeCollection object is being referenced by each of the three classes A,B, and C, each of which is going to try and increment the internal index, causing the error(s). That said, you should be able to read objects in an array from multiple threads with something like the following:
public static object[] sharedList = new object[]{1,2,3,4,5};
public void Worker()
{
int localSum=0;
for(int i=0; i<sharedList.length; i++){
localSum += (int)sharedList[i];
}
}
The important thing here is that each thread will maintain it's own location within the array, unlike with the collectionObj.
Locking the CollectionObj property won't help. One possible problem is that all 3 threads are calling IteratorReset(), which sets the index to -1. Imagine the scenario where A starts the for loop, and gets to the first line in the loop before getting interrupted. Now B comes in and calls IteratorReset(), then gets interrupted to let A run again. Thread A executes the CurrentIndex property, which internally uses index = -1 due to B running. Boom, out of range exception.
There are other ways this can generate bad results, but that's probably the easiest to see. Is the intention to have all three threads go through each item on their own? Or are you expecting A, B, and C to divide up the work (like a consumer queue)?

Categories