Palindrome in Python

Solution to Project Euler problem 4

def isPalindrome(s):
    i = 0
    j = len(s) - 1
    
    while i < j:
        if s[i] != s[j]:
            return False
        i = i + 1
        j = j - 1 
    return True

maxVal = 0
for i in range(100, 1000):
    for j in range(100, 1000):
        prod = i * j
        prodStr = str(prod)
        if isPalindrome(prodStr) and prod > maxVal:
            maxVal = prod

print(maxVal)

Palindrome in Ruby

Solution to Project Euler problem 4

def isPalindrome(s)
  i = 0
  j = s.length - 1
  
  while i < j
    if s[i] != s[j]
      return false
    end
    i = i + 1
    j = j -1
  end
  
  return true
end

max = 0
(100..1000).each do |i|
  (100..1000).each do |j|
    prod = i * j
    prodStr = prod.to_s
    if isPalindrome(prodStr) && prod > max
      max = prod
    end
  end
end

puts(max)

Palindrome in Go

Solution to Project Euler problem 4

package main

import "fmt"

func isPalindrome(s string) bool {
	i := 0
	j := len(s) - 1
	
	for (i <= j) {
		if s[i] != s[j] {
			return false
		}
		i = i + 1
		j = j - 1
	}
	return true
}

func main() {
	var max int
	for i := 100; i < 1000; i++ {
		for j := 100; j < 1000; j++ {
			prod := i * j
			prodStr := fmt.Sprintf("%d", prod)
			if isPalindrome(prodStr) && prod > max {
				max = prod
			}
		}
	}
	println(max)
}

Palindrome in C#

Solution to Project Euler problem 4

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

namespace problem4
{
    class Program
    {
        static bool isPalindrome(string x)
        {
            int i = 0;
            int j = x.Length - 1;
            while (i <= j)
            {
                if (x[i] != x[j])
                    return false;
                i++;
                j--;
            }

            return true;
        }

        static void Main(string[] args)
        {
            int max = 0;
            for (int i = 100; i < 1000; i++)
            {
                for (int j = 100; j < 1000; j++)
                {
                    int prod = i * j;
                    string prodStr = prod.ToString();
                    if(isPalindrome(prodStr))
                        max = Math.Max(max, prod);
                }
            }
            Console.WriteLine(max);
        }
    }
}

Palindrome in Racket

Solution to Project Euler problem 4

#lang racket
(define (isPalindrome x)
  (equal? x (reverseStr x)))
(define (ToStr x)
  (number->string x))
(define (reverseStr x)
  (list->string(reverse(string->list x))))
(define maxPal 0)
(for* ([i (in-range 100 1000)]
       [j (in-range 100 1000)])
  (let ([prod (* i j)])
    (cond [(and (isPalindrome(ToStr prod)) (> prod maxPal))
           (set! maxPal prod)])))
(printf "~a~n" maxPal)

Postfix Calculator in Scala

Element.scala

package calculator

trait Element {

}

NumberElement.scala

package calculator

class NumberElement(numberArg: String) extends Element {
  var number: Double = numberArg.toDouble
  
  def getNumber = number
  
  override def toString() : String = {
    return number.toString()
  }
}

OperatorElement.scala

package calculator

sealed trait OperatorType
case object MULTIPLY extends OperatorType
case object DIVIDE extends OperatorType
case object ADD extends OperatorType
case object SUBTRACT extends OperatorType
case object EXPONENTIAL extends OperatorType
case object OPAREN extends OperatorType
case object CPAREN extends OperatorType
case object NULL extends OperatorType
  
class OperatorElement(operator: Character) extends Element {
  var type1 : OperatorType = NULL
  
  var c : Character = operator
  
  if(operator == '+')
    type1 = ADD
  else if(operator == '-')
    type1 = SUBTRACT
  else if(operator == '*')
    type1 = MULTIPLY
  else if(operator == '/')
    type1 = DIVIDE
  else if(operator == '^')
    type1 = EXPONENTIAL
  else if(operator == '(')
    type1 = OPAREN
  else if(operator == ')')
    type1 = CPAREN
    
  override def toString() : String = {
    return c.toString()
  }
}

