How to find the largest number among 5 in visual basic? - vb.net

I want to find it using the IF statements and NESTED IF statements. I know how to find the largest among 3 numbers, but can't do the 5. I want to follow the same concept as the code below:
Dim number1, number2, number3, largest as integer
number1= 2
number 2= 7
number3= 14
If number1>number2 then
if number1>number 3 then
largest= number1
else
largest= number3
End If
Else If number2> number3 then
largest= number2
else
largest number3
End If
label1.text= largest

By comparing each number to largest and only assigning it if it's larger you will end up with the largest number assigned to largest.
Dim number1, number2, number3, largest As Integer
number1 = 2
number2 = 7
number3 = 14
' if 2 > 0 then largest = 2
If number1 > largest Then largest = number1
' if 7 > 2 then largest = 7
If number2 > largest Then largest = number2
' if 14 > 7 then largest = 14
If number3 > largest Then largest = number3
label1.text = largest

The logic requires some re-thinking. At the moment you are using a brute force approach which, as you have already discovered, becomes more complicated the larger the original set. And your solution is not really maintainable - what if you wanted 4 numbers, 10 numbers etc, you would have to rewrite code all the time.
Modern coding languages include loops and collections to make our lives easier.
Function MyMax(Numbers() As Long) As String
Dim largest As Long = Long.MinValue
If Numbers.Count > 0 Then ' it is ok to find the maximum from a single number!
For iterator = 0 To Numbers.Count - 1
If Numbers(iterator) > largest Then largest = Numbers(iterator)
'largest = If(Numbers(iterator) > largest, Numbers(iterator), largest) ' another way of achieving the line above
Next
Return largest.ToString
Else
Return "Error - no numbers to check!"
End If
End Function
Sub testMyMax()
Debug.Print(MyMax({2, 7, 14}))
End Sub

Related

The sum of the first natural 100 numbers

new to coding,
Quick Homework problem Im having trouble on.
I must find the sum of the first 100 natural numbers. 1+2+3+4, and so on. While using "while loops".
This is what I have so far.
Dim sum, count As Integer
Const num As Integer = 1
Console.WriteLine("The Sum of the first 100 natural numbers is:")
count = num + 1
While count <= 100
Count = num + count
End While
Sum = count
Console.WriteLine("{0}", sum)
Console.ReadLine()
I know for a fact the math and while loop is incorrect, but Im not sure how to fix it. I keep getting 101 as my answer.
You do not need the num constant and the line: count = num + 1
While count <= 100
sum += count
count += 1
End While
I know you are learning and the solution must use a While loop but for fun see what you can do in 2 lines of code.
Dim arrNumbers = Enumerable.Range(1, 100).ToArray
Console.WriteLine(arrNumbers.Sum)
Since your question title asked for sums of all [1 - 100] as well as the evens and odds, here is some LINQ for each one
Dim sum = Enumerable.Range(1, 100).Sum()
Dim sumEvens = Enumerable.Range(1, 100).Sum(Function(i) If(i Mod 2 = 0, i, 0))
Dim sumOdds = Enumerable.Range(1, 100).Sum(Function(i) If(i Mod 2 = 0, 0, i))
Console.WriteLine($"Sum: {sum}, Sum evens: {sumEvens}, Sum odds: {sumOdds}")
Sum: 5050, Sum evens: 2550, Sum odds: 2500
Enumerable.Range(1, 100) creates your sequence of all [1 - 100]. Call the LINQ function Sum to simply get the sum, or you can pass a lambda function to Sum to transform the numbers. Use Mod to select evens or odds. The method above sets odds to 0 for the evens, and vice-versa for the odds.
An alternative to this method of transforming the sequence is to use Where to select only even numbers then Sum, which may be more readable.
Dim sumEvens = Enumerable.Range(1, 100).Where(Function(i) i Mod 2 = 0).Sum()
With your code you've done a few things in a weird way.
Let's simplify the code and see what's going wrong.
To start with you are setting num as a constant to the value of 1. Since it's not changing, we'll put the value in directly.
You'd then have this:
count = 1 + 1
While count <= 100
count = 1 + count
End While
sum = count
So that means count will start at 2 and goes up by one until the value of count is greater than 100 - and that's when it is 101.
Then you set sum to count and you get 101.
What you needed to do was start count as 1 and sum up the values inside the loop.
count = 1
While count <= 100
sum = sum + count
count = count + 1
End While
And that gives the correct result of 5050.
While count <= 100
num += count
count += 1
End While
Sum = num

Why does the "Double" data type mess up my Fibonacci sequence?

