Random Writer (Markov)

This is to implement a Markov approach to predicting what is going to happen next with using what has happened before. For example, for handwriting, if you see the letters “TH” and there is one letter left but you are not able to read it, then you could guess it could be the letter “E”, well that is kinder the idea.

So, in this assignment what is required is to read in a file, any file story etc, and then create seeds (which is a user requested input) with the next character(s) that are linked to that seed. To understand what a seed is, lets say that we have a line of text

“Hi there, my knickname is genux, and I enjoy to do software development, in many languages and operating systems, because development is just interesting!!”

and we picked a seed length of 3, so to start with the first seed is “Hi ” <- yep there is a space there!! because it has to be a length of 3, and the next character is "t" which is what is linked to the seed value "Hi ", so from the text above with a seed length of 3 you can see that there is a seed of "ent" (within the development words for example) has two choices to make for the next character either a "," or a " " and this is the random choice of where to go after this test. If you went to " " then the new seed would be "nt " which there is only one next possible seed which is "t i" and you just carry on like this. To start with this problem, I wanted to create a mapped seeds that had attached the next characters that are linked to that seed value, so it would be a

Map<Vector<char>  > theKeys

which means that we are using a map (seed is the string key) and then a vector or char(acter(s)) that are associated with that seed. So then we need to read in the value and insert into the map, so here is the way that I am using to insert a character into vector associated with the mapped seed key. What I am doing is to start with, to see if there is already a seed within the map already, if so create a vector of values that is already associated with that seed key, either or, insert the new (insertChar) into the vector and place into the map seed key (if you use the put method if will replace the previous values associated with that key).

inline void addNewChar(Map<Vector<char> > &theKeys, string seedValue, char insertChar)
{
	Vector<char> addResults;
	if (theKeys.containsKey(seedValue))
		addResults = theKeys.get(seedValue);
	addResults.add(insertChar);
	theKeys.put(seedValue, addResults);
}

the next thing is to start with reading the seed start length from the file (the readSeedFromFile method will do that and return the string of its value), then whilst there is characters left in the file keep on reading the file whilst inserting the seed and characters into the mapped variable (Map > &theKeys).

void setupKeys(Map<Vector<char> > &theKeys, ifstream &infile, int seed)
{
	// obtain the first seed value
	string seedValue = readSeedFromFile(infile,seed);
	char newChar;
	while (!infile.eof())
	{
		newChar = nextChar(infile);
		addNewChar(theKeys, seedValue, newChar);
		seedValue = seedValue.substr(1,seedValue.length()-1) + newChar;
	}
}

So after we have read in the file, we need to find the highest seeded that has the most next characters attached to it, and this what the function below does, the foreach is a iterator that will loop through all of the seed (key) values within the Map and then find the length of the next characters.

string obtainAMaxKey(Map<Vector<char> > &theKeys)
{
	int maxSeed =0;
	string maxKey="";
	Vector<char> values;
	// iterator through the map values
	foreach (string key in theKeys)
	{
		values = theKeys.get(key);
		if (values.size() > maxSeed)
		{
			maxKey = key;
			maxSeed = values.size();
		}
	}
	return maxKey;
}

the last thing is to output the Markov, stop at a word count of 2000 or if there is no more characters attached to the last seed value. So all we do is start with the seed value from above function, then just get the Vector from the seed, then pick a random number from the length of that Vector and update the seed to the next seed. As below.

void outputMarkov(Map<Vector<char> > &theKeys, string startKey)
{
	Randomize();
	int wordCount = startKey.length(), randomKey;
	Vector<char> values;
	while (true)
	{
		if (wordCount >= 2000) break;
		values = theKeys.get(startKey);
		if (values.size() ==0) 
		{
			cout << "NO MORE KEYS"; 
			break;
		}
		randomKey = RandomInteger(0,values.size()-1);
		cout << values[randomKey];
		startKey = startKey.substr(1,startKey.length()-1) + values[randomKey];
		wordCount++;
	}
}

I have attached the zip file with also the PDF file of the requirements. It will work within visual studio 2008

delegates – settings function on the fly

