Constructing a Moore Machine - output

I have a homework question:
Construct a Moore machine that takes a string consisting of a's b's
and c's as input and outputs a string containing 1 at the end of each
substring abc and a 0 in all other positions. e.g. input, aabcb
produces output, 000010
I tried constructing, but I have come to a dead end. Here is my attempt:
As you can see, I can't create a string cccb and an 'abc' can output a 0. I feel like I overcomplicated this simple problem.
EDIT: Took a break and redid it. I think this is right, unless someone can tell me otherwise:

The solution. Just needed to think clearly.

I'll try to help you without spoiling an answer:
Why do you use a second cycle (the lower triangle)?
How would you implement a machine that halts successfully after finding a subsequence?
What do you need to do to keep it running indefinitely? Convince yourself that an error to match a subsequence is equivalent to the initial state.
I've solved it using only four states, but maybe there's a solution with just three. It should be clear that you can't get better than that.

Related

Shows warning during compiling

enter image description here
it show warning
I was suppose to arrange the numbers, In order irrespective of the values, but to move 0 come at last.
To learn what you are doing wrong you need to read a book in C. Basic one.
I can point some errors and good practices.
comparison is done by ==. so you should use if(i==0)
After the second for loop you would want to change the value of i to 0. i=0.
the two for loops should be run upto the point when i<n and j<n.
That if(a[i]==0) comparison is not needed.
You don't need the while loop here.
You can print all of them after the for-for looping.
Global variables are used but you should have a good reason to use that.
Index variables are better if declared and defined locally.
what you are trying to do is known as Bubble sort.
Even after understanding all this and following this you get error try to run it through debugger, try small value of n.
Then if you can't, then ask here.

Passing a command line argument (as a string) into my Perl script

I'm extremely new at Perl and trying to prove I can pick it up quickly. What I was asked to do is add a string as an argument on my command line, and then feed that into my script. From there it is supposed to search a MySQL table I've made for matches in one column, and spit the contents of another column into an array. It was suggested I used the Getops:Std but I'm uncertain how exactly to do that, and if that's the best technique.
For example: I have a MySQL table with car manufacturers, and car models. I want to run, Perl myscript.pl Ford, and then have it shoot me back an array with
Mustang
Escape
Focus
But I'm uncertain how to get that string input in the first place. Would Getops:Std be best? If so how would it be written? I'm picking this up quickly, but I've been at it less than a week, so the simpler the explanation, the better.
Edit: Basically I was confused why it was suggested I should use GetOpts::Std for this. It seems to be completely inappropriate for what I'm trying to do.
GetOpts::Std is overkill for this. Your command line arguments are in #ARGV. If you haven't been able to work that out after a week, then you need better references for Perl.
The first argument will be in $ARGV[0], the second in $ARGV[1] , and so on.
You should check the DBI module. Google for some tutorial out there.
Then try to write your script and post more specific questions with some code if you need more help.

Query in MUMPS statement

