Declaration of Arrays in Sub Procedure - vb.net

I can not figure out what problems with those codes are?
It keeps producing:
IndexOutOfRangeException
Module Module1
Sub Main()
Console.WriteLine("Please input the length of the array")
Dim n As Integer = Console.ReadLine()
Dim numbers(n - 1) As Integer
Console.WriteLine("Please inform us the number you want to find")
Dim x As Integer = Console.ReadLine()
For i = 0 To n - 1
Console.WriteLine("Please input the {0} number", i)
numbers(i) = Console.ReadLine()
Next
examining(x, n, numbers(n - 1))
Console.ReadLine()
End Sub
Sub examining(ByVal x As Integer, ByVal n As Integer, ByVal ParamArray numbers() As Integer)
Dim i As Integer
For i = 0 To n - 1
If numbers(i) = x Then
Console.WriteLine("There exists {0} in the array", x)
Exit For
End If
Next
If i = n - 1 Then Console.WriteLine("{0} does not exist in the array", x)
End Sub
End Module

Simply way to check of an array contains something:
If numbers.Contains(x) Then
'it does
Else
'it does not
End If

Related

Binary value can't show properly

I have a problem converting the integer number to binary number, anyone can guide me on which one I get the error in my coding? Thanks.
Imports System.Text
Module Module1
Sub Main()
Dim number As Integer
Console.Write("Please Enter Number: ")
number = Console.ReadLine()
'Print the results
Console.WriteLine("The binary is: " & ConvertDecimalToBinary(number))
End Sub
Private Function ConvertDecimalToBinary(number As Integer) As String
Dim remainder As Integer
Dim num As Integer
'Create a string for binary
Dim sb = New StringBuilder()
Do
remainder = number Mod 2
sb.Insert(0, remainder)
num \= 2
Loop While num = 1
Return remainder
End Function
End Module
This is my output when I insert number 5 then give me the binary number is 1:
I want the output like below the sample picture:
EDIT : There is a more simple solution, here you go :
Sub Main()
Dim number As Integer
Console.Write("Please enter a number : ")
number = Convert.ToInt32(Console.ReadLine)
'Print the results
Console.WriteLine("The binary result of the number is : " & Convert.ToString(number, 2))
Console.ReadKey()
End Sub
This is the translated code from C# to VB from this post :
Private Function ConvertDecimalToBinary(number As Integer) As String
Dim bits As Char() = New Char(32) {}
Dim i As Integer
While number <> 0
bits(i) = If((number And 1) = 1, "1"c, "0"c)
i += 1
number >>= 1
End While
Array.Reverse(bits, 0, i)
Return New String(bits)
End Function
So your main function would be something like this :
Sub Main()
Dim number As Integer
Console.Write("Please enter a number : ")
number = Convert.ToInt32(Console.ReadLine)
'Print the results
Console.WriteLine("The binary result of the number is : " & ConvertDecimalToBinary(number))
Console.ReadKey()
End Sub
There is an easier way, you can try it.https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter?redirectedfrom=MSDN&view=netframework-4.8
Sub Main()
Dim number As Integer
Console.Write("Please Enter Number: ")
number = Console.ReadLine()
'Print the results
Console.WriteLine("The binary is: " & Convert.ToString(number, 2))
Console.ReadKey()
End Sub

vb.net readline or readkey don't want to stop my program

