Tag Archives: C#

Fun with doubles!

The following code, though at first glance should reach an end, in reality it's an infinite loop.

double d = 2.0;
while (d != 0.0)
{
    Console.WriteLine(d);
    d = d - 0.2;
}

Logically thinking, the sequence should look like this:

2
1,8
1,6
1,4
1,2
1
0,8
0,6
0,4
0,2

Yet when executing this you'll notice something rather different. The actual output is:

2
1,8
1,6
1,4
1,2
1
0,8
0,6
0,4
0,2
2,77555756156289E-16
-0,2 
-0,4

This happens because floating points are not very precise, all numbers you work with are represented as bits, but the number 0.2 is not precisely represented, so you do not get precisely 0.2. If you'd perform 0,2000000000000000000000000000000000000001 - 2, you'd indeed end up a bit above zero, thus the variable will never hold exactly zero.

Simple prime check


        public static bool isPrime(int num)
        {

            if (0 == num % 2 && 2 != num)
            {
                return false;
            }
            int factor = 3;
            while (factor <= num / factor)
            {
                if (0 == num % factor)
                {
                    return false;
                }
                factor += 2;
            }
            return true;
        }

Code-Snippet: grid products!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace multidimensional_array_search
{
    class Program
    {
        static int[,] multidim;
        static void Main(string[] args)
        {
            multidim = new int[20, 20];
            readInt();
         //   printArray();
            Console.WriteLine(findLargerstProduct());
            Console.ReadKey();
        }

        static void readInt()
        {
            var reader = System.IO.File.ReadAllLines(@"D:\numbers.txt");
            for (int i = 0; i < 20; i++)
            {
                var numbers = reader[i].Split(' ');
                for (int k = 0; k < 20; k++)
                {
                    multidim[i, k] = int.Parse(numbers[k]);
                }
            }

        }

        static void printArray()
        {
            for (int i = 0; i < 20; i++)
            {
                for (int k = 0; k < 20; k++)
                {
                    Console.Write(multidim[i, k]+ " ");
                }
                Console.WriteLine();
            }

        }


            
        static int findLargerstProduct()
        {
            var highestProduct = 0;
            for (int i = 0; i < 20; i++)
            {
                for (int k = 0; k < 20; k++)
                {
                    var downward = checkDownward(i, k);
                    if (downward > highestProduct)
                    {
                        highestProduct = downward;
                    }
                    var horizontalRight = checkHorizontalRight(i, k);
                    if (horizontalRight > highestProduct)
                    {
                        highestProduct = horizontalRight;
                    }
                    var rightDown = checkRightDown(i,k);
                    if (rightDown > highestProduct)
                    {
                        highestProduct = rightDown;
                    }
                    var leftDown = checkLeftDown(i, k);
                    {
                        if(leftDown > highestProduct)
                        {
                            highestProduct = leftDown;
                        }
                    }
                }
            }

        

            return highestProduct;
        }

        #region checkArrayLogic
        public static int checkLeftDown(int x, int y)
        {
            var product = 1;

            if (x + 4 < 20 && y - 4 > 0)
            {
                for (int i = 0; i < 4; i++)
                {
                  //  Console.Write(multidim[x + i, y - i] + " ");
                    product *= multidim[x + i, y - i];
                }
            }

            return product;
        }

        public static int checkRightDown(int x,int y)
        {
            var product = 1;

            if (y + 4 < 20 && x + 4 < 20)
            {
                for (int i = 0; i < 4; i++)
                {
                    product *= multidim[x+i, y + i];
                }
            }

            return product;
        }


        public static int checkHorizontalRight(int x, int y)
        {
           var product = 1;

            if (y + 4 < 20)
            {
                for (int i = 0; i < 4; i++)
                {
                    product *= multidim[x, y + i];
                }
            }

            return product;
        }

        public static int checkDownward(int x, int y)
        {
            var product = 1;

            if (x + 4 < 20)
            {
                for (int i = 0; i < 4; i++)
                {
                    product *= multidim[x + i, y];
                }
            }

           

            return product;
        }


        #endregion
    }
}