I $P(GIH,,24)= S $P(GIH,,24)="C" S
What is the meaning of two S's in above MUMPS statement?
Let me start out by saying the original statement is NOT either Standard MUMPS or InterSystems Cache, or GT.M code. Even broadly guessing what was originally meant, the final S on the line isn't something you would do in MUMPS. A single S could be a SET command, but you still don't have any arguments telling what variable could be assigned, or what value should be assigned to it.
The rest of my reply is trying to figure out what it could have meant.
Your question seems to be broken by some software. either that on stackoverflow or the cut-and-paste process to put it here:
I saw:
I $P(GIH,,24)= S $P(GIH,,24)="C" S
What is the meaning of two S's in above MUMPS statement?
It is hard to figure out what you meant, since it would require hypothesizing where quotes might be and which ones could have been deleted by the transmission of the question.
First of all, let's do something we can guess is reasonable. $P is usually an abbreviation for the built-in (intrinsic) function $PIECE. an I standing alone is probably an IF command
and an S standing alone is probably a SET command. This runs into a problem with your example, because the format of a line of MUMPS code is COMMAND COMMAND-ARGUMENT.
Aside Note: I also just tried to put the text COMMAND-ARGUMENT in "angle brackets" ie: with a less-than character at the beginning of the word and a greater-than character at the end. The text COMMAND-ARGUMENT just disappeared. Which means that stackoverflow sees it as HTML markup. I notice there is a Code marker on the top of this edit window which may or may not help.
If we do the expansions to the code above, we get:
IF $PIECE(GIH,,24)= SET $PIECE(GIH,,24)="C" SET
When we expand the final S but it looks like a SET command, but without any set-argument.
Note, if this was in a Cache system, we might have an example of extra spaces allowed by Cache, which are not allowed in Standard MUMPS, ie the S may have been the right hand side of an equality operator in the IF command. This would only make sense if Cache also allowed the argument of the SET command to be in code without an actual SET command.
i.e.:
IF $PIECE(GIH,,24)=S $PIECE(GIH,,24)="C" SET
We still would have to deal with the two commas in a row for the $PIECE intrinsic function. Currently using two commas in a row to indicate a missing argument is only allowed in Programmer-written code, not when using built-in functions. So this might be a place where we can guess what you meant, or originally pasted in.
If we put in double-quotes we run into the problem that $PIECE command (which separates a string based on a delimiter) would have an quoted string of zero length given as its second argument. Which is just as erroneous as having an empty argument.
So if we hypothesize a quoted string that has angle brackets, we would get something this for your original line:
IF $PIECE(GIH,"<something>",24)="<something>" SET $PIECE(GIH,"<something>",24)="C" SET
Note: I just saw the Code marker allows use of grave accents to keep from assuming a line is HTML - which is good since grave accent is not a character used in MUMPS coding.
As has been mentioned on another reply, the SET-$PIECE-ARGUMENT form is used to change the data stored in a database at a particular delimited substring location.
So this code might be fine for guessing, but it has gone far afield of what you may or may not have done. So I'm stopping now until we get feedback that this is even close to what you wanted. As I said at the first, this is still not quite valid code.
This is pretty bizarre, but what I think is going on is:
I $P(GIH,<null>,24)=<null>
Calling $PIECE with the second argument null will replace the entire string with the value you're assigning, which, in this case, is also null. It looks like a convoluted way of clearing the value of GIH and permitting control to flow into the following SET statement. I seriously doubt that $PIECE sets the $T flag, though, which means that calling this as the condition for the IF operator probably isn't working the way you want it to.
S $P(GIH,,24)="C"
The next statement looks a lot like the first -- replace the entirety of GIH with "C".
S
I don't think the last SET is valid MUMPS.
Why this isn't written as follows is beyond me:
s GIH="C"
Hope that helps!
Maybe Intersystems Caché handles this syntax differently, but that code results in a syntax error when I try it in Caché. There may be other versions of MUMPS for which that is valid, but I don't think it is.
As other have pointed out this statement is not valid, It appears pieces are missing
But S is the SET command in Mumps
Here is what a statement like this might look like:
I $P(GIH,"^",24)="P" S $P(GIH,"^",24)="C" S UPDATEFLG=1
in this case GIH might look something like:
GIH=256^^^42^^^^Mike^^^^^^^^^^^^^^^^P^^^
which would make this evaluate to TRUE:
I $P(GIH,"^",24)="P"
so after:
S $P(GIH,"^",24)="C"
GIH will be:
GIH=256^^^42^^^^Mike^^^^^^^^^^^^^^^^C^^^
then it would set the variable UPDATEFLG=1
Hope this helps :-)

How should substring() work?

