How to randomize a math function/operator in visual basic (console) - vb.net

This is my code so far
Module Module1
Sub Main()
Randomize()
Dim number1 As Integer
Dim number2 As Integer
Dim answer As Integer
Dim userAnswer As Integer
Dim name As String
Console.WriteLine("Hello! Welcome to your Maths Quiz! Please enter your name >")
name = Console.ReadLine
Console.WriteLine("Nice to meet you " + name + ". Lets start the quiz")
Randomize()
number1 = Rnd() * 11 + 1
number2 = Rnd() * 11 + 1
answer = number1 + number2
Try
For i As Integer = 0 To 10
Console.WriteLine("What is " & number1 & " + " & number2 & " = ?")
userAnswer = Console.ReadLine
If userAnswer = answer Then
Console.WriteLine("Correct!")
Else
Console.WriteLine("Incorrect, the answer was " & answer)
End If
Next
Catch ex As InvalidCastException
Console.WriteLine("Oops you have typed in a number, please start over")
End Try
Console.ReadKey()
End Sub
End Module
I need to create a random function to take place of the "+" sign and i have tried many ways but the output comes up weird, i was wondering if you can help, Thanks

If you are going for + - * / then I would do this, if only + - and could go with IIF statments
Create a new random variable operator
op = Int(Rnd() * 4) '0+ 1- 2* 3/
Calculate the anwser with a function
answer= calc(number1, number2, op)
Function calc(n1, n2, op)
If op = 0 Then calc = n1 + n2
If op = 1 Then calc = n1 - n2
If op = 2 Then calc = n1 * n2
If op = 3 Then calc = n1 / n2
End Function
And 1 more function to get the operator sign
Console.WriteLine("What is " & number1 & s_op(op) & number2 & " = ?")
Function s_op(op)
If op = 0 Then s_op = "+"
If op = 1 Then s_op = "-"
If op = 2 Then s_op = "*"
If op = 3 Then s_op = "/"
End Function

Related

Visual basics help-Variables in for loop

I'm trying to get the integers of "num3"(input from the user) and squaring each character and eventually see if its a "happy number"=1 or a "unhappy number" includes 4
For example, 19 is happy number 1^2+9^2=82 , 8^2+2^2=68,6^2+8^2=100, 1^2+0+0=1
Sub Main()
Dim number, num2, total As Integer
Dim num3 As String
Console.Write("pick a number:")
number = Console.ReadLine()
num2 = 0
num3 = Convert.ToString(number)
Do Until total = 1 Or num2 = 4
For Each num3 In num3.Substring(0, num3.Length)
For counter = 1 To num3.Length And num3 = num3.Substring(0, num3.Length)
num2 = num3 ^ 2
total = total + num2
Console.WriteLine(total)
Next
num3 = total
Next
Loop
Console.ReadLine()
If total = 1 Then
Console.WriteLine("happy number")
ElseIf num2 = 4 Then
Console.WriteLine(number & "is a unhappy number")
Console.ReadLine()
End If
End Sub
End Module
however i'm stuck whether "num3" replace itself from the for loop
Here, I believe this should work:
Dim InputNum As Integer = 45 'Your input number
Dim TempNum As Integer = InputNum 'Here we hold number temporarily during steps 19>82....
Do
Dim SumTotal As Double = 0 'sum of numbers squares
For Each number As Char In TempNum.ToString
SumTotal += Integer.Parse(number) ^ 2
Next
TempNum = CInt(SumTotal)
Debug.Print(TempNum.ToString)
'If result is 4 it will loop forever
If SumTotal = 4 Then
Console.WriteLine(InputNum & " is an unhappy number")
Exit Do
ElseIf SumTotal = 1 Then
Console.WriteLine(InputNum & " is a happy number")
Exit Do
End If
Loop

VB - comparing numbers in two labels

