Conversion OF FIFO code from Java to c# - c#

couple of days ago i posted a topic about fifo programming and how to do it because the topic was a bit broad and vague and lacks coding example, so i followed experts advice and searched for codes and tried a bit of coding. and i knew exactly what i wanted to do
i want to create a DES (Discrete event simulation) for the FIFO (first in first out) scheduling algorithm using the C# as my programming language.
so i searched the net and i couldn't find something really helpful in c# for guidance but i found exactly what i wanted to in java codes. which i will post now
The process of Initialization
Queue q = new Queue();
EventQueue eventq = new EventQueue();
Random rand = new Random();
Distribution interarrivalTimeDist =
new ExponentialDistribution(lambda, rand);
Distribution serviceTimeDist =
new ExponentialDistribution(mu, rand);
double t = 0;
// generate first arrival
eventq.addEvent(new Event(Event.ARRIVAL,
interarrivalTimeDist.nextRandom()));
Main program
while (t < simLength) {
Event e = eventq.nextEvent();
t = e.getTime();
switch (e.getType()) {
case Event.ARRIVAL : {
// handle arrival
}
case Event.DEPARTURE : {
// handle departure
}
}
}
Case of Arrival
case Event.ARRIVAL : {
// schedule next arrival
eventq.addEvent(new Event(Event.ARRIVAL,
t + interarrivalTimeDist.nextRandom()));
double serviceTime =
serviceTimeDist.nextRandom();
q.addCustomer(new Customer(t, serviceTime));
if (q.getSize() == 1) {
eventq.addEvent(new Event(Event.DEPARTURE,
t + serviceTime));
}
break;
}
Case of departure
case Event.DEPARTURE : {
q.removeCustomer(t);
if (q.getSize() > 0) {
double serviceTime =
q.getCustomerAt(0).getServiceTime();
eventq.addEvent(new Event(Event.DEPARTURE,
t + serviceTime));
}
break;
}
any clues or guidance how to convert this code to c#??
and help will help highly appreciated it
PS:- for the experts please show some tolerance if my topic wasn't as professional as you guys thought it will be
thanks

Your question sounds a lot like "how do I program this idea", and isn't a good SO question. You should design a lot about what you want to do, build it in steps, and come here with specific questions you have, not broad ideas or lots of code.
To answer just FIFO, that is a queue. Read about queues and practice with them.

Related

How to write tests for legacy code and then refactor it?