Circular primes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace ConsoleApplication37
{
    class Program
    {
        static List<int> primes;
        static int circularPrimes;
        static void Main(string[] args)
        {

            // A CIRCULAR PRIME IS A PRIME WHOSE DIGITS, ROTATED, ALWAYS MAKE A NEW PRIME

            // Find all primes below one million
            // Find all primes that can be permuted into other primes
            // Delete every non-circular-prime from the list.
            
            // STEP1: CREATING THE PRIMES
            primes = new List<int>();
            circularPrimes = 0;
            for (int i = 2; i < 1000000; i++)
            {
                if (isPrime(i))
                    primes.Add(i);
            }

            //STEP2: Check each prime on circularity by permuting it.
            foreach (var prime in primes)
            {
                if (circulateToPrime(prime))
                {
                    circularPrimes++;
                    Console.WriteLine(circularPrimes.ToString());
                }
            }

            Console.ReadKey();
        }

        public static bool circulateToPrime(int prime)
        {
            // Write an algorithm to circulate any digit number!
            bool isCircularPrime = true;
            var numLength = prime.ToString().Length;
            var currentNumber = prime;
            char[] digits = prime.ToString().ToCharArray();

            List<int> intDigits = new List<int>();
            int _Numbers = intDigits.Count;
            int[] tempDigits = new int[numLength];

            foreach (char c in digits)
            {
                intDigits.Add(int.Parse(c.ToString()));
            }

            // DIGITS HAVE BEEN ADDED TO AN ARRAY, NOW WE CIRCULATE THEM AND CHECK THEM FOR THEIR PRIMENESS!
            // as long as the circularNumber == prime, keep looping. Otherwise break for performance

            // the max loop we have to do is the permutation of the number. (combination theory!)
            if (numLength > 1) // if(numlength > 1)!
            {
                for (int i = 0; i < numLength-1; i++) // amount of cycles needed
                {
                    // shuffle all the numbers!
                    for (int k = 0; k < intDigits.Count-1; k++)
                    {
                        tempDigits[k] = intDigits[k+1];
                    }


                    tempDigits[intDigits.Count-1] = intDigits[0];
                    intDigits.Clear();


                    foreach (var ix in tempDigits)
                    {
                        intDigits.Add(ix);
                    }

                    // Now transform this array into an actual number

                    String _t = "";
                    foreach (int x in intDigits)
                    {
                        _t += x.ToString();
                    }

             //       Console.WriteLine(_t);
            //        Console.ReadKey();
                    if (!isPrime(int.Parse(_t)))
                        isCircularPrime = false;

                }
            }


            return isCircularPrime;
        }

        public static bool isPrime(int num)
        {

            if (0 == num % 2 && 2 != num)
            {
                return false;
            }
            int factor = 3;
            while (factor <= num / factor)
            {
                if (0 == num % factor)
                {
                    return false;
                }
                factor += 2;
            }
            return true;
        }

    }
}

Determine location on Windows Phone 7.1

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device;
using System.Device.Location;
using System.Xml.Linq;
namespace Reverse_Geocoding_Blog
{
    public partial class MainPage : PhoneApplicationPage
    {

        GeoCoordinateWatcher geoLocWatcher;
        public MainPage()
        {
            InitializeComponent();
        }

        private void cmdGetLoc_Click(object sender, RoutedEventArgs e)
        {
            // create an object of GeoCoordinateWatcher to ask data from your device
            geoLocWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
            {
                MovementThreshold = 20
            };

            //create the event handlers.
            geoLocWatcher.PositionChanged += this.geoLocWatcher_PositionChanged;
            geoLocWatcher.StatusChanged += this.geoLocWatcher_StatusChanged;
            geoLocWatcher.Start();
        }

        private void geoLocWatcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    // location is unsupported on this device
                    MessageBox.Show("This device has no support for Geopositioning");
                    break;
                case GeoPositionStatus.NoData:
                    // When no data can get queried back
                    break;
            }
        }

        private void geoLocWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            // Now we want to retreive the data from our device
            var data = e.Position.Location;
            var lat = data.Latitude.ToString();
            var lon = data.Longitude.ToString();
            // This is all the data we need to determine our location! We can get extra data out of this such as our Altitude and Speed.
            reverseGeoCode(lat, lon);


        }


        #region reverseGeoCoding
        private void reverseGeoCode(string lat, string lon)
        {

            // retrieve formatted adress given a lat and long
            var baseUri = "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";

            string requestUri = string.Format(baseUri, lat, lon); // create a new string of the baseUri with {0} and {1} defined by the lat and lon variable.
            var webClient = new WebClient();
            webClient.DownloadStringAsync(new Uri(requestUri)); // We create an asynchronous request - we are relying on a webservice and don't want to block the thread!
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted); 
           

        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            var xmlElement = XElement.Parse(e.Result);
            var status = (from elm in xmlElement.Descendants()
                          where elm.Name == "status"
                          select elm).FirstOrDefault();

            if (status.Value.ToLower() == "ok")
            {
                var res = (from elm in xmlElement.Descendants()
                           where elm.Name == "formatted_address" // query out the formatted address from the returned results.
                           select elm).FirstOrDefault(); // If you look in the retrieved results (an xml file), you will see that the adress is stored in the first entry of "formatted_address".

                txtLocation.Text = res.Value.ToString();
            }
            else
            {
                // this implies that an adress has not been found. (The result queried back did not state any village, or other location information)        
            }

        }
        #endregion
    }
}