I am trying to write a program which gives me the index of the first 1000-digit number in the Fibonacci sequence. I have set the data type as "Double" because I need to store the long numbers, however the output I get isn't right?
I have tried setting the "num" data type as "integer", "long" and even "int64", but all these just give me an overflow error after about 2 seconds.
Dim num, prev, temp, index As Double
Sub Main()
num = 1
prev = 1
temp = 1
index = 1
While Len(num) < 1000
Console.WriteLine(num)
temp = num
num += prev
prev = temp
index += 1
End While
Console.WriteLine(index)
Console.ReadLine()
End Sub
I would expect the program to output the Fibonacci sequence until it finds the first 1000-digit number, and then it will output the index of it. However, I just get an output of loads of decimal numbers (to about 20 decimal points) and then it outputs 8. Forever.
I am truly stumped. Any ideas?
The precision of a double data type does not allow you to store so many digits.
If you use BigInteger you can store as many digits as you can, as the data type grows its storage according to your needs.
Additionally, as suggested by the comments, a quick and dirty way to stop after 1000 digits is to have the number converted to string and check its length. This way you are not using mathematical operations which would result in an overflow.
Your code should look like the following:
Dim num, prev, temp, index As BigInteger
Sub Main()
num = 1
prev = 1
temp = 1
index = 1
While BigInteger.Log10(num) <= 999
Console.WriteLine(num)
temp = num
num += prev
prev = temp
index += 1
End While
Console.WriteLine(index)
Console.ReadLine()
End Sub
It all comes down to no data types in vb being able to hold a 1000 digit number. If I were you I would have an array with 1000 items and have each item be a digit.

Is there a better way to set the odds to generating a random number and controling the limits?

I am trying to do a game that has 20 rounds of play. I have assigned 0 thru 8 to represent the items in the game. I need the random number to be 90 percent of the time to be any number 0 thru 5. I need the numbers 6 and 7 to be 4 percent of the time. And, I need the 8 to be only 2 percent of the time. Below is the code I have and it works sometimes but often it generates way too many of the 6s, 7s, and 8's. The way I see the code is that it should be working most of the time correctly but does not. Is there a better way to control the random to get the percents I need to be more consistently?
' Get the random number position into array
Public Sub GetNumPositions(ByVal positions() As Integer)
' 20 rounds, each round 5 numbers
' we want 2 times (8), 4 times (6 and 7)
' 2% 8, 4% 6, 4% 7, and 90% times 0 thru 5
For i As Integer = 0 To positions.Length - 1
Dim p As Integer = rndNums.Next(100)
If p < 90 Then
positions(i) = p \ 15
ElseIf p < 94 Then
positions(i) = 6
ElseIf p < 98 Then
positions(i) = 7
Else
positions(i) = 8
End If
Next
End Sub
Your code is just fine. Here is a method to test it. It gathers some numbers and calculates their frequency:
Sub Main()
Dim count = 100000000
Dim positions(count) As Integer
Dim frequencies(9) As Integer
GetNumPositions(positions)
For Each num In positions
frequencies(num) += 1
Next
For i As Integer = 0 To 8
Console.WriteLine(i & ": " & (100.0 * frequencies(i) / count) & " %")
Next
End Sub
The result is:
0: 14.994567 %
1: 15.000016 %
2: 15.01366 %
3: 14.996542 %
4: 15.002074 %
5: 15.00325 %
6: 4.002246 %
7: 3.999337 %
8: 2.000603 %
As you can see, the frequencies match your input distribution very closely.

How can i choose random number smaller than "1000" or "n" in vb?

How can i choose random number smaller than "1000" or "n"?
Do While ddd <> 1
Static staticRandomGenerator As New System.Random
max += 1
dd = staticRandomGenerator.Next(If(min > max, max, min), If(n > max, min, max))
ddd = ee * dd Mod z
Loop
How can i add this condition to this code? Any idea?
There are two ways to generate a random number in VB.NET (that I am familiar with).
Technique 1:
randomNumber = CInt(Math.Floor((n - 0 + 1) * Rnd())) + 0
n = Upperbound value, otherwise known as the highest value randomNumber can be, which in your case you would have already defined as 1000.
0 = Lowerbound value, otherwise known as the lowest value the randomNumber can be.
You can find more info about this technique here.
Technique 2:
Dim rn As New Random
randomNumber = rn.Next(0, n)
Again, n = Upperbound value, otherwise known as the highest value randomNumber can be, which in your case you would have already defined as 1000.
And again, 0 = Lowerbound value, otherwise known as the lowest value randomNumber can be.
I cannot find a link to an official post about this on the Microsoft MSDN site, but if anyone can find a good post about this technique, please comment, or message me.
I hope this helps!

How to find a position in a integer

If I had a integer that was, for example 11110011. How would I find out what number was in each position so I could use them calculate something. Thanks
cast it to String and then use method of string to find the int at a particular position.
Feel free to read a bit about operators if you wish.
Anyhow i'd use a loop of Mod 10 and divide by 10 each iteration.
Pseudo code:
Given number
While number is not zero
Get the mod 10 of the number
... Do what you need to do with it - that's the digit
Divide by 10.
Repeat.
Done.
for example:
Dim yourNumber As Integer = 12930 // for example.
While index >0
Dim digit As Integer = yourNumber Mod 10
Debug.Write(digit.ToString & " ")
index /= 1
End While
Will write all the digits, seperated by a space:
output: 1 2 3 9 0