Calculate the cross product: C# code

A method written in C# for calculating the cross product between two vectors:

  Vector3d CrossProduct(Vector3d v1, Vector3d v2)
  {
    double x, y, z;
    x = v1.Y * v2.Z - v2.Y * v1.Z;
    y = (v1.X * v2.Z - v2.X * v1.Z) * -1;
    z = v1.X * v2.Y - v2.X * v1.Y;

    var rtnvector = new Vector3d(x, y, z);
    rtnvector.Unitize(); //optional
    return rtnvector;
  }

The cross product enables you to find the vector that is ‘perpendicular’ to two other vectors in 3D space. The magnitude of the resultant vector is a function of the ‘perpendicularness’ of the input vectors.

Read more about the cross product here.

Using Generics in C#

When we write a method in C#, we often want to specify an input and a return for it. Since C# is a strongly typed language, it likes to know exactly what data type these inputs and returns are.

Let’s take an example, which takes a 2D array of data and returns a specified row as a list:

public List<string> GetRowOf2dArray(string[,] array, int rowNo)
{
    List<string> rtnlist = new List<string>();
    for (int i = 0; i < array.GetLength(0); i++)
    {
        rtnlist.Add(array[i, rowNo]);
    }
    return rtnlist;
}

This is all well and good if we only want to use strings. But what happens if, later on, we want to use the function with a list of doubles?

We might decide to create a copy of the method:

public List<double> GetRowOf2dArray(double[,] array, int rowNo)
{
    List<double> rtnlist = new List<double>();
    for (int i = 0; i < array.GetLength(0); i++)
    {
        rtnlist.Add(array[i, rowNo]);
    }
    return rtnlist;
}

Now, at the interface level, we can extract a row whether we have a matrix of doubles or of strings, and return them in the correct data type.

string[,] branchPaths = new string[5, 5];
for (int i = 0; i < branchPaths.GetLength(0); i++)
{
    for (int j = 0; j < branchPaths.GetLength(1); j++)
    {
        branchPaths[i, j] = "I am cell " + i.ToString() + ", " + j.ToString() + ".";
    }
}

var rtnList = new List<string>();
rtnList = tst.GetRowOf2dArray(branchPaths, 0);

But, we’re already running into problems. We basically had to copy and paste the GetRow…() method above, which is already bad practice. What if we want to change something, or we find there’s a bug? We’d have to make the change in every copy of GetRow…(). And what if we want to use the method with yet another data type, such as an array of integers? We’d have to keep copying and pasting for every data type.

One way around this is instead to write the method using objects as the type. Since all types inherit from the object type, we can write the method once and cast the specific data types. A very simple example is:

public bool IsEqual(object v1, object v2)
{
    if (v1 == v2) return true;
    else return false;
}

double a = 2;
double b = 3;
bool areTheyEqual = IsEqual(a, b); //returns false

However, this gives a lot of problems, which are explained in more depth here. Basically, using objects means that we lose performance due to casting, and we lose control since all data types can be casted to and from objects. What we want is a way to create a method suitable for multiple data types, but where we still can feel safe that the user won’t break our method with a strange data type.

Generics

This is solved with generics. As well as feeding in parameters to our methods, we can also tell the method what kind of data type we want to use it with.

This will already be familiar if you have worked with lists:

List<double> myList = new List<double>();

myList.Add(1.5);
myList.Add(5.232);

The bit in the angle brackets is the type – we can’t create a list without telling it what kind of data the list will contain. By writing <double>, we are saying that every item in the list will be a double. And if we wanted to create a list of strings, we don’t need to call a different method or different class, but we can still do it by calling the same class by specifying the type as string.

In short, using generics allows you to write your method once for a wide range of data types.

Back to the matrix example – in our class:

public List<T> GetRowOf2dArray<T>(T[,] array, int rowNo)
{
    List<T> rtnlist = new List<T>();
    for (int i = 0; i < array.GetLength(0); i++)
    {
         rtnlist.Add(array[i, rowNo]);
    }
    return rtnlist;
}

int[,] branchPaths = new int[5, 5];
for (int i = 0; i < branchPaths.GetLength(0); i++)
{
    for (int j = 0; j < branchPaths.GetLength(1); j++)
    {
        branchPaths[i, j] = i*100 + j;
    }
}

var rtnList = new List<int>();
rtnList = tst.GetRowOf2dArray<int>(branchPaths, 2);

T is the placeholder for the type. When the user calls the method, T will hold a data type, such as string or int. In this example, both an input (T[,]) and the return type (List<T>) have data types that must be carried by the user. The place where the user specifies the data type carried by T is in GetRowOf2dArray<T>. So when the user calls the method, they only need to specify T once. T can then be used wherever necessary throughout the method.