Delegates allow a virtual method/function (static method) to be called via a link (which is the delegated variable). I have done a post before about delegates but kinder think and also have been asked how do you link one to a class and also change the delegated function due to a user input, so here goes.

I have started with setting up what type of method that I want to be associated with the delegated variable, this will be a mathematical function of either addition or subtraction with using integer values, so we need to return a integer value and also pass in two integer parameters, so a new delegated virtual method would be

public delegate int mathsOp(int value1, int value2);

and here would be a example of a method that the delegate is able to link to, because it takes 2 integer parameters and returns a integer value

public int add(int value1, int value2)
{
	return value1 + value2;
}

so we now have the delegate declaration and also a method to be able to point to, so we now need to setup the variables, one for the actual functions (MathClass that is holding the subtraction and addition methods) and also the delegated variable theMathOp that is a delegated type.

MathClass mathFunc = new MathClass();
 
mathsOp theMathOp;

to actually set the method up on the fly, you just need to tell it where you want the delegated type to point to

theMathOp = new mathsOp(mathFunc.add);

and all is needed to call the delegated type variable, well you just call it like any other method

theMathOp(inputValue1, inputValue2);

that is about it, here is the code in full that will take in some values from the user and also the user is able to choose between addition and subtraction methods

using System;
 
namespace newDelegates
{
	// a maths holding delegated function
	public delegate int mathsOp(int value1, int value2);
 
	class MathClass
	{
		// the functions to call within the class
		public int add(int value1, int value2)
		{
			return value1 + value2;
		}
 
		public int sub(int value1, int value2)
		{
			return value1 - value2;
		}
 
	}
 
	class MainClass
	{
		public static void Main (string[] args)
		{
 
			// setup the maths class which has the functions inside to call
			MathClass mathFunc = new MathClass();
 
			mathsOp theMathOp;
 
			// there is no error checking in the inputs!!
 
			Console.Write("Please enter value 1 : ");
			int inputValue1 = Convert.ToInt16(Console.ReadLine());
			Console.Write("Please enter value 2 : ");
			int inputValue2 = Convert.ToInt16(Console.ReadLine());
 
			Console.WriteLine("Please enter maths function :");
			Console.WriteLine("1 : add");
			Console.WriteLine("2 : sub");
			int mathsInputFun = Convert.ToInt16(Console.ReadLine());
			// setup the virtual function to which ever the user wants
			switch (mathsInputFun)
			{
				case 1 : 
					theMathOp = new mathsOp(mathFunc.add); 
					break;
				case 2 : 
					theMathOp = new mathsOp(mathFunc.sub); 
					break;
				default :
					Console.WriteLine("Settings to add");
					theMathOp = new mathsOp(mathFunc.add); 
					break;
			}
 
			Console.WriteLine("Value 1= " + inputValue1 + (mathsInputFun == 1 ? " + " : " - ") 
			                  + " value 2 = " + inputValue2 + " = ");
 
			// here we call the virtual function that was setup
			Console.WriteLine(theMathOp(inputValue1, inputValue2));
		}
	}
}

and below is the output of two runs of the program, one using addition and the other using subtraction

Please enter value 1 : 3
Please enter value 2 : 2
Please enter maths function :
1 : add
2 : sub
1
Value 1= 3 +  value 2 = 2 = 5
 
second run through
 
Please enter value 1 : 5
Please enter value 2 : 2
Please enter maths function :
1 : add
2 : sub
2
Value 1= 5 -  value 2 = 2 = 3

Reflection – Calling functions

With c++ you can call functions as a reference instead of the actual name, as long as the reference is linked to the function itself (I did a post about it function pointers and also within csharp delegates)

To start with, we need to sort out what function we want to use to call, I am going to pick a function that returns a value and also passes parameters (kinder covers all aspects really), so this is going to be the function

public String addsTogether(String st1, String st2)

So to start off , lets build up the parameters to pass to the function, we have two string parameters, so we need to have a array of 2 strings.

String[] passingParameters = { new String("genux"), new String("was here")};

Now we need to setup a link to the function that we want to call, we setup a class instance with using the forName (which is the function name). Also because the function takes 2 String parameters we need to setup blank classes that are both Strings in types.

Class callingClass = Class.forName("CallMethodClass");
 