And XAML

<phone:PhoneApplicationPage 
    x:Class="Reverse_Geocoding_Blog.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Content="Get Location" Height="72" HorizontalAlignment="Left" Margin="0,6,0,0" Name="cmdGetLoc" VerticalAlignment="Top" Width="450" Click="cmdGetLoc_Click" />
            <TextBlock Height="31" HorizontalAlignment="Left" Margin="12,84,0,0" Name="txtLocation" Text="Location" VerticalAlignment="Top" Width="426" />
        </Grid>
    </Grid>
 
    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

Error LNK2038 (Source SDK)

When creating a MOD for a source game using a more recent version of Visual Studio (2010 or 2012), you might encounter a problem described in the image below.

To fix this problem, right click on server_hl2mp (or client if that's where the problem occurs!). Next click on properties -> Configuration properties -> C/C++ -> Preprocessor.
On the first line named "Preprocessor definitions" add the following line: "_ITERATOR_DEBUG_LEVEL=0" (without quotation marks). This fixed the problem for me, alternate solutions can be found on steamforums and other general coding forums such as stackoverflow. Depending on your version of visual studio, this solution might not work for you but it's surely worth a try as it only takes you a few seconds.

Why the loops, mister Fibonacci?

When people write a fibonacci sequence, they often want to write a loop and use an array to generate the sequence up to a certain number n.

Now this is a fine way of doing it, and I don't see anything wrong with it, but when you ask these people to write a program, that returns them the "nth fibonacci number", they often stick to this strategy.

For example, asking them to return the nth fibonacci number, you often encounter the following:

        public int getFibAtPost(int pos)
        {
            fibRow.Add(0);
            fibRow.Add(1);

            for (int i = 1; i < 100; i++)
                fibRow.Add(fibRow[i] + fibRow[i - 1]);

            return fibRow[pos];

        }

Not only is this a memory hungry way of doing it, another problem that could come up is "what if the fibonacci number we asked for lies outside of this range?". Well, there is an easy fix for that, keep looping untill array[pos] is filled etc..

Yet there is a much easier way of doing it, that doesn't require you to even use a loop, all you need to have is some knowledge of mathematics. Or, if you're reading this, the skills to copy-paste.

        public double getFibPos(int i)
        {

            var omega = 1 + Math.Sqrt(5);
            var phi = 1 - Math.Sqrt(5); ;
            var theta = Math.Round((Math.Pow(omega, i) + Math.Pow(phi, i)) / (Math.Pow(2, i) * Math.Sqrt(5)));
            return theta;
        }

The formule used in the method posted above is actually a rather famous one, by Jacques Philippe Marie Binet, and hence known as Binet's formula or Binet's Fibonacci number formula.

Binnet's Formula

Read text from local files

When you have a text file added to your solution with, let’s say a list of words and you want to parse this in Windows Store applications, you can not do this in the conventional way anymore. But luckily, WinRT provides us with an API to get quick access to these files.

To access the words.txt file, we first need to add the namespace “using Windows.Storage;” to the top of our project.
Once we have done this, we can now access the API to load files that are stored within our application.
Make sure you have set the build action on the words.txt file to content, then, create a method to load the content from the file. Make sure that this method is async.

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
          

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/words.txt"));
            var lines = await FileIO.ReadLinesAsync(file);

            foreach (var word in lines)
            {
               var _x = new Windows.UI.Popups.MessageDialog(word);
               await _x.ShowAsync();
            }

        }

And there we go, a quick and easy way to read files from local content.

Behind the scenes: Switch statement

Today we are going to look at one of C#’s language features, namely the Switch statement. Though this may seem straight forward, you may be surprised by the internal workings of this seemingly ‘trivial’ operation.

There are different ways of switching, let’s look at the most trivial one of them first.

public static void SwitchSequence(int x)
{
      switch (x)
      {
       case 1: Console.WriteLine("one");
       break;

       case 2: Console.WriteLine("two");
       break;

       case 3: Console.WriteLine("three");
       break;
    }
}

Understanding this is basic, but let’s look at what the compiler generated using IL DASM.

As you can clearly notice the br.s is our check command, to see if the input matches the possible case. Next you have IL_0019, IL_0026, IL_0033 that respectively refer to case 1, 2, 3 and point to the location to load the string according to that case before printing it (which is obviously a void operation, it does not return anything).