I do not understand why Java's [String.substring() method](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#substring(int,%20int%29) is specified the way it is. I can't tell it to start at a numbered-position and return a specified number of characters; I have to compute the end position myself. And if I specify an end position beyond the end of the String, instead of just returning the rest of the String for me, Java throws an Exception.
I'm used to languages where substring() (or substr()) takes two parameters: a start position, and a length. Is this objectively better than the way Java does it, and if so, can you prove it? What's the best language specification for substring() that you have seen, and when if ever would it be a good idea for a language to do things differently? Is that IndexOutOfBoundsException that Java throws a good design idea, or not? Does all this just come down to personal preference?
There are times when the second parameter being a length is more convenient, and there are times when the second parameter being the "offset to stop before" is more convenient. Likewise there are times when "if I give you something that's too big, just go to the end of the string" is convenient, and there are times when it indicates a bug and should really throw an exception.
The second parameter being a length is useful if you've got a fixed length of field. For instance:
// C#
String guid = fullString.Substring(offset, 36);
The second parameter being an offset is useful if you're going up to another delimited:
// Java
int nextColon = fullString.indexOf(':', start);
if (start == -1)
{
// Handle error
}
else
{
String value = fullString.substring(start, nextColon);
}
Typically, the one you want to use is the opposite to the one that's provided on your current platform, in my experience :)
I'm used to languages where
substring() (or substr()) takes two
parameters: a start position, and a
length. Is this objectively better
than the way Java does it, and if so,
can you prove it?
No, it's not objectively better. It all depends on the context in which you want to use it. If you want to extract a substring of a specific length, it's bad, but if you want to extract a substring that ends at, say, the first occurrence of "." in the string, it's better than if you first had to compute a length. The question is: which requirement is more common? I'd say the latter. Of course, the best solution would be to have both versions in the API, but if you need the length-based one all the time, using a static utility method isn't that horrible.
As for the exception, yeah, that's definitely good design. You asked for something specific, and when you can't get that specific thing, the API should not try to guess what you might have wanted instead - that way, bugs become apparent more quickly.
Also, Java DOES have an alternative substring() method that returns the substring from a start index until the end of the string.
second parameter should be optional, first parameter should accept negative values..
If you leave off the 2nd parameter it will go to the end of the string for you without you having to compute it.
Having gotten some feedback, I see when the second-parameter-as-index scenario is useful, but so far all of those scenarios seem to be working around other language/API limitations. For example, the API doesn't provide a convenient routine to give me the Strings before and after the first colon in the input String, so instead I get that String's index and call substring(). (And this explains why the second position parameter in substr() overshoots the desired index by 1, IMO.)
It seems to me that with a more comprehensive set of string-processing functions in the language's toolkit, the second-parameter-as-index scenario loses out to second-parameter-as-length. But somebody please post me a counterexample. :)
If you store this away, the problem should stop plaguing your dreams and you'll finally achieve a good night's rest:
public String skipsSubstring(String s, int index, int length) {
return s.subString(index, index+length);
}

Is hard-coding literals ever acceptable?