Class[] callingParameters = new Class[2];
callingParameters[0] = String.class;
callingParameters[1] = String.class;

this is the main part, this is the link, we create a Method (from the java.lang.reflect package) that links to the class function/method “addsTogether” (the function at the start of this post) and also the parameters type and length (2 strings).

Method callingMethod = callingClass.getMethod("addsTogether", callingParameters);

that is about it, all we need to do is to call the function now and that is it, so we use the Method link above variables invoke method, this takes the class that the function is wrapped within and also the parameters that we want to send to the function (method and function are kinder interchangeable) and that is about it. Since the returning value is a String (and we know this) we will need to case the returning type into that by using (String) otherwise it would be a type of Object (the base object type in java)

String result = (String)callingMethod.invoke(new CallMethodClass(), passingParameters);

Here is the source code in full (Save as CallMethodClass.java if you want to compile it up)

import java.lang.reflect.Method;
 
public class CallMethodClass {
 
	// adds together the two strings with inserting a space between them
	public String addsTogether(String st1, String st2)
	{
		return st1.concat(new String(" ").concat(st2));
	}
 
	public static void main(String[] args) {
		try
		{
			String[] passingParameters = { new String("genux"), new String("was here")};
			// setup the link to the class to call
			Class callingClass = Class.forName("CallMethodClass");
			// passing parameters to the callingClass, the method has two String parameters
			Class[] callingParameters = new Class[2];
			callingParameters[0] = String.class;
			callingParameters[1] = String.class;
			// and now setup the method to call
			Method callingMethod = callingClass.getMethod("addsTogether", callingParameters);
 
			// call the method and get the return (convert to a String)
			// pass in the parameters here, when calling (invoking) the method
			String returnValue = (String)callingMethod.invoke(new CallMethodClass(), passingParameters);
 
			// and now output the result
			System.out.println("OUTPUT : "+returnValue);
		} catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
	}
}

here is the output of the program

OUTPUT : genux was here

Life cycle

This course is in C++ each language is great to learn with but c++ is allot more fun at times since you have direct access the memory locations of variables :).

Anyway, here is the assignment 1, life cycles, I have included the full source code in the zip file attached. Life cycle, is when you have cells within a grid and the rules are (as taken from the assignment 1 PDF file within the zip file) where the neighbours are a 3 x 3 grid around the cell in question

The simulation starts with an initial pattern of cells on the grid and computes successive generations of cells according to the following rules:

  • 1. A location that has one or fewer neighbors will be empty in the next generation. If a cell was in that location, it dies of loneliness. Sad!
  • 2. A location with two neighbors remains “stable”

Adventure game

The adventure game is textural based, but the main part of the assignment is pull data from files to build up the adventure environment so that nothing as such is hard coded apart from the main options like QUIT, HELP etc.

You have different parts of the adventure game to build up, reading in of the rooms that the user will move around, the adventure objects to pick up file to read in (and place within the rooms in the adventure game) and you are also able to pick up the items as well. To start with I am going to do the reading in of the files (if present)

Here is part of the room file, it starts with the room ID number, then the small name followed by the description (finishing with “—–“) and, last but not least, is the movement options and the room ID to move to, e.g WEST 2 means if you go WEST you will end up in room ID 2


1
Outside building
You are standing at the end of a road before a small brick
building. A small stream flows out of the building and
down a gully to the south. A road runs up a small hill
to the west.
-----
WEST 2
UP 2

here is how I am reading in the main room file, the readPassEmpty is another function that will read passed any empty lines and return the first non empty string from within the file, the readInLine will read just one line at a time (with all error checking). the returnRoom is what I am going to return back to the main adventure class that will add the rooms read into a ArrayList.

String st = readPassedEmpty(rd);
if (st== null) return null;
returnRoom.roomNumber = Integer.parseInt(st);
returnRoom.roomName = readInLine(rd);
String readIn;
while(true) {
	readIn = readInLine(rd);
	if (readIn.indexOf("-----")>=0) break;
	returnRoom.roomDescription.add(readIn);
}
while (true)
{
	readIn = readInLine(rd);
	if (readIn == null) break;
	if (readIn.equals("")) break;
	returnRoom.roomMotionTable.add(getMotionTable(readIn));
}