Parser.scala

package calculator

import scala.collection.mutable.ArrayBuffer

class Parser {
  def Parse(s: String) : ArrayBuffer[Element] = 
  {
    var e = new ArrayBuffer[Element]()
    var sb = new StringBuilder()
    var i = 0
    for(i <- 0 until s.length()) 
    {
      var c = s.charAt(i)
      if(Character.isDigit(c))
        sb.append(c)
      if(i + 1 < s.length())
      {
        var d = s.charAt(i + 1)
        if(Character.isDigit(d) == false && sb.length() > 0)
        {
          e.append(new NumberElement(sb.toString()))
          sb.clear()
          
        }
      }
      
      if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')')
        e.append(new OperatorElement(c));
    }
    
    if(sb.length() > 0)
      e.append(new NumberElement(sb.toString()));
    
    return e
  }
}

InfixToPostfix.scala

package calculator

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Stack
import util.control.Breaks._

class InfixToPostfix {
  private var converted: ArrayBuffer[Element] = new ArrayBuffer[Element]

  def Precedence(c: OperatorElement) : Int = 
  {
    if(c.type1 == EXPONENTIAL)
    {
      return 2
    }
    else if(c.type1 == MULTIPLY || c.type1 == DIVIDE)
    {
      return 3
    }
    else if(c.type1 == ADD || c.type1 == SUBTRACT)
    {
      return 4
    }
    else
      return Int.MaxValue  
  }
  
  def ProcessOperators(st: Stack[Element], element: Element, top: Element)
  {
    var top1 = top;
    breakable
    {
	  while(st.size > 0 && Precedence(element.asInstanceOf[OperatorElement]) >= Precedence(top1.asInstanceOf[OperatorElement]))
	  {
	    var p = st.pop()
	    if(p.asInstanceOf[OperatorElement].type1 == OPAREN)
	      break
	    converted.append(p)
	    if(st.size > 0)
	      top1 = st.top
	  }
    }
  }
  
  def ConvertFromInfixToPostFix(e: ArrayBuffer[Element]) : ArrayBuffer[Element] = 
  {
    var stack1: ArrayBuffer[Element] = new ArrayBuffer[Element]()
    e.copyToBuffer(stack1)
    var st: Stack[Element] = new Stack[Element]()
    
    var i: Int = 0
    for(i <- 0 until stack1.length)
    {
      var element = stack1(i)
      if(element.isInstanceOf[OperatorElement])
      {
        if(st.isEmpty || element.asInstanceOf[OperatorElement].type1 == OPAREN)
          st.push(element);
        else
        {
          var top = st.top;
	      if(element.asInstanceOf[OperatorElement].type1 == CPAREN)
	          ProcessOperators(st, element, top);
	      else if(Precedence(element.asInstanceOf[OperatorElement]) < Precedence(top.asInstanceOf[OperatorElement]))
	          st.push(element);
	      else
	      {
	          ProcessOperators(st, element, top);
	          st.push(element);
	      }
        }
      }
      else
        converted.append(element);
    }
    
    while(st.size > 0)
    {
        var b1 = st.pop()
        converted.append(b1)
    } 
    return converted
  }
  
  override def toString(): String =
  {
    var sb: StringBuffer = new StringBuffer()
    converted.foreach(f => sb.append(f + " "))
    return sb.toString()
  }
}

PostFixEvaluator.scala

package calculator

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Stack

class PostFixEvaluator {
  def calculate(left: NumberElement, right: NumberElement, op: OperatorElement): NumberElement = 
  {
    var temp = Double.MaxValue
    if(op.type1 == ADD)
    {
      temp = left.getNumber + right.getNumber
    }
    else if(op.type1 == SUBTRACT)
    {
      temp = left.getNumber - right.getNumber
    }
    else if(op.type1 == MULTIPLY)
    {
      temp = left.getNumber * right.getNumber
    }
    else if(op.type1 == DIVIDE)
    {
      temp = left.getNumber / right.getNumber
    }
    else if(op.type1 == EXPONENTIAL)
    {
      temp = Math.pow(left.getNumber, right.getNumber)
    }
    
    return new NumberElement(temp.toString)
  }
  
