This week I’m trying to find all the new thing in .Net 4.0 and VS2010. One of the more exiting features in .Net 4.0 is the parallel extension. Or how to make multithreading easy.
I guess we all know the Fizzbuzz test by now.
Describe by Imram as the following.
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
Seems easy enough.
vbnet
Sub Main()
Dim fiz As Integer = 3
Dim buzz As Integer = 5
Dim input As String
Dim x As Integer
Console.WriteLine("Give the upper limit:")
input = Console.ReadLine()
If Integer.TryParse(input, x) AndAlso x > 15 Then
Dim text As String = String.Empty
For i = 1 To x
text = i & ". "
If i Mod 3 = 0 Then
text &= "fizz"
End If
If i Mod 5 = 0 Then
If text.Contains("fizz") Then
text &= " "
End If
text &= "buzz"
End If
If Not text.Contains("zz") Then
text &= i
End If
Console.WriteLine(text)
Next
End If
Console.ReadLine()
End Sub
With this as the result.
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizz buzz
16
17
fizz
19
buzz
But did anyone say you had to write these out in order? No they didn’t so we can make this much faster by using multithreading.
This is how I would do that in pre .Net 4.0.
```vbnet Sub Main() Dim fiz As Integer = 3 Dim buzz As Integer = 5 Dim input As String Dim x As Integer Console.WriteLine(“Give the upper limit:“) input = Console.ReadLine() If Integer.TryParse(input, x) AndAlso x > 15 Then For i = 1 To x Dim starter = New Threading.ParameterizedThreadStart(AddressOf Printtext) Dim t As New Threading.Thread(starter) t.Start(i) Next End If Console.ReadLine() End Sub
Private Sub Printtext(ByVal o As Object)
Dim i = CType(o, Integer)
Dim text As String = String.Empty
text = i & ". "
If i Mod 3 = 0 Then
text &= "fizz"
End If
If i Mod 5 = 0 Then
If text.Contains("fizz") Then
text &= " "
End If
text &= "buzz"
End If
If Not text.Contains("zz") Then
text &= i
End If
Console.WriteLine(text)
End Sub```
With this as the result.
1
fizz
2
4
buzz
7
fizz
8
fizz
fizz
buzz
11
13
14
fizz buzz
16
17
fizz
19
buzz
Didin’t seem to difficult to me.
But it is even easier in .Net 4.0.
vbnet
Sub Main()
Dim fiz As Integer = 3
Dim buzz As Integer = 5
Dim input As String
Dim x As Integer
Console.WriteLine("Give the upper limit:")
input = Console.ReadLine()
If Integer.TryParse(input, x) AndAlso x > 15 Then
Dim text As String = String.Empty
Parallel.For(1, x, Function(i) As Integer
text = i & ". "
If i Mod 3 = 0 Then
text &= "fizz"
End If
If i Mod 5 = 0 Then
If text.Contains("fizz") Then
text &= " "
End If
text &= "buzz"
End If
If Not text.Contains("zz") Then
text &= i
End If
Console.WriteLine(text)
Return 0
End Function)
End If
Console.ReadLine()
End Sub
With this as the result.
1
2
4
fizz
7
8
fizz
buzz
13
14
fizz buzz
16
19
11
fizz
17
fizz
fizz
buzz
Which seems a bit more random to me.
That was a fun excercise.