To break the movement roomID (/options) part of the file into parts, I used the split function within the String class, you pass in a regular expression, in this case [ ]+ which means any space [ ] and + means 1 or more times e.g. if there is one space between movement or 5 then it will classes as the same thing, and if there is any options attached to the roomID e.g. you needs to have KEYS

String[] split = st.split("[ ]+");
dir = split[0];
int indexOf =split[1].indexOf("/");

reading in the adventure room objects and also the synonyms is very similar in that I either break the synonym into a regular expression searching for the “=” and thus linking the left value to the right value within a ArrayList of synonyms. The adventure objects, I just read in there values and add the objects to the required room, for example the file looks like

KEYS
a set of keys
3

where the KEYS is the object, “a set of keys” is the long description, and 3 is the roomID to place the items into.

Movement around the adventure

To move around the adventure game, the user types in the direction (or there is some hidden options) and then the adventure game will move to that required place and the way that I thought about this was to get all of the movement options within that room, see if the player has requested any of these movement options and move that player to the next room, but if there is a option/requirement (e.g. KEYS) to access that room then see if the player has them within his user objects. Else if there is no movement that the user requested just output a error and return -1 (which means no update).

private int movePlayer(String player, int roomID)
{
	AdvMotionTableEntry[] moves = advRooms.get(roomID-1).getMotionTable();
	for (int i = 0; i < moves.length; i++)
	{
		if (moves[i].getDirection().equals(player))
		{
			String keyName =moves[i].getKeyName();
			if (keyName != null)
			{
				int objectPlace = getObjectIndexUsers(keyName);
				if (objectPlace >=0)
					return moves[i].getDestinationRoom();
			} else
				return moves[i].getDestinationRoom();
		}
	}
	println("There is no way to move in that direction.");
	return -1;
}

the getObjectIndexUsers is just a function that will scan though the users objects and search for the key, if one found return that key index, else return -1 as below.

private int getObjectIndexUsers(String keyName)
{
	for (int i =0; i < userObjects.size(); i++)
	{
		if (userObjects.get(i).getName().equals(keyName))
			return i;
	}
	return -1;
}

if you download the zip file you will notice that the most of game loop is within the mainGame function, what happens in there is to

  • whilst not finished
  • display the room – short or long description – if required
  • set the room to be classed as visited (for the short/long description to be displayed)
  • check for the room is FORCED – and thus to not request the users input and move
  • If not FORCED request the users input for the movement
  • With the users request, process the request to either TAKE/DROP MOVE QUIT etc options
  • If none of the standard requested, see if it was a movement request e.g. WEST/NORTH/DOWN etc.
  • Then if the roomID = 0, the game is finished, either win/lose
  • repeat

The rest of the code is very similar in nature to the above code, looping through arrays and checking for conditions, it was a interesting game assignment I thought, I am going to do the CS106B next, which is a course that you write code in C++ (but only on a MAC/Windows PC). Shall do some posts of there assignments.

I used ArrayList to store the rooms etc into, because they allow for good access to the data in. I have included the full source code of the assignment and also the assignment PDF file within the ZIP file attached.

HTML Elements and altering them

With javascript you can alter the different elements within the HTML page, which is great when you are doing things like AJAX and you just want to alter one part of the page and not the whole page.

All you need to do is to get the element that you want to “talk” to and then alter that HTML tags element parts, so lets say that you have a HTML P tag

  <p id="hideme">

you can get that element within a variable for javascript to talk to it via

     var elem = document.getElementById("hideme");

and now you can alter all parts of that HTML P tag, e.g. the style, the inner HTML text (which is the text within the <p>innerHTML</p> tags) which gives you allot more things to do on the page that allows more of a desktop feel to the site over a static page that you need to send back and forth to the server.

Of course you cannot alter any internal parts of the HTML tag that do not exist e.g. for the HTML Input there is no innerHTML because it only has a value (the text within the input box) so if you try and do that some web browsers will error/stop/or just ignore.

Here is the full source code that will alter a HTML P style to red and also the innerHTML, and also a lower one will hide and then show the text within a HTML P tag whilst altering the link to show either “click here to hide me”/”click here to show me”, which once again helps users to now what to do.

