SPOJ 42. Adding Reversed Numbers (ADDREV) with F#

Problem Definition

The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.

Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.

ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).

Input

The input consists of N cases (equal to about 10000). The first line of the input contains only positive integerN. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.

Output

For each case, print exactly one line containing only one integer – the reversed sum of two reversed numbers. Omit any leading zeros in the output.

Solution

// problem definition : https://www.spoj.com/problems/ADDREV/
open System
let parseTuple() : int*int =
let line = Console.ReadLine().Split()
line.[0] |> int , line.[1] |> int
let reverseInt n =
let rec reverseInt' n acc =
let acc' = acc + (n%10)
match n with
| n when n >= 10 -> reverseInt' ((int)(n/10)) (acc'*10)
| n -> acc'
reverseInt' n 0
let solveCase (n1,n2) = reverseInt (reverseInt n1 + reverseInt n2)
let rec solveCases i maxCases =
if i < maxCases then
parseTuple()
|> solveCase
|> printfn "%d"
solveCases (i + 1) maxCases // solving next case
let spoj42() =
match Console.ReadLine() |> Int32.TryParse with
| (true, i) when i > 0 -> solveCases 0 i
| _ -> ()
spoj42()
view raw addrev.fs hosted with ❤ by GitHub

More details of this problem is available here

Euler Problem 002 with F#

Problem Statement

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solutions

Recursive Solution:

// Recursive solution
let eulerProblem2Answer'' =
let maxF = 4000000
let rec computeSum f1 f2 sum =
match f1 + f2 with
| n -> computeSum f2 n sum
| n when n%2 = 0 -> if (n<maxF) then (computeSum f2 n (sum+n)) else sum
computeSum 0 1 0
view raw euler02.fsx hosted with ❤ by GitHub

Using infinite Fibonacci sequence:

let eulerProblem2Answer =
(0,1)
|> Seq.unfold (fun (f1,f2) -> Some(f2, (f2, f1+f2))) // Fibonacci Sequence
|> Seq.takeWhile(fun x -> x < 4000000) // Taking upto Max Fibbonacci
|> Seq.filter (fun x -> x%2=0) // Filtering only even numbers
|> Seq.sum // computing sum
view raw euler02.fsx hosted with ❤ by GitHub

A bit shorter version can be derived using Seq.SumBy:

let eulerProblem2Answer' =
(0,1)
|> Seq.unfold (fun (f1,f2) -> Some(f2, (f2, f1+f2)))
|> Seq.takeWhile(fun x -> x < 4000000)
|> Seq.sumBy (fun x -> if (x%2)=0 then x else 0) // using SumBy with a projection
view raw euler02.fsx hosted with ❤ by GitHub

Result

> 
val eulerProblem2Answer : int = 4613732
val eulerProblem2Answer' : int = 4613732
val eulerProblem2Answer'' : int = 4613732

Scala Notes: Pattern Matching

Pattern matching lets you automatically execute code based on some piece of data. Scala uses pattern matching often, such as when you parse XML or pass messages between threads. Basic syntax of pattern matching is as follow.

    target match { case _ => result } 

Following are the important aspects of pattern matching:

Pattern matching works a bit like a switch statement.

def dochore(chore:String):String = chore match{
    case "A" => "A"
    case "B" => "B"  
    case  _  => "C"
}

A pattern matches a target if it is structurally equivalent to the pattern in question. If multiple pattern matches the target, Scala chooses the first matching case.

List(1,2,3) match { case _ => 42} // => 42
List(1,2,3) match { case h::t => h}    // => 1 
List(1,2,3) match { case h::t => t}     // => List(2,3) 

If none of the patterns matches with the target, MatchError occurs. A MatchError indicates that the none of the cases in a match expression matched the target.

List(1,2,3) match {case Nil => 42}     // => `MatchError` at runtime. 

Next, we outline few concrete examples.

Examples

Example1: Computing Factorial. To compute a factorial in Scala, we specify a condition in a guard for each match statement.

def factorial(n: Int): Int = n match {
    case 0 => 1 
    case x if x>0 => factorial(n-1) *n 
}

Example 2: Computing summation of a given List as an argument. To do this, we need to define a function with signature: def sum(l:List[int]) and implement it as follows.

def sum (list:List[Int]) = {
    def sumAux (xs:List[Int], res:Int):Int = xs match {
      case Nil   => res
      case x::xt => sumAux(xt, res+x) <span class="bullet rounded">1</span>
    }

    sumAux (list, 0)
}

Example 3: Computing Product is taken from Functional Programming in Scala book.

sealed trait List[+A]
case object Nil extends List[Nothing]
case class(head: A, tail:List[A]) extends List[A]

def product(ds: List[Double]): Double = ds match{
    case Nil => 1.0
    case Cons(0,0,_) => 0.0 
    case Cons(x, xs) => x * product(xs)   
}

lucabol's avatarx += x++

Hi, I’m back. I’ve finally sorted out the guidelines for blogging in Credit Suisse.

Here is something I have been playing around with in the spare time between one meeting and the next one.  It is a Scheme interpreter that includes a REPL window. The full code is here.

All the smarts for it come from this Wiki Book. I just ported the code to F# (and modified it a bit). I thought the comparison might be interesting, so here we go. Thanks to Tobias and Jose for reviewing the code, find one bug and suggest improvements.

Before we start looking at the real code, here is what we are trying to accomplish in form of test cases. If you are a bit rusty on LISP syntax, you might want to try and see if you understand what it does.

Our goal is to make all this XUnit…

View original post 501 more words

lucabol's avatarx += x++

This is part of my ‘things that I do in the empty spaces between one meeting and the next one, which might end up being vaguely interesting’. It is a lambda expression parser.

The full source code is here.

I actually have two versions of it: one written longhand and the other one written with FParsec. Just to be clear: I’m no expert of either.

And just to be more clear: I think writing most parsers longhand in the way I am about to show is crazy. You either use FParsec or  fslex / fsyacc.

I have a strong distaste for additional compilation steps. I think it lingers on from MFC project types of 15/20 years ago. I was one of these crazy folks that would generate the project, wrap the generated code (with some generalizations) in my own library and use that one from then on.

View original post 408 more words

Design a site like this with WordPress.com
Get started