  def Evaluate(e: ArrayBuffer[Element]): Double = 
  {
    var stack: Stack[Element] = new Stack[Element]
    var v: ArrayBuffer[Element] = new ArrayBuffer[Element]
    e.copyToBuffer(v)
    
    var i: Int = 0
    for(i <- 0 until v.length)
    {
      var element = v(i)
      if(element.isInstanceOf[NumberElement])
        stack.push(element)
      if(element.isInstanceOf[OperatorElement])
      {
        var right = stack.pop()
        var left = stack.pop()
        var result = calculate(left.asInstanceOf[NumberElement], right.asInstanceOf[NumberElement], element.asInstanceOf[OperatorElement])
        stack.push(result)
      }
    }
    return stack.pop().asInstanceOf[NumberElement].getNumber
  }
}

Calculator.scala

package calculator

object Calculator {
  def main(args: Array[String]): Unit = {
    val t = "4+6+9*8-(5*6+9)^2"
    val p = new Parser()
    var e = p.Parse(t)
    var i = new InfixToPostfix()
    e = i.ConvertFromInfixToPostFix(e)
    println(i)
    var pfe = new PostFixEvaluator();
    var result = pfe.Evaluate(e);
    println(result)
  }
}

Dependency Injection Pattern in C# using Unity (part 2)

Note: Use NuGet to install Unity

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work
{
    interface IPerson
    {
        string Name { get; }
    }

    class Person : IPerson
    {
        [InjectionConstructor]
        public Person(string name)
        {
            this.name = name;
        }

        string name = "default";
        public string Name
        {
            get
            {
                return name;
            }
        }
    }

    class Work
    {
        [Dependency("office1")]
        public IPerson office1 { get; set; }
        [Dependency("office2")]
        public IPerson office2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<IPerson, Person>("office1", new InjectionConstructor("John"));
                container.RegisterType<IPerson, Person>("office2", new InjectionConstructor("Catherine"));
                Work w = container.Resolve<Work>();

                Console.WriteLine(w.office1.Name + " is at office 1");
                Console.WriteLine(w.office2.Name + " is at office 2");
            }
        }
    }
}

Dependency Injection via config file
Note: Add reference “System.Configuration”
App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="work"/>
    <namespace name="work"/>

    <container>
      <register name="John" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="John" />
        </constructor>
      </register>
      <register name="Catherine" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Catherine" />
        </constructor>
      </register>
      <register type="Work">
        <property name="office1">
          <dependency name="John" />
        </property>
        <property name="office2">
          <dependency name="Catherine" />
        </property>
      </register>
    </container>
  </unity>
</configuration>

Program.cs

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work
{
    interface IPerson
    {
        string Name { get; }
    }

    class Person : IPerson
    {
        [InjectionConstructor]
        public Person(string name)
        {
            this.name = name;
        }

        string name = "default";
        public string Name
        {
            get
            {
                return name;
            }
        }
    }

    class Work
    {
        [Dependency("office1")]
        public IPerson office1 { get; set; }

        [Dependency("office2")]
        public IPerson office2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();

                Work w = container.Resolve<Work>();

                Console.WriteLine(w.office1.Name + " is at office 1");
                Console.WriteLine(w.office2.Name + " is at office 2");
            }
        }
    }
}

Dependency Injection Pattern in C# using Unity

Note: Use NuGet to install Unity

IExam.cs

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

namespace school
{
    interface IExam
    {
        string GetQuestions();
    }
}

EnglishExam.cs

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

namespace school
{
    class EnglishExam : IExam
    {
        public string GetQuestions()
        {
            return "English Questions";
        }
    }
}

MathExam.cs

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

namespace school
{
    class MathExam : IExam
    {
        public string GetQuestions()
        {
            return "Math Questions";
        }
    }
}

ExamService.cs

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

namespace school
{
    class ExamService
    {
        IExam exam = null;
        public ExamService(IExam exam)
        {
            this.exam = exam;
            Console.WriteLine(exam.GetQuestions());
        }

        public string GetQuestions()
        {
            return exam.GetQuestions();
        }
    }
}