my code is working i tried it separately but the problem here is that when i'm putting them together , the readkey or readline don't stop the program and the do loop is not working too, can someone take a look please thank in advance
Dim count As Integer
Dim first(5) As Integer
Dim temp As Integer
Dim answer As String
Sub Main()
Do
Console.WriteLine("Please enter your first number")
first(0) = Console.ReadLine
Console.WriteLine("Please enter your second number")
first(1) = Console.ReadLine
Console.WriteLine("Please enter your third number")
first(2) = Console.ReadLine
Console.WriteLine("Please enter your fourth number")
first(3) = Console.ReadLine
Console.WriteLine("Please enter your fifth number")
first(4) = Console.ReadLine
Console.WriteLine("Please enter your sixth number")
first(5) = Console.ReadLine
randomnumber()
Console.WriteLine("do you want to continue?")
answer = Console.ReadLine
Loop Until (answer = "n" Or answer = "No")
Console.ReadKey()
End Sub
Sub randomnumber()
Dim r As New List(Of Integer)
Dim rg As New Random
Dim rn As Integer
Dim arraywinner(5) As Integer
Do
rn = rg.Next(1, 40)
If Not r.Contains(rn) Then
r.Add(rn)
End If
Loop Until r.Count = 6
'store bane random value in array'
arraywinner(0) = r(0)
arraywinner(1) = r(1)
arraywinner(2) = r(2)
arraywinner(3) = r(3)
arraywinner(4) = r(4)
arraywinner(5) = r(5)
'print random numbers
count = 0
While count <= 5
Console.WriteLine("the randoms numbers are : " & arraywinner(count))
count = count + 1
End While
'look for the amount of number
temp = 0
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If arraywinner(count1) = first(count2) Then
temp = temp + 1
End If
Next
Next
If temp = 1 Or temp = 0 Then
Console.WriteLine("You have got " & temp & " number")
Else
Console.WriteLine("You have got " & temp & " numbers")
End If
money(temp)
End Sub
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
You have two problems in money():
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
Your parameter is t1, but you're using temp in all of your code. As written, it will still work since temp is global, but you should either change the code to use t1, or not pass in that parameter at all.
Secondly, you have End in the block for 0, 1, or 2 matches. The End statement Terminates execution immediately., which means the program just stops. Get rid of that line.
There are so many other things you could change, but that should fix your immediate problem...
I moved all the display code to Sub Main. This way your Functions with your business rules code can easily be moved if you were to change platforms. For example a Windows Forms application. Then all you would have to change is the display code which is all in one place.
Module Module1
Private rg As New Random
Public Sub Main()
'keep variables with as narrow a scope as possible
Dim answer As String = Nothing
'This line initializes and array of strings called words
Dim words = {"first", "second", "third", "fourth", "fifth", "sixth"}
Dim WinnersChosen(5) As Integer
Do
'To shorten your code use a For loop
For index = 0 To 5
Console.WriteLine($"Please enter your {words(index)} number")
WinnersChosen(index) = CInt(Console.ReadLine)
Next
Dim RandomWinners = GetRandomWinners()
Console.WriteLine("The random winners are:")
For Each i As Integer In RandomWinners
Console.WriteLine(i)
Next
Dim WinnersCount = FindWinnersCount(RandomWinners, WinnersChosen)
If WinnersCount = 1 Then
Console.WriteLine($"You have guessed {WinnersCount} number")
Else
Console.WriteLine($"You have guessed {WinnersCount} numbers")
End If
Dim Winnings = Money(WinnersCount)
'The formatting :N0 will add the commas to the number
Console.WriteLine($"Your winnings are {Winnings:N0}")
Console.WriteLine("do you want to continue? y/n")
answer = Console.ReadLine.ToLower
Loop Until answer = "n"
Console.ReadKey()
End Sub
'Too much happening in the Sub
'Try to have a Sub or Function do only one job
'Name the Sub accordingly
Private Function GetRandomWinners() As List(Of Integer)
Dim RandomWinners As New List(Of Integer)
Dim rn As Integer
'Good use of .Contains and good logic in Loop Until
Do
rn = rg.Next(1, 40)
If Not RandomWinners.Contains(rn) Then
RandomWinners.Add(rn)
End If
Loop Until RandomWinners.Count = 6
Return RandomWinners
End Function
Private Function FindWinnersCount(r As List(Of Integer), WinnersChosen() As Integer) As Integer
Dim temp As Integer
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If r(count1) = WinnersChosen(count2) Then
temp = temp + 1
End If
Next
Next
Return temp
End Function
Private Function Money(Count As Integer) As Integer
'A Select Case reads a little cleaner
Select Case Count
Case 3
Return 120
Case 4
Return 500
Case 5
Return 10000
Case 6
Return 1000000
Case Else
Return 0
End Select
End Function
End Module

Visual Basic loop sum of integers ^ 2 till user input. power of 2

I need help with one simple task:
Input an integer number n and output the sum: 1 + 2^2 + 3^2 + ... + n^2. Use input validation for n to be positive.
My code does not work and till now is:
Sub Main()
Dim inputNumber As Integer
Console.WriteLine("Please enter a positive number.")
inputNumber = Console.ReadLine()
If inputNumber <= 0 Then
Console.WriteLine("Please use only positive numbers > 0 !")
End If
Dim sum As Integer
Dim i As Integer = 1
For i = 1 To i <= inputNumber
sum = sum + (i * i)
i = i + 1
Next
Console.WriteLine(sum)
Console.ReadLine()
End Sub
Try these changes:
Dim inputNumber as Long ' not Integer. Also change sum, i.
...
inputNumber = CLng(Console.ReadLine) ' make it a number, not a string
...
Dim sum as Long ' yum
dim i as Long ' don't assign it here
for i = 1 to inputNumber ' don't use "<=" in a for loop
...
' i = i+1 ' Don't increment i within the loop, since the loop does that for you.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Input As Integer
Input = TextBox1.Text
Dim i As Integer
i = 0
Dim x As Integer
x = 0
Dim y As Integer
y = 0
For a = 1 To Input
y = Math.Pow(a, (Input - i))
x = Math.Pow(a, (Input - i)) + x
i = i + 1
Next
Label1.Text = x
End Sub