I'm doing a school project in Visual Basic (using visual studio 2015) and i'm kinda stuck.
My goal is to create a lottery, where player chooses 6 numbers from checkboxes, then he generates six random numbers (1 - 49) and finally, those two sets should be compared and needed result is the number of correctly guessed numbers.
I have both results (guessed numbers, generated numbers) saved in two different labels.
The checkboxes itself are genereted like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lev = 20
tt = 0
For j = 1 To 50
tt = tt + 1
n = n + 1
box(j) = New CheckBox
box(j).Name = "box(" & Str(j) & ")"
If n = 11 Then lev = lev + 110 : n = 1 : tt = 1
box(j).Left = lev
box(j).Parent = Me
box(j).Top = tt * 20
box(j).Tag = j
box(j).Text = j
box(j).Visible = True
Next
box(50).Enabled = False
End Sub
First label (guessed numbers) is filled this way (i'm not posting whole code)
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + " " + box(j).Text
Next
and the second one (generated numbers) like this:
Do
rn = rg.Next(1, 50)
If Not r.Contains(rn) Then
r.Add(rn)
End If
Loop Until r.Count = 6
Label1.Text = r(0).ToString + " " + r(1).ToString + " " + r(2).ToString + " " + r(3).ToString + " " + r(4).ToString + " " + r(5).ToString
any idea how to compare numbers stored in those labels and get the result (number of correctly guessed numbers).
thanks in advance
You can compare numbers in the labels by splitting the Text properties of the labels into arrays of strings and converting them to integer arrays. First though there is a tiny problem with your code that adds the guessed numbers to the label.
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + " " + box(j).Text
Next
The " " should be moved to the end of the line because at the moment, the label will always start with a space and that messes with the function below. So you should have -
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + box(j).Text + " "
Next
Ok. The function below splits the two text labels into their own array and loops through the guesses and checks if any number is contained in the generated numbers. It then returns the number of matches.
Private Function ComparePicks() As Integer
Dim numbersMatched As Integer
Dim picks(5) As Integer
Dim generatedNumbers(5) As Integer
For i As Integer = 0 To 5
picks(i) = CInt(Split(Label9.Text, " "c)(i))
Next
For i As Integer = 0 To 5
generatedNumbers(i) = CInt(Split(Label1.Text, " "c)(i))
Next
For i As Integer = 0 To 5
If generatedNumbers.Contains(picks(i)) Then
numbersMatched += 1
End If
Next
Return numbersMatched
End Function

Converting RGB value into integers

I'm making an app with a color dropper tool on it using g.CopyFromScreen(screenpoint, Point.Empty, Bmp2.Size) (the dropper tool works currently), once I have the dropper values I want to convert the RBG values into individual integers.
The values that i'm converting are in this format
Color [A=255, R=240, G=240, B=240]
which needs to be in four different integers
My code is giving me odd results and I'm lost now
My code:
Dim text1Conv As String
text1Conv = TextBox1.Text
Dim myChars() As Char = text1Conv.ToCharArray()
For Each ch As Char In myChars
If Char.IsDigit(ch) And Not ch = " " And Not ch = "," And Not count > 2 Then
color1Conv = color1Conv + ch
TextBox2.Text = TextBox2.Text + color1Conv 'test result
count = count + 1
ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 2 And Not count > 5 Then
color2Conv = color2Conv + ch
TextBox2.Text = TextBox2.Text + color2Conv 'test result
count = count + 1
ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 5 And Not count > 8 Then
color3Conv = color3Conv + ch
TextBox2.Text = TextBox2.Text + color3Conv 'test result
count = count + 1
ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 8 And Not count > 11 Then
color4Conv = color4Conv + ch
TextBox2.Text = TextBox2.Text + color4Conv 'test result
count = count + 1
End If
Next
results: 225 255 118 112 122
results: 225 255 116 772 721
probably an easy one but I can't see it
Using regular expressions:
I used "[A=255, R=241, G=24, B=2]" as a test string and split it into four integers.
Dim a as Integer, r as Integer, g as Integer, b as Integer
Dim s as String = "[A=255, R=241, G=24, B=2]"
Dim mc as MatchCollection = System.Text.RegularExpressions.Regex.Matches( s, "(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+", RegexOptions.None )
Integer.TryParse( mc(0).Groups(1).Value, a )
Integer.TryParse( mc(0).Groups(2).Value, r )
Integer.TryParse( mc(0).Groups(3).Value, g )
Integer.TryParse( mc(0).Groups(4).Value, b )
NOTE: it will have no problems with numbers being 1, 2, or any number of digits long.
You can use regular expressions:
Imports System.Text.RegularExpressions
Dim input As String = "Color [A=255, R=240, G=240, B=240]"
Dim re As New Regex("Color \[A=(\d+), R=(\d+), G=(\d+), B=(\d+)\]")
Dim m As Match = re.Match(input)
Dim integer1 As Integer = Convert.ToInt32(m.Groups(1).Value) '255
Dim integer2 As Integer = Convert.ToInt32(m.Groups(2).Value) '240
Dim integer3 As Integer = Convert.ToInt32(m.Groups(3).Value) '240
Dim integer4 As Integer = Convert.ToInt32(m.Groups(4).Value) '240

Calculate words value in vb.net

I have a textbox on a form where the user types some text. Each letter is assigned a different value like a = 1, b = 2, c = 3 and so forth. For example, if the user types "aa bb ccc" the output on a label should be like:
aa = 2
bb = 4
dd = 6
Total value is (12)
I was able to get the total value by looping through the textbox string, but how do I display the total for each word. This is what I have so far:
For letter_counter = 1 To word_length
letter = Mid(txtBox1.Text, letter_counter, 1)
If letter.ToUpper = "A" Then
letter_value = 1
End If
If letter.ToUpper = "B" Then
letter_value = 2
End If
If letter.ToUpper = "C" Then
letter_value = 3
End If
If letter.ToUpper = "D" Then
letter_value = 4
End If
If letter.ToUpper = "E" Then
letter_value = 5
End If
If letter.ToUpper = " " Then
letter_value = 0
End If
totalletter = totalletter + letter_value
Label1.Text = Label1.Text & letter_value & " "
txtBox2.Text = txtBox2.Text & letter_value & " "
Next letter_counter
This simple little routine should do the trick:
Private Sub CountLetters(Input As String)
Label1.Text = ""
Dim total As Integer = 0
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("a"c, 1)
dicLetters.Add("b"c, 5)
dicLetters.Add("c"c, 7)
For Each word As String In Input.Split
Dim wordtotal As Integer = 0
For Each c As Char In word
wordtotal += dicLetters(Char.ToLower(c))
Next
total += wordtotal
'Display word totals here
Label1.Text += word.PadRight(12) + "=" + wordtotal.ToString.PadLeft(5) + vbNewLine
Next
'Display total here
Label1.Text += "Total".PadRight(12) + "=" + total.ToString.PadLeft(5)
End Sub
This should give you an idea:
Dim listOfWordValues As New List(Of Integer)
For letter_counter = 1 To word_length
letter = Mid(txtBox1.Text, letter_counter, 1)
If letter = " " Then
totalletter= totalletter + letter_value
listOfWordValues.Add(letter_value)
letter_value = 0
Else
letter_value += Asc(letter.ToUpper) - 64
End If
Next letter_counter
totalletter = totalletter + letter_value
If Not txtBox1.Text.EndsWith(" ") Then listOfWordValues.Add(letter_value)
txtBox2.Text = txtBox2.Text & string.Join(", ", listOFWordValues);
You can try something like this. Assuming txtBox1 is the string the user enters and " " (space) is the word delimiter:
Dim words As String() = txtBox1.Text.Split(New Char() {" "}, StringSplitOptions.RemoveEmptyEntries)
Dim totalValue As Integer = 0
Dim wordValue As Integer = 0
For Each word As String In words
wordValue = 0
For letter_counter = 1 To word.Length
Dim letter As String = Mid(txtBox1.Text, letter_counter, 1)
Select letter.ToUpper()
Case "A":
wordValue = wordValue + 1
Case "B":
wordValue = wordValue + 2
' And so on
End Select
Next
totalValue = toalValue + wordValue
Next
The above code first takes the entered text from the user and splits it on " " (space).
Next it sets two variables - one for the total value and one for the individual word values, and initializes them to 0.
The outer loop goes through each word in the array from the Split performed on the user entered text. At the start of this loop, it resets the wordValue counter to 0.
The inner loop goes through the current word, and totals up the values of the letter via a Select statement.
Once the inner loop exits, the total value for that word is added to the running totalValue, and the next word is evaluated.
At the end of these two loops you will have calculated the values for each word as well as the total for all the worlds.
The only thing not included in my sample is updating your label(s).
Try this ..
Dim s As String = TextBox1.Text
Dim c As String = "ABCDE"
Dim s0 As String
Dim totalletter As Integer
For x As Integer = 0 To s.Length - 1
s0 = s.Substring(x, 1).ToUpper
If c.Contains(s0) Then
totalletter += c.IndexOf(s0) + 1
End If
Next
MsgBox(totalletter)
I would solve this problem using a dictionary that maps each letter to a number.
Private Shared ReadOnly LetterValues As Dictionary(Of Char, Integer) = GetValues()
Private Shared Function GetValues() As IEnumerable(Of KeyValuePair(Of Char, Integer))
Dim values As New Dictionary(Of Char, Integer)
Dim value As Integer = 0
For Each letter As Char In "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
value += 1
values.Add(letter, value)
Next
Return values
End Function
Public Function CalculateValue(input As String) As Integer
Dim sum As Integer = 0
For Each letter As Char In input.ToUpperInvariant()
If LetterValues.ContainsKey(letter) Then
sum += LetterValues.Item(letter)
End If
Next
Return sum
End Function
Usage example:
Dim sum As Integer = 0
For Each segment As String In "aa bb ccc".Split()
Dim value = CalculateValue(segment)
Console.WriteLine("{0} = {1}", segment, value)
sum += value
Next
Console.WriteLine("Total value is {0}", sum)
' Output
' aa = 2
' bb = 4
' ccc = 9
' Total value is 15

Loops - Adding Numbers - Visual Basic

So the program has to add all the numbers from "x" to "y".
But it also has to display all the numbers added :
i.e. 10 to 20 should display 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 = 165
Here's what I have:
Dim firstnum As Integer = Val(TextBox1.Text)
Dim secondnum As Integer = Val(TextBox2.Text)
Dim sum As Integer = 0
While firstnum <= secondnum
sum = sum + firstnum
firstnum = firstnum + 1
Label3.Text = firstnum & "+"
End While
suum.Text = " = " & Val(sum)
With the following:
Label3.Text = firstnum & "+"
You are overwriting the value in Label3 every time you go through the loop. What you probably want to do is concatenate the existing value with the next number.
This should get you on your way:
Label3.Text = Label3.Text & firstnum & " + "
Is Linq ok? Then you can use Enumerable.Range and Enumerable.Sum:
Dim startNum = Int32.Parse(TextBox1.Text)
Dim endNum = Int32.Parse(TextBox2.Text)
Dim numbers = Enumerable.Range(startNum, endNum - startNum + 1) 'inclusive, therefore + 1
Label3.Text = String.Join(" + ", numbers)
suum.Text = numbers.Sum()
your Label3.Text will only contain the last num and "+" at the end of the algorithm. You should replace
Label3.Text = firstnum & "+"
with
Label3.Text = Label3.Text & firstnum & "+ "