Program.cs

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school
{
    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<IExam, EnglishExam>();
                //container.RegisterType<IExam, MathExam>();

                ExamService exam = container.Resolve<ExamService>();

                exam.GetQuestions();
            }
        }
    }
}

Dependency Injection via configuration file
Note: Add reference “System.Configuration”

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="school"/>
    <namespace name="school"/>
    
    <container>
      <register type="IExam" mapTo="EnglishExam" />
      <!--<register type="IExam" mapTo="MathExam" />-->
    </container>
  </unity>
</configuration>

Program.cs

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school
{
    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();

                ExamService exam = container.Resolve<ExamService>();
                exam.GetQuestions();
            }
        }
    }
}

Depth-first search algorithm in C#

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

namespace DepthFirst
{
    class Program
    {
        public class Person
        {
            public Person(string name)
            {
                this.name = name;
            }

            public string name { get; set; }
            public List<Person> Friends
            {
                get
                {
                    return FriendsList;
                }
            }

            public void isFriendOf(Person p)
            {
                FriendsList.Add(p);
            }

            List<Person> FriendsList = new List<Person>();

            public override string ToString()
            {
                return name;
            }
        }

        public class DepthFirstAlgorithm
        {
            public Person BuildFriendGraph()
            {
                Person Aaron = new Person("Aaron");
                Person Betty = new Person("Betty");
                Person Brian = new Person("Brian");
                Aaron.isFriendOf(Betty);
                Aaron.isFriendOf(Brian);

                Person Catherine = new Person("Catherine");
                Person Carson = new Person("Carson");
                Person Darian = new Person("Darian");
                Person Derek = new Person("Derek");
                Betty.isFriendOf(Catherine);
                Betty.isFriendOf(Darian);
                Brian.isFriendOf(Carson);
                Brian.isFriendOf(Derek);

                return Aaron;
            }

            public Person Search(Person root, string nameToSearchFor)
            {
                if (nameToSearchFor == root.name)
                    return root;

                Person personFound = null;
                for (int i = 0; i < root.Friends.Count; i++)
                {
                    personFound = Search(root.Friends[i], nameToSearchFor);
                    if (personFound != null)
                        break;
                }
                return personFound;
            }

            public void Traverse(Person root)
            {
                Console.WriteLine(root.name);
                for (int i = 0; i < root.Friends.Count; i++)
                {
                    Traverse(root.Friends[i]);
                }
            }
        }

        static void Main(string[] args)
        {
            DepthFirstAlgorithm b = new DepthFirstAlgorithm();
            Person root = b.BuildFriendGraph();
            Console.WriteLine("Traverse\n------");
            b.Traverse(root);

            Console.WriteLine("\nSearch\n------");
            Person p = b.Search(root, "Catherine");
            Console.WriteLine(p == null ? "Person not found" : p.name);
            p = b.Search(root, "Alex");
            Console.WriteLine(p == null ? "Person not found" : p.name);
        }
    }
}

Kadane’s (Maximum Subarray) Algorithm

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

class Program
{
    //http://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane.27s_algorithm
    static int MaxSubArray_wiki(int[] arr)
    {
        int max_ending_here = 0;
        int max_so_far = 0;

        foreach (int x in arr)
        {
            max_ending_here = Math.Max(0, max_ending_here + x);
            max_so_far = Math.Max(max_so_far, max_ending_here);
        }

        return max_so_far;
    }

    static int MaxSubArray(int[] arr)
    {
        int max_ending_here = 0;
        int max_so_far = 0;

        for (int i = 0; i < arr.Length; i++)
        {
            int x = arr[i];
            max_ending_here += x;

            if (max_ending_here <= 0)
                max_ending_here = 0;

            if (max_ending_here > max_so_far)
                max_so_far = max_ending_here;
        }

        return max_so_far;
    }

    static void Main(string[] args)
    {
        int[] arr = { 3, 4, -6, 33, 45, 55, -10, 1000, -2000, 5, 6, 1490 };
        Console.WriteLine(MaxSubArray(arr));
        Console.WriteLine(MaxSubArray_wiki(arr));
    }
}