When we look to a more complex switch-statement thought, this is, a switch where the case numbers do not follow up in a nice sequential order with gaps here and there, the IL code starts to look mutated.

public static void SwitchNoSequence(int x)
{
      switch (x)
       { 
         case 11: Console.WriteLine("Eleven");
         break;

         case 14: Console.WriteLine("Fourteen");
         break;

         case 17: Console.WriteLine("Seventeen");
         break;
       }   
}

This will already make the IL code look slightly different:

This looks quite a bit different from what we had earlier.

The most frequent new instruction here is first located at “IL_0006” beq.s, a branch-equal command. This is comparably with the “If- else if” commonly found in programming languages.

What happens when the switch-casing does not follow up in a sequential order is the switch being translated to the If-else if structure we see here, done by the compiler.

So we could actually write this same piece of code using just If-Else if in C#.

This would give us this:

public static void SwitchNoSequence(int x)
{

    if (x == 11)
    {
        Console.WriteLine("Eleven");
    }
    else if (x == 14)
    {
        Console.WriteLine("Fourteen");
    }
    else if (x == 17)
    {  
        Console.WriteLine("Fourteen");
    }
}

Using a switch is much more convenient though, especially for a larger number of possible entries.

And finally we’ll look at a switch using strings instead of integers.

Let’s take the following piece of code:

public static void SwitchString(string s)
{
    switch (s)
    { 
       case "Hello":
           Console.WriteLine("Hello there");
           break;

       case "World":
           Console.WriteLine("Well hello world");
           break;
    }   
}

You have string input, which will then be checked against the different options in the switch case, and Console.WriteLine will be called if it matches.

After we used IL DASM again, this is what we get.

Bool [mscorlib]System.String::op_Equality(string,string) is the new function that gets called here. Obviously is the Equals method on the string, which returns a Boolean value (either true or false). If the first Boolean check comes back as true, it will branch of to instruction IL_0022 where we find the string that has to be printed using Console.WriteLine();

This way of dealing with switches is quite similar to the previous one, where we branched off after an integer check.

ArrayList collection in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArrayList
{
    class arrayList<T>
    {

        private T[] _ar;

        private int originalSize;
        private int capacity; // size of the ArrayList
        private int elements; // elements in the ArrayList

        
        public arrayList()
        {
            originalSize = 10;
            capacity= 10;
            elements = 0;
            _ar = new T[capacity]; // use a default size of 10
            
        }

        public arrayList(int size)
        {
            originalSize = size;
            capacity = originalSize;
            elements = 0;
            _ar = new T[capacity]; // use a default size of 10
        }

        #region getters

        public int getCapacity()
        {
            return this.capacity;
        }

        public int countElements()
        {
            return this.elements;
        }

        #endregion

        public void Add(T item) // returns boolean
        {
            checkArray();

            _ar[elements] = item;
            elements++;   
        
        }

        public void Add(IEnumerable<T> collection)
        {
            foreach (T _T in collection)
            {
                this.Add(_T);
            }
        }



        public void Clear()
        {
            for (int i = 0; i < elements; i++)
                _ar[i] = default(T);
        }

        public bool Contains(T item)
        {
            bool Contains = false;

            for (int i = 0; i < elements; i++)
            {
                if (_ar[i].ToString() == item.ToString())
                {
                    Contains = true;
                    break;
                }
            }

            return Contains;
        }

        private void checkArray()
        {
            if (elements == capacity)
            {
                T[] _ar2 = new T[originalSize + capacity];
                for(int i = 0; i < _ar.Length; i++)
                {
                    _ar2[i] = _ar[i];
                }

                capacity = _ar2.Length;
                _ar = _ar2;
                // nieuwe array
            }
        }

        public void RemoveAll()
        {
            _ar = new T[capacity];
            elements = 0;
        }

        public void Remove(int Index)
        {
            // remove the item at the specified Index

            for (int i = Index; i < elements - 1; i++)
            {
                _ar[i] = _ar[i + 1];
            }

            _ar[elements - 1] = default(T);
            elements--;
        }

        public int getIndex(T item)
        {
            //returns the index of the first occurance of this Item.
            int index = -1;
            for (int i = 0; i < elements; i++)
            {
                if (_ar[i].ToString() == item.ToString())
                {
                    index = i;
                    break;
                }
            }

            //returns -1 if the index isn't found
            return index;

        }

        public bool set(int index, T item)
        {
            // replaces the item at the current index with the new item
            // returns true if the Set was a success.
            bool boolean = false;
            try
            {
                _ar[index] = item;
                boolean = true;
            }
            catch (Exception ex)
            {
                boolean = false;
            }

            return boolean;
        
        }

        public void Randomize()
        {
            
        }

        
        
    }
}