The code base I'm currently working on is littered with hard-coded values.
I view all hard coded values as a code smell and I try to eliminate them where possible...however there are some cases that I am unsure about.
Here are two examples that I can think of that make me wonder what the best practice is:
1. MyTextBox.Text = someCondition ? "Yes" : "No"
2. double myPercentage = myValue / 100;
In the first case, is the best thing to do to create a class that allows me to do MyHelper.Yes and MyHelper.No or perhaps something similar in a config file (though it isn't likely to change and who knows if there might ever be a case where its usage would be case sensitive).
In the second case, finding a percentage by dividing by 100 isn't likely to ever change unless the laws of mathematics change...but I still wonder if there is a better way.
Can anyone suggest an appropriate way to deal with this sort of hard coding? And can anyone think of any places where hard coding is an acceptable practice?
And can anyone think of any places where hard coding is an acceptable practice?
Small apps
Single man projects
Throw aways
Short living projects
For short anything that won't be maintained by others.
Gee I've just realized how much being maintainer coder hurt me in the past :)
The real question isn't about hard coding, but rather repetition. If you take the excellent advice found in "The Pragmatic Programmer", simply Don't Repeat Yourself (DRY).
Taking the principle of DRY, it is fine to hardcode something at any point. However, once you use that particular value again, refactor so this value is only hardcoded once.
Of course hard-coding is sometimes acceptable. Following dogma is rarely as useful a practice as using your brain.
(For an example of this, perhaps it's interesting to go back to the goto wars. How many programmers do you know that will swear by all things holy that goto is evil? Why then does Steve McConnell devote a dozen pages to a measured discussion of the subject in Code Complete?)
Sure, there's a lot of hard-gained experience that tells us that small throw-away applications often mutate into production code, but that's no reason for zealotry. The agilists tell us we should do the simplest thing that could possibly work and refactor when needed.
That's not to say that the "simplest thing" shouldn't be readable code. It may make perfect sense, even in a throw-away spike to write:
const MAX_CACHE_RECORDS = 50
foo = GetNewCache(MAX_CACHE_RECORDS)
This is regardless of the fact that in three iterations time, someone might ask for the number of cache records to be configurable, and you might end up refactoring the constant away.
Just remember, if you go to the extremes of stuff like
const ONE_HUNDRED = 100
const ONE_HUNDRED_AND_ONE = 101
we'll all come to The Daily WTF and laugh at you. :-)
Think! That's all.
It's never good and you just proved it...
double myPercentage = myValue / 100;
This is NOT percentage. What you wanted to write is :
double myPercentage = (myValue / 100) * 100;
Or more correctly :
double myPercentage = (myValue / myMaxValue) * 100;
But this hard coded 100 messed with your mind... So go for the getPercentage method that Colen suggested :)
double getpercentage(double myValue, double maxValue)
{
return (myValue / maxValue) * 100;
}
Also as ctacke suggested, in the first case you will be in a world of pain if you ever need to localize these literals. It's never too much trouble to add a couple more variables and/or functions
The first case will kill you if you ever need to localize. Moving it to some static or constant that is app-wide would at least make localizing it a little easier.
Case 1: When should you hard-code stuff: when you have no reason to think that it will ever change. That said, you should NEVER hard code stuff in-line. Take the time to make static variables or global variables or whatever your language gives you. Do them in the class in question, and if you notice that two classes or areas of your code share the same value FOR THE SAME REASON (meaning it's not just coincidence), point them to the same place.
Case 2: For case case 2, you're correct: the laws of "percentage" will not change (being reasonable, here), so you can hard code inline.
Case 3: The third case is where you think the thing could change but you don't want to/have time to bother loading ResourceBundles or XML or whatever. In that case, you use whatever centralizing mechanism you can -- the hated Singleton class is a good one -- and go with that until you actually have need to deal with the problem.
The third case is tricky, though: it's extraordinarily hard to internationalize an application without really doing it... so you will want to hard-code stuff and just hope that, when the i18n guys come knocking, your code is not the worst-tasting code around :)
Edit: Let me mention that I've just finished a refactoring project in which the prior developer had placed the MySql connect strings in 100+ places in the code (PHP). Sometimes they were uppercase, sometimes they were lower case, etc., so they were hard to search and replace (though Netbeans and PDT did help a lot). There are reasons why he/she did this (a project called POG basically forces this stupidity), but there is just nothing that seems less like good code than repeating the same thing in a million places.
The better way for your second example would be to define an inline function:
double getpercentage(double myValue)
{
return(myValue / 100);
}
...
double myPercentage = getpercentage(myValue);
That way it's a lot more obvious what you're doing.
Hardcoded literals should appear in unit tests for the test values, unless there is so much reuse of a value within a single test class that a local constant is useful.
The unit tests are a description of expected values without any abstraction or redirection.
Imagine yourself reading the test - you want the information literally in front of you.
The only time I use constants for test values is when many tests repeat a value (itself a bit suspicious) and the value may be subject to change.
I do use constants for things like names of test files to compare.
I don't think that your second is really an example of hardcoding. That's like having a Halve() method that takes in a value to use to divide by; doesn't make sense.
Beyond that, example 1, if you want to change the language for your app, you don't want to have to change the class, so it should absolutely be in a config.
Hard coding should be avoided like Dracula avoids the sun. It'll come back to bite you in the ass eventually.
"hardcoding" is the wrong thing to worry about. The point is not whether special values are in code or in config files, the point is:
If the value could ever change, how much work is that and how hard is it to find? Putting it in one place and referring to that place elsewhere is not much work and therefore a way to play it safe.
Will maintainance programmers definitely understand why the value is what it is? If there is any doubt whatsoever, use a named constant that explains the meaning.
Both of these goals can be achieved without any need for config files; in fact I'd avoid those if possible. "putting stuff in config files means it's easier to change" is a myth, unless either
you actually want to support customers changing the values themselves
no value that could possibly be put in the config file can cause a bug (buffer overflow, anyone?)
your build and deployment process sucks
The text for the conditions should be in a resource file; that's what it's there for.
Not normally (Are hard-coding literals acceptable)
Another way at looking at this is how using a good naming convention
for constants used in-place of hard coded literals provides additional
documentation in the program.
Even if the number is used only once, it can still be hard to recognized
and may even be hard to find for future changes.
IMHO, making programs easier to read should be second nature to a
seasoned software professional. Raw numbers rarely communicate
meaningfully.
The extra time taken to use a well named constant will make the
code readability (easy to recall to the mind) and useful for future
re-mining (code re-use).
I tend to view it in terms of the project's scope and size.
Some simple projects that I am a solo dev on? Sure, I hard code lots of things. Tools I write that only I will ever use? Sure, if it gets the job done.
But, in working on larger, team projects? I agree, they are suspect and usually the product of laziness. Tag them for review and see if you can spot a pattern where they can be abstracted away.
In your example, the text box should be localizable, so why not a class that handles that?
Remember that you WILL forget the meaning of any non-obvious hard-coded value.
So be certain to put a short comment after each to remind you.
A Delphi example:
Length := Length * 0.3048; { 0.3048 converts feet to meters }
no.
What is a simple throw away app today will be driving your entire enterprise tomorrow. Always use best practices or you'll regret it.
Code always evolves. When you initially write stuff hard coding is the easiest way to go. Later when a need arrives to change the value it can be improved. In some cases the need never comes.
The need can arrive in many forms:
The value is used in many places and it needs to be changed by a programmer. In this case a constant is clearly needed.
User needs to be able to change the value.
I don't see the need to avoid hard coding. I do see the need to change things when there is a clear need.
Totally separate issue is that of course the code needs to be readable and this means that there might be a need for a comment for the hard coded value.
For the first value, it really depends. If you don't anticipate any kind of wide-spread adoption of your application and internationalization will never be an issue, I think it's mostly fine. However, if you are writing some kind of open source software or something with a larger audience consider the fact that it may one day need to be translated. In that case, you may be better off using string resources.
It's okay as long as you don't do refactoring, unit-testing, peer code reviews. And, you don't want repeat customers. Who cares?
I once had a boss who refused to not hardcode something because in his mind it gave him full control over the software and the items related to the software. Problem was, when the hardware died that ran the software the server got renamed... meaning he had to find his code. That took a while. I simply found a hex editor and hacked around it instead of waiting.
I normally add a set of helper methods for strings and numbers.
For example when I have strings such as 'yes' and 'no' I have a function called __ so I call __('yes'); which starts out in the project by just returning the first parameter but when I need to do more complex stuff (such as internationaizaton) it's already there and the param can be used a key.
Another example is VAT (form of UK tax) in online shops, recently it changed from 17.5% to 15%. Any one who hard coded VAT by doing:
$vat = $price * 0.175;
had to then go through all references and change it to 0.15, instead the super usefull way of doing it would be to have a function or variable for VAT.
In my opinion anything that could change should be written in a changeable way. If I find myself doing the same thing more than 5 times in the same day then it becomes a function or a config var.
Hard coding should be banned forever. Althought in you very simple examples i don't see anything wrong using them in any kind of project.
In my opinion hard coding is when you believe that a variable/value/define etc. will never change and create all your code based on that belief.
Example of such hard coding is the book Teach Yourself C in 24 Hours that everybody should avoid.