So according to my website stats people are ending up on this site after looking for the keywords “check if triangle contain the origin” (yeah I know that’s not good English but it’s what people enter into the search engine), no doubt looking for help with Project Euler Problem #102! (warning that link contains a solution to the problem; don’t click if you want to solve it yourself). However maybe they just want something to check a point and a triangle and see if the triangle encompasses the point. So I went a head and extracted my function for testing whether a triangle encompasses a point from my Project Euler solution and translated it to f# and cleaned it up a bit.
This function uses the half-plane test to check if a triangle contains a point (said point could be the origin if one wants.) this method could be extended for n-polygon shapes but as provided it’s limited to triangles.
Code provided in f#.
#light
open System
type Point(x:float, y) =
member p.X = x
member p.Y = y
let Origin = new Point(0.0,0.0)
let Sign (p1:Point) (p2:Point) (p3:Point) =
(p1.X - p3.X) * (p2.Y - p3.Y) - (p2.X - p3.X) * (p1.Y - p3.Y)
let CheckPoint pt p1 p2 p3 =
let test1 = (Sign pt p1 p2) < 0.0
let test2 = (Sign pt p2 p3) < 0.0
let test3 = (Sign pt p3 p1) < 0.0
((test1 = test2) && (test2 = test3))
let A = new Point(-340.0,495.0)
let B = new Point(-153.0,-910.0)
let C = new Point(835.0,-947.0)
let X = new Point(-175.0,41.0)
let Y = new Point(-421.0,-714.0)
let Z = new Point(574.0,-645.0)
Console.WriteLine (CheckPoint Origin A B C)
Console.WriteLine (CheckPoint Origin X Y Z)
Tags: f#, Math
Posted in Math, Software | Comments (0)
So I found myself working on a small personal project in F# to gain more familiarity in the language when I decided the best way to solve my data storage needs would be a small local database file. So I went looking for ways to get sqlite into F# projects and couldn’t find a decent example. So I’ve started going through an example project in c# and trying to make it work in F#. I’ve got database creation and item insertion working so I figured what the heck I’ll post it here to make up for all of the posts I haven’t been writing lately.
I’m using the sqlite-net class from here compiled as a dll in a c# project. I’m then using that dll in my F# project. So if you’re looking for a pure f# implementation you at the wrong place. However its all il code at that level anyway. So armed with this dll I then create a f# type that looks a little something like this:
type Site (url:string) =
let mutable id = new int()
let mutable BD = ""
let mutable site = url
let mutable shown = false
let mutable exemplarcontributor = false
[<PrimaryKey>] [<AutoIncrement>]
member x.ID with get() = id
and set v = id <- v
member x.ExemplarContributor with get() = exemplarcontributor
and set v = exemplarcontributor <- v
member x.Shown with get() = shown
and set v = shown <- v
member x.BreakDown with get() = BD
and set v = BD <- v
[<Indexed>]
member x.Site with get() = site
and set v = site <- v
member x.Url = url
new() = Site "www.google.com"
now I should mention that this is directly from the test applet I’ve been using to get sqlite to work. as such it can probably be cleaned up quite a bit. Basically we have a URL and a few other details of a site and a few attributes. The ID is a primary key and auto incremented as shown above, note that this NEEDS to be put on the member declaration not the actual id. Also note that we need getter and setters on anything that we want to show up in the database, as such we need to make everything mutable. I’m still looking to see if there is another way to do that but this works for now. Anyways, armed with this type we can go to the next section, creating a database type that we’ll be adding custom stuff to in addition to inheriting from SQLiteConnection. And that looks like:
type Database (path) =
inherit SQLiteConnection(path)
member this.Setup = base.CreateTable<Site>()
Pretty basic right? All we’ve done is give the Database type a setup method that can be used to add the Site table to the database. If the database already has a Site table it’s not replaced but a safety check could easily be added to this method to make sure we don’t overwrite anything; however this is a throw away app and I’m not going to add it. Next we start doing stuff with these types. In fact we do this:
let D = new Database("test.sqlitedb")
D.Setup |> ignore
let s = new Site "www.google.com"
D.Insert(s) |> ignore
D.Commit|>ignore
Here we create a Database that we call D, call its setup method and pipe that to ignore (it returns an int to indicate errors, but I don’t want to catch it). Then we create a new instance of the Site type, do an insert again piping it to ignore and finally we commit everything and pipe that to ignore. And that’s it. We have a simple program that builds a useless database and adds a single entry to it. If you run this program multiple times it’ll just keep adding instances of Site to the database because it doesn’t overwrite the file.
Tags: .net4, f#, fsharp, programming, sqlite
Posted in Software | Comments (0)
So I was wandering the internet when I found an article about steganography, which is the art of hiding something in plain sight. Such as hiding a message inside a picture. Specifically the least significant bit method where you take the RGB color values of the pixel and set them based off a message in binary your encoding. So I figured I’d work something up and see if I could do that. This is a first attempt and it only encodes the message, right now it’ll truncate it if it doesn’t have enough pixels to work with or if the message length in binary isn’t divisible by three. Obviously this is a first attempt and a very simple one at that.
So basically you give it a picture and a text file and it reads the text file as a single string, converts it to binary then for each pixel it sets each of the RGB values based off the binary message value for that position. In this example if the binary message is odd for this position we set the color to an odd number (in effect setting the least significant bit to 1) else we make sure its an even number.
I have a few plans for expanding this project. It would be nice to decode the messages first of all, it would also be nice to have some options for encoding such as skipping a certain number of pixels between parts of the message, Only using certain color channels etc. But for now this is what I have.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Steganography
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.CheckPathExists = true;
op.CheckFileExists = true;
op.Filter = "JPG image |*.jpg";
op.ShowDialog();
textBox1.Text = op.FileName;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
Preview.ImageLocation = textBox1.Text ;
}
catch
{
}
}
private void BrowseMessage_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.CheckPathExists = true;
op.CheckFileExists = true;
op.ShowDialog();
textBox2.Text = op.FileName;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Your image will be saved as " + textBox1.Text +".new");
//Get message as a binary string;
string message = LoadMessage(textBox2.Text);
string binmessage = "";
foreach (char letter in message.ToCharArray())
{
binmessage += Convert.ToString(letter, 2);
}
//get bitmap of image.
Bitmap bitm = (Bitmap)Preview.Image.Clone();
int mPosition = 0;
//Embed message
#region embed
for (int height = 0; height < bitm.Height; height++)
{
for (int width = 0; width < bitm.Width; width++)
{
if (mPosition + 3 <= binmessage.Length)
{
Color pixelColor = bitm.GetPixel(width, height);
int R = int.Parse(pixelColor.R.ToString());
int G = int.Parse(pixelColor.G.ToString());
int B = int.Parse(pixelColor.B.ToString());
int m1 = int.Parse(binmessage[mPosition].ToString());
mPosition++;
int m2 = int.Parse(binmessage[mPosition].ToString());
mPosition++;
int m3 = int.Parse(binmessage[mPosition].ToString());
mPosition++;
if (m1 % 2 == 0)
{
if (R % 2 != 0 && R > 0)
{
R -= 1;
}
else
{
R += 1;
}
}
else
{
if (R % 2 != 1 && R > 0)
{
R -= 1;
}
else
{
R += 1;
}
}
if (m2 % 2 == 0)
{
if (G % 2 != 0 && G > 0)
{
G -= 1;
}
else
{
G += 1;
}
}
else
{
if (G % 2 != 1 && G > 0)
{
G -= 1;
}
else
{
G += 1;
}
}
if (m3 % 2 == 0)
{
if (B % 2 != 0 && B > 0)
{
B -= 1;
}
else
{
B += 1;
}
}
else
{
if (B % 2 != 1 && B > 0)
{
B -= 1;
}
else
{
B += 1;
}
}
Color pc = Color.FromArgb(R, G, B);
bitm.SetPixel(width, height, pc);
}
else
{
}
}
}
#endregion embed
bitm.Save(textBox1.Text + ".new");
}
private string LoadMessage(string p)
{
string RetValue = "";
StreamReader sr;
sr = File.OpenText(p);
RetValue = sr.ReadToEnd();
sr.Close();
return RetValue;
}
}
}
Tags: c#, csharp, programming
Posted in General, Software | Comments (0)
Here are some random snippets of f# code I had lying around. mostly simple stuff for basic stats calculations. Not the most complex stuff but maybe its useful to somebody trying to learn f#.
// Learn more about F# at http://fsharp.net
open System
open System.Net
//basic arithmetic mean
let Mean (x:List<float>) =
let sum = x |> Seq.sum
let items = x |>Seq.length
sum / (float items)
//basic variance method
let Variance x =
let m = Mean x
let deviation =
x
|> Seq.map (fun x -> Math.Pow((x-m), 2.))
|> Seq.toList
Mean deviation
//Calculates standard deviation using above variance method
let StandardDeviation x =
Math.Sqrt(Variance x)
//recursively calculates the factorial of x
//will overflow long before running into recursion limits
//at larger values it will wrap back around to 0
let rec Factorial x =
if x = 0I then
1I
else
x * Factorial(x-1I)
//calculates combinations
let Combinations n r =
(Factorial n)/ ((Factorial r)*(Factorial (n-r)))
//calculates permutations
let Permutations n r =
(Factorial n)/ (Factorial (n-r))
//uses Euclids formula for the greatest common divisor
let rec GCD a b =
if b = 0UL then
a
else
GCD b (a%b)
//returns an array representing the binary version of x
let toBinary (x:uint64) =
let rec con (x:uint64) r =
if x = 0UL then
r
else
con (x/2UL) ([x%2UL] @ r)
con x []
// gets ticker price using yahoo
let GetTickerPrice (ticker:string) =
let url =
"http://download.finance.yahoo.com/d/quotes.csv?s="+
ticker+
"&f=sl1d1t1c1ohgv&e=.csv"
let wc = new WebClient()
let info = wc.DownloadString(url).Split([|','|])
float info.[1] // info.[1] is the current price will return 0.0 on invalid ticker
Tags: .net4, f#
Posted in Software | Comments (0)
Because there’s nothing like running through a town with a sledgehammer destroying anything that moves…
Definitely one of the most entertaining games, the vehicles handle well, and there is a lot of weapons to choose from when planning how your going to attack the EDF. Plus you get a rifle that eats people alive!

Posted in General, Software | Comments (0)