vb .net permutation of string. permutation or combination?

i've got arary of string like this C - F - A - M. i want to create a combination from that with condition:
each other item beside last character has to be combined with last character
there's not allowed a same combination, even the order is different. for example
FC - M
CF - M
if the string array contains >=3 element it will generate 2 & 3 itemset, if 2 element then it will generate only 2 itemset
below is my code. my code generate the result like right part of the picture
my question is what method should i use? is it permutation, combination, or other things?
and in pseudocode, what is my case would be like?
here's my code
Public Class permute
Dim ItemUsed() As Boolean
Dim pno As Long, pString As String
Dim inChars() As Char = {"c", "f", "a", "m"}
Private Sub permute_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Sub Permute(ByVal K As Long)
ReDim ItemUsed(K)
pno = 0
Dim i As Integer
For i = 2 To K
Permutate(i, 1)
tb.Text = K
Next
End Sub
Private Sub Permutate(ByVal K As Long, ByVal pLevel As Long)
Dim i As Long, Perm As String
Perm = pString
For i = 0 To K - 1
If Not ItemUsed(i) Then
If pLevel = 1 Then
pString = inChars(i)
Else
pString += inChars(i)
End If
If pLevel = K Then
pno = pno + 1
Results.Text += _
pno & " " & " = " & " " & pString & vbCrLf
Exit Sub
End If
ItemUsed(i) = True
Permutate(K, pLevel + 1)
ItemUsed(i) = False
pString = Perm
End If
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Permute(tb.Text)
End Sub
Private Sub tb_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tb.TextChanged
If tb.Text = "" Then
Results.Text = ""
Else
Permute(tb.Text)
End If
End Sub
End Class
here's the requirement screenshot
and here's the program screenshot
Add this class to your project:
Public NotInheritable Class Permutation
Public Shared Function Create(array As Char()) As List(Of String)
Return Permutation.Create(array, False)
End Function
Public Shared Function Create(array As Char(), sort As Boolean) As List(Of String)
If (array Is Nothing) Then
Throw New ArgumentNullException("array")
ElseIf ((array.Length < 0) OrElse (array.Length > 13)) Then
Throw New ArgumentOutOfRangeException("array")
End If
Dim list As New List(Of String)
Dim n As Integer = array.Length
Permutation.Permute(list, array, 0, array.Length)
If (sort) Then
list.Sort()
End If
Return list
End Function
Private Shared Sub Permute(list As List(Of String), array As Char(), start As Integer, n As Integer)
Permutation.Print(list, array, n)
If (start < n) Then
Dim i, j As Integer
For i = (n - 2) To start Step -1
For j = (i + 1) To (n - 1)
Permutation.Swap(array, i, j)
Permutation.Permute(list, array, (i + 1), n)
Next
Permutation.RotateLeft(array, i, n)
Next
End If
End Sub
Private Shared Sub Print(list As List(Of String), array As Char(), size As Integer)
If (array.Length <> 0) Then
Dim s As Char() = New Char(size - 1) {}
For i As Integer = 0 To (size - 1)
s(i) = array(i)
Next
list.Add(s)
End If
End Sub
Private Shared Sub RotateLeft(array As Char(), start As Integer, n As Integer)
Dim tmp As Char = array(start)
For i As Integer = start To (n - 2)
array(i) = array(i + 1)
Next
array(n - 1) = tmp
End Sub
Private Shared Sub Swap(array As Char(), i As Integer, j As Integer)
Dim tmp As Char
tmp = array(i)
array(i) = array(j)
array(j) = tmp
End Sub
End Class
Because of the Int32.MaxValue limit this class will support levels 1 through 13.
s=1, n=1
s=2, n=2
s=3, n=6
s=4, n=24
s=5, n=120
s=6, n=720
s=7, n=5040
s=8, n=40320
s=9, n=362880
s=10, n=3628800
s=11, n=39916800
s=12, n=479001600
s=13, n=6227020800
Usage:
Me.TextBox1.Text = String.Join(Environment.NewLine, Permutation.Create({"c"c, "f"c, "a"c, "m"c}, sort:=False))
Output:
cfam
cfma
cafm
camf
cmfa
cmaf
fcam
fcma
facm
famc
fmca
fmac
acfm
acmf
afcm
afmc
amcf
amfc
mcfa
mcaf
mfca
mfac
macf
mafc
The class is based on C++ code from the following link:
Calculating Permutations and Job Interview Questions
This seems to be a Combination problem rather than Permutation :
"In mathematics, a combination is a way of selecting several things out of a larger group, where (unlike permutations) order does not matter". [Wikipedia]
Try to solve this by doing Combination to all item in array except the last item. Or in other words, do Combination operations nCk for all k, with
n = size of input array minus the last item
k = size of the output itemset, minimum k is 1 and maximum is n
Then append each Combination result with the last item. Following is the pseudocode code, using C# syntax :p
var input = new char[] {'C', 'F', 'A', 'M'};
//save last char
var lastChar = input[input.Length - 1];
//combinationInput is input member without the last character
var combinationInput = new char[input.Length - 1];
Array.Copy(input, 0, combinationInput, 0, combinationInput.Length);
//generate output with itemset size 1 to combinationInput.Length
for (int i = 1; i <= combinationInput.Length; i++)
{
//generate combination with size i
var combinationOutput = combinationInput.Combinations(i);
foreach (var combinedChar in combinationOutput)
{
//print output as: combinationOutput item + lastChar
Console.WriteLine(string.Join(", ", combinedChar) + ", " + lastChar);
}
}
References :
Array.Copy(...). [How to copy part of an array to another array]
.Combinations(int outputSize) extension method. [How to Generate Combinations of Elements of a List in .NET 4.0]

