Sunday, December 18, 2016

JavaScript - Sum of the first X prime numbers

I recently had a programming challenge where I had to find the sum of the first X prime numbers in JavaScript in a slightly compressed format, and couldn't find anything decent online.

So I coded this.


It could be far better, although the challenge was timed :P

Thanks to The Polyglot Developer for their "isPrime" function :)

Wednesday, November 23, 2016

A Textbox that only allows numbers

Since this seems so hard to do... An actual working example :)

Usage HTML: <input type="text" onkeypress="return isNumericKeyPress(event.keyCode);" onpaste="isNumericPaste(this);" />

OR

ASP.NET: <asp:textbox ID="txtNumsOnly" runat="server" onkeypress="return isNumericKeyPress(event.keyCode);" onpaste="isNumericPaste(this);"></asp:textbox>

Demo Type or paste something:

Samples
- [email protected]#
- Test
- Test1
- 1a2b3c

Saturday, October 29, 2016

C# - Finding the Median value of a List

I love using Lists in C#. Unfortunately, the List class lacks some functionality - Like finding the median value in a set.

Definition: The median is the value separating the higher half of a data sample, a population, or a probability distribution, from the lower half. In simple terms, it may be thought of as the "middle" value of a data set. For example, in the data set {1, 3, 3, 6, 7, 8, 9}, the median is 6, the fourth number in the sample. The median is a commonly used measure of the properties of a data set in statistics and probability theory.

Examples:

1.) If there is an odd number of numbers, the middle one is picked. For example, consider the set of numbers:
1, 3, 3, 6, 7, 8, 9
This set contains seven numbers. The median is the fourth of them, which is 6.

2.) In the data set:
1, 2, 3, 4, 5, 6, 8, 9
The median is the mean of the middle two numbers: this is (4 + 5) ÷ 2, which is 4.5.
- Median on Wikipedia

So - Here's some code to do it :)

    class Program
    {
        static void Main(string[] args)
        {
            List<double> exampleOne = new List<double> { 1, 3, 3, 6, 7, 8, 9 };
            List<double> exampleTwo = new List<double> { 1, 2, 3, 4, 5, 6, 8, 9 };
            List<double> exampleThree = new List<double> { 0, 1, 2, 4, 6, 5, 3 };
            double medianOne = exampleOne.Median();
            double medianTwo = exampleTwo.Median();
            double medianThree = exampleThree.Median();
            Console.WriteLine(medianOne); // 6
            Console.WriteLine(medianTwo); // 4.5
            Console.WriteLine(medianThree); // 3
            Console.ReadLine();
        }
    }

    public static class ListExtensions
    {
        public static double Median(this List<double> inputList)
        {
            double[] xs = inputList.ToArray();
            Array.Sort(xs);
            return xs[xs.Length / 2];
        }
    }