Using F# Indexed Properties in a Type - f#

I'm trying to convert the following C# into F#:
public class Matrix
{
double[,] matrix;
public int Cols
{
get
{
return this.matrix.GetUpperBound(1) + 1;
}
}
public int Rows
{
get
{
return this.matrix.GetUpperBound(0) + 1;
}
}
public Matrix(double[,] sourceMatrix)
{
this.matrix = new double[sourceMatrix.GetUpperBound(0) + 1, sourceMatrix.GetUpperBound(1) + 1];
for (int r = 0; r < this.Rows; r++)
{
for (int c = 0; c < this.Cols; c++)
{
this[r, c] = sourceMatrix[r, c];
}
}
}
public double this[int row, int col]
{
get
{
return this.matrix[row, col];
}
set
{
this.matrix[row, col] = value;
}
}
}
This is what I have so far:
type Matrix(sourceMatrix:double[,]) =
let mutable (matrix:double[,]) = Array2D.create (sourceMatrix.GetUpperBound(0) + 1) (sourceMatrix.GetUpperBound(1) + 1) 0.0
member this.Item
with get(x, y) = matrix.[(x, y)]
and set(x, y) value = matrix.[(x, y)] <- value
do
for i = 0 to matrix.[i].Length - 1 do
for j = (i + 1) to matrix.[j].Length - 1 do
this.[i].[j] = matrix.[i].[j]
My type above seems to have two problems I'm not sure how to resolve. The first one is that matrix.[(x, y)] is expected to have type `a[] but has type double[,]. The second is type definitions must have let/do bindings preceding member and interface definitions. The problem with that is I'm trying to populate an indexed property in the do block, which means I have to create it first.
Thanks in advance,
Bob

Regarding your first problem, you want to use matrix.[x,y] instead of matrix.[(x,y)] - your matrix is indexed by two integers, not by a tuple of integers (although these are conceptually similar).
Here's something roughly equivalent to your C#:
type Matrix(sourceMatrix:double[,]) =
let rows = sourceMatrix.GetUpperBound(0) + 1
let cols = sourceMatrix.GetUpperBound(1) + 1
let matrix = Array2D.zeroCreate<double> rows cols
do
for i in 0 .. rows - 1 do
for j in 0 .. cols - 1 do
matrix.[i,j] <- sourceMatrix.[i,j]
member this.Rows = rows
member this.Cols = cols
member this.Item
with get(x, y) = matrix.[x, y]
and set(x, y) value = matrix.[x, y] <- value
This assumes that your matrix can't actually be reassigned (e.g. in the C# you've posted, you could have made your matrix field readonly - unless there's additional code that you've hidden). Therefore, the number of rows and columns can be calculated once in the constructor since the entries of the matrix may change but its size won't.
However, if you want a more literal translation of your code, you can give your newly constructed instance a name (this in this case):
type Matrix(sourceMatrix:double[,]) as this =
let mutable matrix = Array2D.zeroCreate<double> (sourceMatrix.GetUpperBound(0) + 1) (sourceMatrix.GetUpperBound(1) + 1)
do
for i in 0 .. this.Rows - 1 do
for j in 0 .. this.Cols - 1 do
this.[i,j] <- sourceMatrix.[i,j]
member this.Rows = matrix.GetUpperBound(0) + 1
member this.Cols = matrix.GetUpperBound(1) + 1
member this.Item
with get(x, y) = matrix.[x, y]
and set(x, y) value = matrix.[x, y] <- value

type Matrix(sourceMatrix:double[,]) =
let matrix = Array2D.copy sourceMatrix
member this.Item
with get(x, y) = matrix.[x, y]
and set(x, y) value = matrix.[x, y] <- value

Related

Unable to understand firstTerm = secondTerm; secondTerm = nextTerm; in fibonacci series