I have a project with lots of ugly code I've written some time ago. Now I'm trying to make it testable and to use TDD for further development. But every time I'm trying to write unit tests for existing code I'm getting stuck. I just don't know how to test my old code. I can't write any little test. It makes me sick. So can anyone show me what tests to write for function like this to make further refactoring painless:
public void ChangeHealth(UInt16 id, HealthTypes health, FighterCount count)
{
var uc = new FighterCommand {Health = health, KillerId = 1024};
Fighter f;
switch(count)
{
case FighterCount.All:
if (Fight.GetInstance().Status == FightStatuses.Enable)
{
foreach (var u in Fighters.Elements)
uc.AddUnit(u.Id);
}
FightEvents.StatusUnit(null, health);
_sender.SendCommand_AppServer(uc);
break;
case FighterCount.NotEqual:
for (var i = Fighters.Count - 1; i >= 0; i--)
{
f = Fighters.GetUnit(i);
if (health == f.Health) continue;
uc.AddUnit(f.Id);
FightEvents.StatusUnit(f, health);
}
if (uc.UnitCount > 0) _sender.SendCommand_AppServer(uc);
break;
default:
f = Fighters.GetById(id);
uc.AddUnit(f.Id);
FightEvents.StatusUnit(f, health);
_sender.SendCommand_AppServer(uc);
break;
}
}
Take a look at the "golden master" technique by Michael Feathers. The idea is that you throw input at your untestable code, record the output or the state of your program. Then you can refactor and throw the same input and observe the same output or internal state (with the exception of the minor incremental change you've made). Bit by bit the code becomes more testable. Explained in further depth at http://blog.thecodewhisperer.com/2014/09/28/surviving-legacy-code-with-golden-master-and-sampling/
A tool for dumping the state of your application is https://github.com/kbilsted/StatePrinter where you simply can say
var printer = new Stateprinter();
Console.WriteLine( printer.PrintObject( myProgram) );

Translations without using localization options

I've heard that many people had problems using the language localization features, plus you can only translate the interface (I can't translate messages from a messagebox as far as I know).
So I just wanted to know what do you think about my approach to translate my winform app.
namespace Tris
{
class Translations
{
public string draws;
public string language;
public string help;
public string newgame;
public bool lang_en;
public bool lang_it;
public bool lang_ru;
namespace Tris
{
class TranslationStrings
{
public void engTranslation(Translations TS)
{
TS.draws = "Draws";
TS.language = "Language";
TS.help = "Help";
TS.newgame = "New Game";
TS.lang_en = true;
TS.lang_it = false;
TS.lang_ru = false;
public void rusTranslation(Translations TS)
{
TS.draws = "Ничья";
TS.language = "Язык";
TS.help = "Помощь";
TS.newgame = "Новая Игра";
TS.lang_en = false;
TS.lang_it = false;
TS.lang_ru = true;
When I need something I just call the right method:
case 2:
pic = Properties.Resources.end3;
if (lang_en)
{
strings.winTranslationsEng(TS);
phrase = loser + TS.win3;
End1 end3 = new End1(lang_en, lang_it, lang_ru, winner, loser, phrase, pic);
end3.ShowDialog();
}
if (lang_it)
{
strings.winTranslationsIta(TS);
phrase = loser + TS.win3;
End1 end3 = new End1(lang_en, lang_it, lang_ru, winner, loser, phrase, pic);
end3.ShowDialog();
}
if (lang_ru)
{
strings.winTranslationsRus(TS);
phrase = winner + TS.win1;
End1 end1 = new End1(lang_en, lang_it, lang_ru, winner, loser, phrase, pic);
end1.ShowDialog();
}
break;
Before all the code was like:
if(lang_en)
{
phrase="hi";
}
if(lang_it)
{
phrase="ciao";
}
etc
Now it's way better than before, but I'm not still satisfied.
This way of managing translations makes me use a boolean, so I have to add a new "if else" on which translation method I want to pick for every new language I add.
Do you have any suggestions about how to implement a better translation system?
Do you think mine is legit or inappropriate?
edit:
The application should be in English, then I can press a button to use either the Italian or the Russian language
Your implementation of localization will work, but it will involve heavy maintenance, lots and lots of if statements and your entire codebase will need to be revisited when you want to add another language option to your application. You can imagine the headache that that will make for yourself or a future maintainer of the application.
Instead of rolling a self made, very heavy localization implementation, I would recommend that you familiarize yourself with how to do localization and globalization within C# on an application scale, utilizing resource files. Full information obtainable here
This method will even allow for localization of message dialogue texts, menu text, form headers and most importantly numerical representations of values
(Eg. US = $23 432.22 vs DE = $23.432,22 note the difference in thousand and decimal seperators)
Here is also a very good explanation from a similar question on SO:
How to use localization in C#

Depth first search did find solution state in Missionaries and Cannibals problems

I am doing my project on Missionaries and Cannibals using C#. I have used two search algorithms namely breadth first search and depth first search. Using Breadth first search, the program finds the result at level 12 from the root. But using Depth first search, it can not find solution and this hangs my computer. I think it enters a cycle in the graph. So my question is, can't i use Depth first search to solve Missionaries and cannibals problem?
Code for Breadth first search is
public State getSolutionStatesBFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, true);
while (searchAgenda.Count > 0) {
CurState = (State)searchAgenda.Dequeue();
if (CurState.Equals(EndState)) {
break;
} else {
if (!isVisited(CurState, visited))
{
generateSucessors(CurState, true);
visited.Add(CurState);
}
}
}
return CurState;
}
and the code for depth first search is
public State getSolutionStatesDFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, false);
while (searchAgendaS.Count > 0)
{
CurState = (State)searchAgendaS.Pop();
if (CurState.Equals(EndState))
{
break;
}
else
{
if(!isVisited(CurState,visited))
{
generateSucessors(CurState, false);
}
}
}
return CurState;
}
It is hard to tell answer seeing your code. However, based upon my experience: a DFS search does not provide complete solution. There is a good possibility that your code might have got stuck into some infinite loop (which is common with dfs) or (since, you are checking isVisited), there is a possibility that you are not reaching the end goal.
So my question is, can't i use Depth first search to solve Missionaries and cannibals problem?
Yes, it is deffinatly possible, take a look at this site:
http://www.aiai.ed.ac.uk/~gwickler/missionaries.html
With the code given its hard to tell where your issue is.

Complicated C# for learning purposes

I'm trying to read some of other people's code, both to help me learn C#, and also purely to develop my ability to understand other people's code, but a lot of what I've found online to look at is both very long, and relatively simple. I wonder if anyone could point me to something short but more complex, preferably including less common uses of the language.
(It doesn't need to do anything sensible, so long as it does something. Something entirely pointless, like a C# equivilent of the XSLT Mandelbrot, would be perfectly fine)
Eric Lippert has recently been writing a series on graph colouring on his blog. This may well be something to sink your teeth into as it's a multi-part series that should allow you to work your way from simple to brain-meltingly-ouch as he progresses with explaining graph colouring. =)
I'd recommend looking at the Effective C# books. They'll help you learn more complex uses of the language.
Take a look at the mono source code - many of the BCL classes are implemented and you are sure to learn something :)
There are also many open source .NET projects out there that are not small and simple applications that you can look at.
Here are some off the top of my head:
MonoDevelop - a .NET IDE
nHibernate - an ORM
Pinta - image manipulation a la gimp
Raytracing in one LINQ statement, from Luke Hoban's blog, jumps immediately to mind.
Take a look at the .NET framework assemblies themselves using the .NET Reflector. There is a bunch of really great stuff in there and has helped me a lot during my learning.
Many times I have thought to myself how Microsoft has done certain things in the framework and I was easily able to find the answers right within their source.
Check out Coding4Fun. It's a mix of .Net languages and some (most) of the projects are really cool. XNA Creators Club is pretty cool as well... plenty of samples and it you have an XBox360 or a Zune you can write games for them as well.
How about this?
private Element ReadMemberExpression()
{
var queue = new Queue<Element[]>();
var newDepth = 0;
var argsCount = 0;
_scanner.CreateRestorePoint();
while (true)
{
_scanner.CreateRestorePoint();
{
var a = ReadArguments();
if (a != null)
{
argsCount++;
if (argsCount > newDepth)
{
_scanner.Restore();
break;
}
queue.Enqueue(new[] { default(Element), default(Element), a });
_scanner.DeleteRestorePoint();
continue;
}
}
_scanner.DeleteRestorePoint();
var pe = ReadPrimaryExpression();
if (pe != null)
{
queue.Enqueue(new[] { pe });
continue;
}
var fe = ReadFunctionExpression();
if (fe != null)
{
queue.Enqueue(new[] { fe });
continue;
}
if (_scanner.MatchNext(Grammar.New))
{
newDepth++;
queue.Enqueue(new[] { Grammar.New });
}
else if (_scanner.Match(Grammar.LeftSquareBracket))
{
var e = ReadExpression();
if (e == null)
{
throw new ParseException();
}
if (!_scanner.MatchNext(Grammar.RightSquareBracket))
{
throw new ParseException();
}
queue.Enqueue(new[]{default(Element), Grammar.LeftSquareBracket, e, Grammar.RightSquareBracket});
}
else if (_scanner.Match(Grammar.FullStop))
{
if (!_scanner.MatchNext(ElementType.IdentifierName))
{
throw new ParseException();
}
queue.Enqueue(new[] { default(Element), Grammar.FullStop, _scanner.Current });
}
else
{
_scanner.Unwind();
break;
}
}
if (queue.Count == 0)
{
_scanner.DeleteRestorePoint();
return null;
}
else
{
var element = default(Element);
var children = queue.Dequeue();
while (children[0] == Grammar.New)
{
children = queue.Dequeue();
}
element = new Element(ElementType.MemberExpression, children);
while (queue.Count > 0)
{
children = queue.Dequeue();
if (children.Length == 3 && children[2].Type == ElementType.Arguments)
{
newDepth--;
children[0] = Grammar.New;
children[1] = element;
element = new Element(ElementType.MemberExpression, children);
}
else
{
children[0] = element;
element = new Element(ElementType.MemberExpression, children);
}
}
if (newDepth > 0)
{
_scanner.Restore();
return null;
}
_scanner.DeleteRestorePoint();
return element;
}
}
It's not terribly complex, but may be briefly entertaining -- Mads Torgersen has implemented a fixed-point combinator in C# here:
http://blogs.msdn.com/b/madst/archive/2007/05/11/recursive-lambda-expressions.aspx
This may be an obvious suggestion, but I would checkout the articles on CodeProject.com. You can search for specific articles relevant to C#, and the contributors generally do a great job of explaining their code.
For instance, here is an article on creating a Mandelbrot set in C# (though this may not be as complex as you might be looking for).
Other than that, I would take a peak inside any C# opensource projects you may find via Google.

Pragmatic programmer code generation exercise

I am reading the The Pragmatic programmer and doing the following exercise in .net world (Chapter 3 - Code Generators)
The Exercise
"Write a code generator that takes the input in Listing 1, and generates output in two languages of your choice. Try to make it easy to add new languages."
Listing 1
# Add a product
# to the 'on-order' list
M AddProduct
F id int
F name char[30]
F order_code int
E
How would you implement the solution in T4 or anything else in .net world (CodeDOM is too complex) so that we can generate the code in c# and in one other .net language (visual basic or IronRuby etc.)
I know you say CodeDOM is too complex, but I would suggest using CodeDOM =). Here's a short example to start with: http://asp.dotnetheaven.com/howto/doc/listbuilder.aspx. For your example, you probably want to add a CodeMemberMethod to CodeTypeDeclaration's members - MSDN has some examples.
T4 could work, but it I don't think it's really ideal for this situation.
I don't think this is intended to be an exercise in working with existing code generators. Actually there's much more to it. The goal, I believe, is to build your own code generator, domain-specific language and deal with concepts like parsing and extensibility/pluggability. Perhaps I am reading too much into the exercise, but perhaps it's more about developing core developer skills/knowledge than educating oneself on existing tools.
Taking Ben Griswold advice, I think it is a good idea to implement it myself. And while just a little into implementing code generator in C#, I realized few things -
1. Need text manipulation language like Python etc.
2. Need to learn Regular expressions
I do intend to implement it in Ruby but for now, I implemented it in C# as -
static void Main(string[] args)
{
CodeGenerator gen = new CodeGenerator();
gen.ReadFile("Input.txt");
}
public class CodeGenerator
{
public void ReadFile(string filename)
{
StreamReader fs = new StreamReader(filename);
string line;
CSharpCode CG = new CSharpCode();
while ((line = fs.ReadLine()) != null)
{
line = line.TrimEnd('\n');
if (Regex.IsMatch(line, #"^\s*S"))
CG.BlankLine();
else if (Regex.IsMatch(line, #"^\#(.*)")) // match comments
CG.Comment(line.TrimStart('#'));
else if (Regex.IsMatch(line, #"^M\s*(.+)")) // start msg
CG.StartMsg(line.Split(' ')[1]);
else if (Regex.IsMatch(line, #"^E")) // end msg
CG.EndMsg();
else if (Regex.IsMatch(line, #"^F\s*(\w+)")) // simple type
CG.SimpleType(Regex.Split(line, #"^F\s*(\w+)")[1], Regex.Split(line, #"^F\s*(\w+)")[2]);
else
Console.WriteLine("Invalid line " + line);
}
}
}
// Code Generator for C#
public class CSharpCode
{
public void BlankLine() { Console.WriteLine(); }
public void Comment(string comment) { Console.WriteLine("//" + comment); }
public void StartMsg(string name) { Console.WriteLine("public struct " + name + "{"); }
public void EndMsg() { Console.WriteLine("}"); }
public void SimpleType(string name, string type)
{
if(type.Contains("char["))
type = "string";
Console.WriteLine(string.Format("\t{0} {1};", type.Trim(), name));
}
}

Categories

Resources