I’ve started working on a new character generator in Java and decided to try to piece it together using this Model View Controller design pattern I’ve heard so much about.
For those that don’t know, and for those that do know please correct me if I’m wrong. First off we have the view which the user interacts with. The view triggers actions in the controller. The controller then changes the model. The model then dispatches and event so that the view can update to show the changes to the model.
This is a very simplified description of what MVC is and I may be wrong on this, I’ve seen some very conflicting descriptions and diagrams claiming what MVC is. But I digress, onto my confusion.
As mentioned earlier I’m trying to make a character Generator in Java using this pattern and... I’m not quite sure how this is supposed to work out. Is there some glue code that passes the objects around? Does the view hold a copy of the control, or does the control have a copy of the view?
What I’d really like to get my hands on is some production code with MVC implemented so I can scan through it. If someone knows an open source project that uses this design send me a message pointing me to it because at this point I’ve been told so many things that I’m just now sure what to think of MVC anymore.
Decided to work on the challenges in Codingame again. So far I’ve only worked on they easy challenges and they are living up to the name so far. They have been easy, except in the cases where I add an extra spin to the challenge.
As you all saw in my If statements post not too long ago, I’ve been trying to avoid using if statements except where they are absolutely necessary. Which has been a pretty fun challenge for a sign like Codingame.
The challenges (at least the ones I’ve done) in the easy section seem to be understandably geared towards the inexperienced developer and expects a solution using if statements.
Now, onto my current problem. I’ve come across another problem where I’m stuck with an if-else ladder.
In this problem we are on a stretch of road moving at a random speed from the start. Ahead there is a large hole in the road that we want to jump over. After the jump the road ends in a cliff. Also at each iteration of the loop we have a choice of speeding up, slowing down, jumping, or to wait till the next iteration. Our goal is to get enough speed to jump the gap, then slow down so that we don’t go over the cliff.
Below is my current solution. I have an if-else tree to handle what choices should be made when.
#include #include #include int main() { int R; // the length of the road before the gap. scanf("%d", &R); int G; // the length of the gap. scanf("%d", &G); int L; // the length of the landing platform. scanf("%d", &L); int option = 0; char *options[] = {"SPEED", "SLOW", "JUMP", "WAIT"}; // game loop while (1) { int S; // the motorbike's speed. scanf("%d", &S); int X; // the position on the road of the motorbike. scanf("%d", &X); option = selectOption(X, G, S, R, L); printf("%s\n",options[option]); } } //returns an int value. 0-3 int selectOption(int curPos, int lengthOfGap, int speed, int posOfGap, int lengthOfStop){ int returnValue = 3; if(curPos == (posOfGap-1)) returnValue = 2; else if (curPos > posOfGap) returnValue = 1; else if (speed < (lengthOfGap+1) && speed < lengthOfStop) returnValue = 0; else if (speed > (lengthOfGap+1)) returnValue = 1; return returnValue; }
To fix this I’m thinking of altering the options array into a 2D array instead. My mind is a bit fizzed out right now, and I don’t want to give away all of my thoughts just yet. I’ll work on this more tomorrow and we’ll see what comes out of it.
In the mean time, any thoughts of how I can remove this if-else tree or do you think I’m stuck with it?
I’m a long time follower of tinyjavacode and I’ve watched them turn out a daily snippet of code solving each of the reddit programming challenges. So, figure I’d give it a shot. Today’s challenge was to create a substitution cypher. Tinyjavacode did this already in java so I did it in c.
Check under the break to see the code and for a breakdown of it.
Original Text : Hello World.
Encrypted Text : Mjqqt%\twqi3
Decrypted Text : Hello World.
C made this encryption/decryption code pretty simple. Char values are already stored as ascii values so I took those values and added 5 to them to encrypt them. Then did the opposite to decrypt them. This has the added bonus of encrypting special characters too.
The encrypt and decrypt functions are identical except the +5 and =5 in the for loop. Step by step,
We declare our returnValue as a char pointer, which has the added benefit of acting like an array if you know how to play with it.
Allocate the memory needed to store the entire input string in our return String.
Copy the input string to our return string character for character.
Declare our iterator i.
Loop through the characters in the return string adding 5 to the ascii value of each one.
Then return the value to our driver.
All in all this was a fun program to cobble together. Biggest problem I had was allocating the memory. I forgot to do that originally and was segfaulting before I realized the mistake.
Now a comparison to tinyjavacode’s solution. You can be find it here. It should also be noted I haven’t read their description of the code, nor have I looked at their code till now.
For the encryption portion it looks like they iterate through the alphabet until they find the letter that matches the first letter of the message to be encoded. Then we use that first letter as the first part of our substitution cypher.
Only thing I’d change here is that first iteration. I think instead of the for loop we could use something like:
Problem with the above is your lose readability but you gain speed.
Next up is the decryption portion which goes beyond what I did. My version only decrypts one version which is to move the text -5. tinyjavacode’s version of the decryption has to be able to work with multiple versions of encryption since the encrypt code can encrypt in multiple ways.
Overall this was fun to work on, and I look forward to more challenges. I tip my hat to tinyjavacode for being more creative with their encryption and decryption.
Took me longer to complete this project than it should have. So, with the use of a formula I was able to get rid of that huge ugly if-else tree and turn it into a single function that I could call.
Check out the read more to see the code and to see the silly reason for the hours upon hours I spent on this code.
int determineDirection(int goalPosition, int position){
int returnValue;
if(goalPosition == position)
returnValue = 0;
else
returnValue = (goalPosition - position) / abs(goalPosition - position);
return returnValue;
}
So it’s pretty much the same set up. I changed the variable names to make them more read-able. Notice the determineDirection function at the bottom. This is the big lifter for this code. I input my current position on the grid (either x or y) and the goal position (corresponding x or y) and the method will give out a -1, 0, or 1 depending on which way the goal is compared to our current position.
We combine this number with the new directions array. By adding 1 to the corresponding x: -1, 0, 1 and y: -1, 0, 1 we get the direction we need to go from the array.
Now that we have the code explanation done, let’s talk about why it took me hours to get this code completed. To be honest, I had this implementation done in about an hour or so. After I finished it though I wanted to go a step further.
I wanted to make the program multi-threaded because... well I just wanted to. I beat my head against this problem for hours before I finally had a working solution. Then when I submitted the code the thread that found the direction and added it to an array executed flawlessy.
The thread that actually moved the character though. It did absolutely nothing. So I beat my head against the problem for another hour or so and managed to make the code pretty sleek because I thought the problem was the second thread didn’t have enough time to start up because of a 100ms time limit.
That wasn’t the problem. The problem was the environment that Codingame uses doesn’t use multiple threads. So I made a multi-threaded answer to a problem that can’t be solved with multiple threads.
I head desked pretty hard. Learned a lot from the experience, a lot of stuff I had forgotten but ugh. It sucked figuring out that all that work went to waste.
Anyways, the multi-threaded solution can be seen below. I’m not going to explain it unless someone asks me to.
For the longest time I’ve been told to avoid if statements where I can. Instead I should use polymorphic behavior to replace if statements. Replacing said if statements with polymorphism ends with code that is easier to maintain.
This idea is one I have been told and have known for quite some time but I’ve not really applied it or thought about it beyond what I just said above.
I bring them up now though because I recently joined a fun little website called codingame. The premise is that you program your way through games in order to practice your coding skills and to have fun at the same time.
I got to the second challenge which was simple enough. I’m dropped into a random position on a map 40x18 map and have to get to a random position on that map by moving in one of 8 directions. Northwest, North, Northeast, East, Southeast, South, Southwest, and West.
int main()
{
int LX; // the X position of the light of power
int LY; // the Y position of the light of power
int initialTX; // Thor's starting X position
int initialTY; // Thor's starting Y position
scanf("%d%d%d%d", &LX, &LY, &initialTX, &initialTY); //scans in all the starting data
int posTX = initialTX; //posTX keeps track of our x position.
int posTY = initialTY; //posTY keeps track of our y position.
As you can see, I have a giant if else tree to determine which direction I should go and it just looks and feels all sorts of wrong. Mind you this code passed all of this challenge’s (this is only challenge #2 by the way) tests with flying colors. However, I’d be ashamed to pass this onto someone else to review.
So, what can I do about all these if statements? Maybe I’m just too inexperienced but I don’t really see a way to fix this with polymorphism (please correct me if I’m wrong). However, I have an idea in mind to solve this with a simple algorithm and a 2d array.
Before I release my solution, what do you all think? Can this be solved with polymorphism or do you have another idea in mind?