get combinations with repetition

How can I write all possible combinations to the console? For example, if user enters abc, then it will write aaa, aab, aac, abb, abc, acc, bbb, bbc, ccc. Please help me.
Here's some code:
Dim abc() As String = {"a", "b", "c"} '
Sub Main()
Console.WriteLine("Enter the amount of characters")
Dim count As Integer = Console.ReadLine
outputStrings("", count)
Console.ReadLine()
End Sub
Private Sub outputStrings(ByVal startString As String, ByVal letterCount As Integer)
For i = 0 To abc.Length - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
If i = abc.Length - 1 Then
Console.WriteLine("----")
End If
Else
outputStrings(temp, letterCount)
End If
Next
End Sub
Something has to be done after the dashed lines to remove unwanted permutation to leave out only valid combinations.
You can restrict the letters used to ones at or to the right of abc(i) with an additional parameter abcIndex, and start the for loop from there. Only strings which have their letters in alphabetical order will be written, which prevents duplicates.
Private Sub outputStrings(ByVal startString As String, ByVal letterCount As Integer, ByVal abcIndex As Integer)
For i = abcIndex To abc.Length - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
Else
outputStrings(temp, letterCount, i)
End If
Next
End Sub
Call with:
outputStrings("", 3, 0)
def go(chars,thusfar):
if len(thusfar) = len(chars):
print thusfar
for char in chars:
go(chars,thusfar+char);
This should be easy enough to translate to VB (read: I don't know VB)
You just need to make a recursive call there.
Dim abc() As String = {"a", "b", "c"} '
Sub Main()
Console.WriteLine("Enter the amount of characters")
Dim count As Integer = Console.ReadLine
outputStrings("", count)
Console.ReadLine()
End Sub
Private Sub outputStrings(ByVal startString As String, ByVal letterCount As Integer)
For i = 0 To abc.Count - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
Else
outputStrings(temp, letterCount)
End If
Next
End Sub
Do note that if someone enters a negative number that your code will run forever. I'll leave fixing that as an easy exercise.
Amazing code from here:
Private Shared Function PermutationsWithRepetition(Of T)(list As IEnumerable(Of T), length As Integer) As IEnumerable(Of IEnumerable(Of T))
If length = 1 Then
Return list.[Select](Function(x) New T() {x})
End If
Return PermutationsWithRepetition(list, length - 1).SelectMany(Function(x) list, Function(t1, t2) t1.Concat(New T() {t2}))
End Function
Can be used with Integer, Char, Double etc.
Example of use:
Dim myarray(1) As Integer
myarray(0) = 1
myarray(1) = 2
Dim k As Integer = 2 'number of "slots" to do the permutations
mypermutations = PermutationsWithRepetition(myarray,k)
For Each row As IEnumerable(Of Integer) In mypermutations
Console.WriteLine("")
For Each col As IntegerIn row
Console.Write(col.toString())
Next
Next
Output:
11
12
21
22