<html>
<head>
<script language="javascript">
  function hideme()
  {
     var elem = document.getElementById("hideme");
     var elema= document.getElementById("hidemea");
 
     if (elem.style.display == "none")
     {
	elem.style.display = "block";
	elema.innerHTML = "click to hide me";
     }
     else
     {
	elem.style.display = "none";
	elema.innerHTML = "click to show me";
     }
  }
 
  function start()
  {
    var inputElem = document.getElementById("thewords");
    // you cannot alter the innerHTML of a input tag because it does not have any!!.
    // some browsers will error here because you cannot alter the innerHTML of a input tag
    //inputElem.innerHTML = "somewhere";
    // but you can alter the HTML A tag value because that is what input has
    inputElem.value = "genux was here!";
 
    var para = document.getElementById("paragraph");
    para.innerHTML = "I have changed the text within the paragraph!!!.. yeppy.. and also the colour to red ";
    // you also have access to the style(s) attached to that HTML tag, in this case the color 
    para.style.color = "red";
  }
</script>
</head>
<body>
  <input id="thewords"/>
  <a onclick="javascript:start()">Click me</a>
  <p id="paragraph">
  some text within the paragraph
  </p>
  <p id="hideme">
  hideme after the click below<br/>
  you can alter the style e.g. style.display = value<br/>
  and also alter the innerHTML - as I am altering the HTML A tag below text from hide/show me
  </p>
  <a id="hidemea" onclick="javascript:hideme()">click to hide me</a>
</body>
</html>

with using more javascript on pages, you need to have a way of keeping details of the updates on a page if you browse away from that page and come back which is where some problems could arise. So you just need to freshen up on your HTML tags and what they are capable of doing and have fun 🙂

Prototypes

Prototypes are a great thing with javascript, and they really come into there own with ajax and jQuery. A prototype basically it extends the present functional aspects. So lets say that you have a basic shape of animal (legs, head etc) and then you want to extend that basic shape with the option if the animal can fly then you can write a prototype to extend that, the prototype can either be a function or a variable so for example

// variable
animal.prototype.flyable = false;
// function
animal.prototype.canFly = function() {
     return this.flyable;
}

the “this.” means access the variables/functions within the main type (in this case it would be the animal as the main type).

in the example I am just altering some text within a HTML input tag, to start with I am creating a function (that I will extend later) and create a local (this.) variable that points to the element passed by using the document object, afterwards set the value equal to “hi from the parent”. I called it the parent because it is the main type,

  function nameing(elem)
  {
      this.theelem = document.getElementById(elem);
      this.theelem.value = "hi from the parent";
  }

then to extend this type, you start with the typename.prototype.extension_name, so the examples below will either return the value from the document element value that was setup in the “parent” / main type, and also the setText function will set the text to the document element.

  nameing.prototype.getText = function() 
  {
    return this.theelem.value;
  }

this is how I set up the object by calling new on the main type with passing in the element that I want to link to the object.

  // sets up the link with the 'thewords' id element within the html page
    var name = new nameing('thewords');

it is all very similar to other object languages, where you reference the object itself by using the “this.” syntax.

Below is the full html code that you can copy-paste into your favourite text editor and then open up in a web browser to see what you think.

<html>
<head>
<script language="javascript">
// a prototype 
  function nameing(elem)
  {
      this.theelem = document.getElementById(elem);
      this.theelem.value = "hi from the parent";
  }
 
  nameing.prototype.getText = function() 
  {
    return this.theelem.value;
  }
 
  nameing.prototype.setText = function(newText)
  {
    this.theelem.value = newText;
  }
 
 
  function start()
  {
  // sets up the link with the 'thewords' id element within the html page
    var name = new nameing('thewords');
    // since the call above will set the 'thewords' to equal "hi from the parent"
    alert(name.getText());
    // now we are setting the text
    name.setText("genux was here");
    // and again outputting the text again
    alert(name.getText());
  }
 
 
</script>
</head>
<body>
  <input id="thewords"/>
  <a onclick="javascript:start()">Click me</a>
</body>
</html>