References

MSDN – An introduction to C# generics
MSDN – Generics (C# programming guide)

Using AutoHotKey for accelerated scrolling in Windows/Bootcamp

There exists already a third party driver for BootCamp to improve upon the terrible drivers for the trackpad in Windows provided by Apple. It’s called Trackpad++ and attempts to provide some of the key trackpad actions that Mac users have come not to be able to live without.

But, to be honest, it’s not the solution I was looking for. The accelerated scrolling does not feel anywhere as natural as on a Mac (or even my Chromebook for that matter) and many of the better shortcuts are still absent. There are some settings available in Trackpad++ but they’re too simplistic and don’t allow the level of control I feel that I need. To top it off, the free version must be reinstalled every week (a passive-aggressive technique to encourage you to pay) and I can’t bring myself to actually pay for software that doesn’t actually solve the problem I’m trying to solve. Which is a shame really.

Trackpad++ is the only software out there that attempts to completely re-write the driver, but are there any other ways of getting the trackpad’s functionality back? I’ve been investigating using AutoHotKey to simply use Apple’s driver in Windows more effectively. Two features that I miss are accessing middle-click with the trackpad – something I addressed in this post – and the other is accelerated scrolling. This is where, if you scroll quickly, the speed of scrolling also increases, making it easier to navigate long pages without having to use the scroll bar. Done right, as on OSX and ChromeOS, it feels very natural and you don’t even realise that the scroll is accelerated. Get used to this and move back to Windows with its non-accelerated scrolling, and it feels like you’re browsing the web through treacle. This is very annoying!

With my perceived failure of Trackpad++ in solving this problem, my search has yielded an alternative, using AutoHotKey.

http://www.autohotkey.com/board/topic/48426-accelerated-scrolling-script/

Download the ZIP file and extract it. There is an EXE if you don’t have AutoHotKey installed – it’s as easy as running this EXE to get accelerated scrolling. There is also the AHK source file that you can run with AHK – this is the version I recommend if you want to tweak the code.

Thoughts? It still doesn’t feel amazing – the acceleration seems to kick in unpredictably, like only a small difference in scrolling speed will take you between half a page down, and to the bottom of the page. If using BootCamp, I recommend going into the mouse settings in the control panel, and setting the scroll wheel to scroll 1 line per notch, otherwise it feels far to fast. It also lacks the ‘momentum’ on ChromeOS/OSX (where the page keeps moving and gradually slows down when you have stopped scrolling).

But the fact that it is an AHK file means that I can play with it and improve it. Out the box, it is already quite acceptable, and I’m looking forward to finding the time to make it work even better. Added to the fact that AHK is in principle much safer than allowing someone’s third party drivers to worm its way into the core of your fragile Windows system, this is definitely the path I would sooner recommend.

A trackpad middle-click hack for Bootcamp/Windows using AutoHotKey

A great feature of both my Mac and my Chromebook is that middle-clicks are built into the trackpad by tapping with 3 or 4 fingers at once. But in Bootcamp (and with most Windows trackpads too) there is no equivalent to a triple-finger tap built into the drivers. Among many uses, the middle click is a dead easy way of closing tabs in Chrome without worrying about that fiddly tiny little close button – a feature I miss when using Windows.

To solve this, it’s AutoHotKey to the rescue! Credit to Lifehacker reader Nakul – I have a slightly modified the script to turn a double-right-click into a middle click. Note that this might not be suitable if you use applications that have specific actions for double-right-clicks, but for the vast majority of people this shouldn’t be an issue.

~RButton::
If (A_PriorHotKey = A_ThisHotKey and A_TimeSincePriorHotkey < 500)
{
Click middle
}
Return

Simply install AutoHotKey, right click on the notification icon by the clock, click ‘Edit This Script’ and paste the above code. Save the notepad file and then reload the script.

The way that the script works is that, whenever the right mouse button is pressed, the code on the second line is called. If the code is called twice in a row, with 500ms between each call, then it simulates a middle-click. You can change the 500 value to a higher or lower value (in milliseconds) if you prefer.

To use the script with a trackpad, do a two-finger tap (as you would normally do for a right-click) twice quickly. It might make the right-click menu appear, but the second right-click should make it hide again.

Create keyboard shortcuts for coding in C# using AutoHotKey

AutoHotKey is a remarkably useful piece of free software which allows you to automate any repetitive keyboard or typing task. It effectively allows you to program any key, or any combination of keys, to any command of your choosing.

Here, I will show how to use AutoHotKey to make writing C# code a little faster and easier.

Continue reading Create keyboard shortcuts for coding in C# using AutoHotKey