class Main {
public static void main(String[] args) {
int n = 5, firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series till " + n + " terms:");
for (int i = 1; i <= n; ++i) {
System.out.print(firstTerm + " ");
// compute the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
//Q) Unable to understand why firstTerm = secondTerm;
secondTerm = nextTerm; statement is written, can anyone explain me this concept
The fibonnaci sequence is defined by
F(0) = 0 // This is our first term
F(1) = 1 // This is the second term
F(n) = F(n - 1) + F(n - 2)
To calculate a term that is neither the first term, nor the second term, we need to sum, the two previous terms.
This is the reason why while iterating, the second term value is assigned to the first term and so on
You will have more details here

How can I optimize my code for better execution times

I'm implementing an image processing algorithm called BM3D and I've already achieved the outcome which is denoising a grayscale image but the thing is that it is too slow, even with a 436 by 436 gray image.
I have already tried to find way to maybe fasten up the work that I do with array and lists, but didn't get much improvement
val img = imread("files/image.png", 0)
val img3= Mat(img.rows(),img.cols(),img.type())
val listaBlocos = mutableListOf(Pair(0.0, Pair(0,0)))
val tamanhoBloco = 3 //Block Size
val tamanhoJanela = 9 //Window Size
val mediaPorBloco = DoubleArray(16)
var sum = 0.0
listaBlocos.clear()
val stats_file = File("files/tempos436x436.txt")
val test = 10
for (x in 0 until test){
val timeelapsed = measureTimeMillis {
for (col in 20 ..img.width() - 20) {
for (row in 20 ..img.height() - 20) {
val block1 = generateBlock(img, row, col, tamanhoBloco)
for (c in -tamanhoJanela..tamanhoJanela) {
for (l in -tamanhoJanela..tamanhoJanela) {
val block2 = generateBlock(img, row + l, col + c, tamanhoBloco)
val d = distBlock(block1, block2)
val par = Pair(d, Pair(row + l, col + c))
listaBlocos.add(par)
}
}
val listaBlocosOrdenada = listaBlocos.sortedWith(compareBy { it.first })
listaBlocos.clear()
for (k in 0..15) {
sum = 0.0
val c2 = listaBlocosOrdenada[k].second.second
val l2 = listaBlocosOrdenada[k].second.first
for (c in 0..tamanhoBloco - 1) {
for (l in 0..tamanhoBloco - 1) {
sum += img.get(l2 - l, c2 - c)[0]
}
}
mediaPorBloco[k] = sum / 4
}
val v = mediaPorBloco.average()
img3.put(row,col,v)
}
}
}
imwrite("files/resultado.png", img3)
stats_file.appendText("teste$x 100X200 $timeelapsed\n")
}
well the result in the actual image denoising is good but is takes maybe 15 min to denoise a 436 x 436 image. I'm currently using a virtual machine with Ubuntu and 4 cores a 4 gbs of Ram

why my code is slow when finding Fibonacci sum?

I'm writing answers for project Euler Questions in this repo
but having some performance issues in my solution
Question 2:
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.
My Solution is
func solution2()
{
func fibonacci(number: Int) -> (Int)
{
if number <= 1
{
return number
}
else
{
return fibonacci(number - 1) + fibonacci(number - 2)
}
}
var sum = 0
print("calculating...")
for index in 2..<50
{
print (index)
if (fibonacci(index) % 2 == 0)
{
sum += fibonacci(index)
}
}
print(sum)
}
My Question is, why it gets super slow after iteration 42, i want to do it for 4000000 as the question says, any help?
solution 2
func solution2_fast()
{
var phiOne : Double = (1.0 + sqrt(5.0)) / 2.0
var phiTwo : Double = (1.0 - sqrt(5.0)) / 2.0
func findFibonacciNumber (nthNumber : Double) -> Int64
{
let nthNumber : Double = (pow(phiOne, nthNumber) - (pow(phiTwo, nthNumber))) / sqrt(5.0)
return Int64(nthNumber)
}
var sum : Int64 = 0
print("calculating...")
for index in 2..<4000000
{
print (index)
let f = findFibonacciNumber(Double(index))
if (f % 2 == 0)
{
sum += f
}
}
print(sum)
}
The most important thing about PE questions is to think about what it is asking.
This is not asking you to produce all Fibonacci numbers F(n) less than 4000000. It is asking for the sum of all even F(n) less than 4000000.
Think about the sum of all F(n) where F(n) < 10.
1 + 2 + 3 + 5 + 8
I could do this by calculating F(1), then F(2), then F(3), and so on... and then checking they are less than 10 before adding them up.
Or I could store two variables...
F1 = 1
F2 = 2
And a total...
Total = 3
Now I can turn this into a while loop and lose the recursion altogether. In fact, the most complex thing I'm doing is adding two numbers together...
I came up with this...
func sumEvenFibonacci(lessThan limit: Int) -> Int {
// store the first two Fibonacci numbers
var n1 = 1
var n2 = 2
// and a cumulative total
var total = 0
// repeat until you hit the limit
while n2 < limit {
// if the current Fibonacci is even then add to total
if n2 % 2 == 0 {
total += n2
}
// move the stored Fibonacci numbers up by one.
let temp = n2
n2 = n2 + n1
n1 = temp
}
return total
}
It runs in a fraction of a second.
sumEvenFibonacci(lessThan: 4000000)
Finds the correct answer.
In fact this... sumEvenFibonacci(lessThan: 1000000000000000000) runs in about half a second.
The second solution seems to be fast(er) although an Int64 will not be sufficient to store the result. The sum of Fibonacci numbers from 2..91 is 7,527,100,471,027,205,936 but the largest number you can store in an Int64 is 9,223,372,036,854,775,807. For this you need to use some other types like BigInteger
Because you use the recursive, and it cache in the memory.If you iteration 42, it maybe has so many fibonacci function in your memory, and recursive.So it isn't suitable for recursive, and you can store the result in the array, not the reason of the swift.
this is the answer in two different ways
func solution2_recursive()
{
func fibonacci(number: Int) -> (Int)
{
if number <= 1
{
return number
}
else
{
return fibonacci(number - 1) + fibonacci(number - 2)
}
}
var sum = 0
print("calculating...")
for index in 2..<50
{
print (index)
let f = fibonacci(index)
if( f < 4000000)
{
if (f % 2 == 0)
{
sum += f
}
}
else
{
print(sum)
return
}
}
}
solution 2
func solution2()
{
var phiOne : Double = (1.0 + sqrt(5.0)) / 2.0
var phiTwo : Double = (1.0 - sqrt(5.0)) / 2.0
func findFibonacciNumber (nthNumber : Double) -> Int64
{
let nthNumber : Double = (pow(phiOne, nthNumber) - (pow(phiTwo, nthNumber))) / sqrt(5.0)
return Int64(nthNumber)
}
var sum : Int64 = 0
print("calculating...")
for index in 2..<50
{
let f = findFibonacciNumber(Double(index))
if(f < 4000000)
{
if (f % 2 == 0)
{
sum += f
}
}
else
{
print(sum)
return
}
}
}

To calculate every third term in a Fibonacci sequence

int Fib1, Fib2, Fib3, FibSum;
Fib1 = 0;
Fib2 = 1;
while(Fib3 < 500000)
{
Fib3 = Fib1 + Fib2;
Fib1 = Fib2;
Fib2 = Fib3;
FibSum = Fib3 + Fib1;
}
printf("%d\n", FibSum);
return 0;
I want to sum every third term of a fibonacci series but my answers is 832040 and it must be 158905...any help will be grateful!
This seems like homework but hey, I was once a student too. Still learning.
I wrote the following code in R but you can follow along enough:
fib1 <- 0
fib2 <- 1
fib3 <- 0
fib_sum <- 0
placeholder <- 0
while(fib3 < 500000)
{
placeholder <- placeholder + 1
f1 <- fib1
f2 <- fib2
f3 <- fib3
fib3 <- fib1 + fib2
fib1 <- fib2
fib2 <- fib3
if(placeholder %% 3 == 0)
{
fib_sum <- fib_sum + f1
print(paste('postsum [placeholder, fib_sum, fib1, fib2, fib3]: ',
placeholder, ' ', fib_sum, ' ', f1, ' ', f2, ' ', f3))
}
}
print(fib_sum)
Which results in what you were looking for. Lesson time, since this seems to be homework help. To help you out on the path of being a better programmer I would suggest taking the approach of scaffolding (just simply printing out everything after each line or so) when doing programming.
This will help you to see how you program is evolving as you do it.
Is there a better solution to the one below? I am sure there is but since I output the code as I was programming, I was able to come to the conclusion a lot quicker.
Hope that helps.
There is a shortcut to calculate every third fibonacci number:
If you want to sum up 1,5,21,89,377 ...then you sum up the first two numbers you have (fibsum = 1 + 5) and calculate and add the next numbers as follows in a loop.
fib1 = 1
fib2 = 5
fib3 = 0
fibsum = fib1 + fib2
while fib3 < 500000 :
fib3 = fib2*4+fib1
if fib3 < 500000:
fibsum += fib3
fib1 = fib2
fib2 = fib3
print fibsum
Here is some working code applying a formula found at HERE
double phi1 = (1 + sqrt(5)) / 2.0;
double phi2 = (1 - sqrt(5)) / 2.0;
int counter = 2;//Third term
int total = 0, term;
while (true) {
term = (pow(phi1, counter) - pow(phi2, counter)) / (phi1 - phi2);
if (term >= 500000)
break;
total += term;
counter += 3;
}
printf("%d\n", total);
return 0;
EDIT: Just realized this was posted OVER A YEAR AGO

Adding Overloaded Constructors to Implicit F# Type

I have created the following type using implicit type construction:
open System
type Matrix(sourceMatrix:double[,]) =
let rows = sourceMatrix.GetUpperBound(0) + 1
let cols = sourceMatrix.GetUpperBound(1) + 1
let matrix = Array2D.zeroCreate<double> rows cols
do
for i in 0 .. rows - 1 do
for j in 0 .. cols - 1 do
matrix.[i,j] <- sourceMatrix.[i,j]
//Properties
///The number of Rows in this Matrix.
member this.Rows = rows
///The number of Columns in this Matrix.
member this.Cols = cols
///Indexed Property for this matrix.
member this.Item
with get(x, y) = matrix.[x, y]
and set(x, y) value =
this.Validate(x,y)
matrix.[x, y] <- value
//Methods
/// Validate that the specified row and column are inside of the range of the matrix.
member this.Validate(row, col) =
if(row >= this.Rows || row < 0) then raise (new ArgumentOutOfRangeException("row is out of range"))
if(col >= this.Cols || col < 0) then raise (new ArgumentOutOfRangeException("column is out of range"))
However now I need to add the following overloaded constructor to this type (which is in C# here):
public Matrix(int rows, int cols)
{
this.matrix = new double[rows, cols];
}
The problem that I have is that it seems any overloaded constructors in an implicit type must have a parameter list that is a subset of the first constructor. Obviously the constructor I want to add does not meet this requirement. Is there any way to do this using implicit type construction? Which way should I do this? I'm pretty new to F# so if you could show the whole type with your changes in it I would greatly appreciate it.
Thanks in advance,
Bob
P.S. If you have any other suggestions to make my class more in the functional style please feel free to comment on that as well.
I would probably just do this:
type Matrix(sourceMatrix:double[,]) =
let matrix = Array2D.copy sourceMatrix
let rows = (matrix.GetUpperBound 0) + 1
let cols = (matrix.GetUpperBound 1) + 1
new(rows, cols) = Matrix( Array2D.zeroCreate rows cols )
unless we are talking about very large arrays which are created very often (i.e. copying the empty array becomes a performance bottleneck).
If you want to emulate the C# version, you need an explicit field that can be accessed from both constructors, like so:
type Matrix(rows,cols) as this =
[<DefaultValue>]
val mutable matrix : double[,]
do this.matrix <- Array2D.zeroCreate rows cols
new(source:double[,]) as this =
let rows = source.GetUpperBound(0) + 1
let cols = source.GetUpperBound(1) + 1
Matrix(rows, cols)
then
for i in 0 .. rows - 1 do
for j in 0 .. cols - 1 do
this.matrix.[i,j] <- source.[i,j]
BTW, there is also a matrix type in the F# PowerPack.

Resources