Visual basic : Calculate Average function returning infinity - vb.net

I am supposed to calculate the average number of words and then convert them into a percentage, however they are displaying infinity. The code I am using is below .
Public Class Form1
Private Structure advertisements
Public name As String
Public words As Integer
Public font() As fonts
Public mostLegible As String
End Structure
Private Structure fonts
Public name As String
Public NoWords() As Integer
Public aveWords As Double
Public percent As Double
End Structure
Private noAdverts As Integer
Private noFonts As Integer
Private noReaders As Integer
Private advert() As advertisements
Private Sub GridPlacement(ByVal r As Integer, ByVal c As Integer, ByVal t As String)
grdDisplay.Row = r
grdDisplay.Col = c
grdDisplay.Text = t
End Sub
Private Sub gridAndArraySettings()
Dim x, y As Integer
ReDim advert(noAdverts)
For x = 1 To noAdverts
ReDim advert(x).font(noFonts)
For y = 1 To noFonts
ReDim advert(x).font(y).NoWords(noReaders)
'GridPlacement(0, y, "font " & CStr(y))
Next
Next
grdDisplay.Cols = noFonts + 2
grdDisplay.Rows = noAdverts + 1
GridPlacement(0, 0, "Name of advert")
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
noAdverts = CInt(txtadverts.Text)
noReaders = CInt(txtReaders.Text)
noFonts = CInt(txtFonts.Text)
gridAndArraySettings()
End Sub
Private Sub btnInput_Click(sender As Object, e As EventArgs) Handles btnInput.Click
Dim x, y, z As Integer
Dim total(,) As Integer
ReDim total(noAdverts, noFonts)
For x = 1 To noAdverts
advert(x).name = InputBox("please enter the name of advert " & CStr(x))
advert(x).words = CInt(InputBox("please enter the number of words for " & advert(x).name))
GridPlacement(x, 0, advert(x).name)
For y = 1 To noFonts
advert(x).font(y).name = InputBox("please enter the name of font " & CStr(y) & " Used in advert " & CStr(x))
For z = 1 To noReaders
advert(x).font(y).NoWords(z) = CInt(InputBox("please enter the number of words understood by reader " & CStr(z) & " for font " & advert(x).font(y).name & " in advert " & advert(x).name))
total(x, y) += advert(x).font(y).NoWords(z)
Next
advert(x).font(y).aveWords = calcAve(total(x, y))
advert(x).font(y).percent = advert(x).font(y).aveWords * 100
GridPlacement(x, y, CStr(advert(x).font(y).aveWords)) 'Format(advert(x).font(y).percent, "###%")
Next
Next
End Sub
Private Function calcAve(ByVal elements As Integer) As Double
Dim x, y As Integer
Dim placeholder As Double = 1
Select Case elements
Case Is > 0
For x = 1 To noAdverts
For y = 1 To noFonts
advert(x).font(y).aveWords = (elements / noReaders) / advert(x).words
placeholder = advert(x).font(y).aveWords
MsgBox(CStr(placeholder))
Next y
Next x
Case Is = 0
MsgBox("There is incorrect values ")
End Select
Return placeholder
End Function
End Class
The textboxes are called txtadverts, txtfonts and txtreaders
The button btnsubmit gets the input from the textboxes and stores them in variables. btninput allows input from user.
GrdDisplay is a custom extension used by my university which is a 2D grid used to diplay values.

Related

Attach VBA Class Object to Visio shape

Question
I have a shape in visio 2021 , which is the "GRID" found in "Charting Shapes"
I would like to scale the smaller shapes in the master according to the ratios. Therefore I would like to bind a new instance of the class I created below to my master, and then be able to resize the master, which intern would scale the components relative to the ratios.
Code
Class name = LWR_Calc
Private Widths() As Double
Private Heights() As Double
Private W, H As Double
Private TotalWidthRatio, TotalHeightRatio
Private WidthRatioSubDivision, HeightRatioSubDivision
Private Sub Class_Initialize()
W = 1
H = 1
End Sub
Public Sub SetWidths(Lst As String, Optional delimiter As String = ",")
Dim WidthsRatioStrArr() As String
Dim Current As Double
WidthsRatioStrArr = Split(Lst, delimiter)
TotalWidthRatio = 0
ReDim Widths(0 To UBound(WidthsRatioStrArr))
For i = 0 To UBound(WidthsRatioStrArr)
Current = CDbl(WidthsRatioStrArr(i))
Widths(i) = Current
TotalWidthRatio = TotalWidthRatio + Current
Next
WidthRatioSubDivision = W / TotalWidthRatio
End Sub
Public Sub SetHeights(Lst As String, Optional delimiter As String = ",")
Dim HeightsRatioStrArr() As String
Dim Current As Double
HeightsRatioStrArr = Split(Lst, delimiter)
TotalHeightRatio = 0
ReDim Heights(0 To UBound(HeightsRatioStrArr))
For i = 0 To UBound(HeightsRatioStrArr)
Current = CDbl(HeightsRatioStrArr(i))
Heights(i) = Current
TotalHeightRatio = TotalHeightRatio + Current
Next
HeightRatioSubDivision = H / TotalHeightRatio
End Sub
Public Function GetHeight(ByVal index As Integer) As Double
On Error GoTo endr:
GetHeight = Heights(index - 1) * HeightRatioSubDivision
Exit Function
endr:
GetHeight = 0
End Function
Public Function GetWidth(ByVal index As Integer) As Double
On Error GoTo endr:
GetWidth = Widths(index - 1) * WidthRatioSubDivision
Exit Function
endr:
GetWidth = 0
End Function
Public Property Let Width(ByVal vNewValue As Double)
W = vNewValue
End Property
Public Property Let Height(ByVal vNewValue As Double)
H = vNewValue
End Property
my sub which tests the code is as follows
Private Sub Test__LWR_Calc()
Dim LWRC As LWR_Calc
Set LWRC = New LWR_Calc
LWRC.Height = 2
LWRC.Width = 10
LWRC.SetWidths ("1.75,1,1,1,1,1,1,1,1,1")
LWRC.SetHeights ("1.75,1,1,1.75,1,1,1,1,1,1")
For i = 1 To 10
For j = 1 To 10
Debug.Print i & "-" & j & " "; LWRC.GetWidth(j) & " , " & LWRC.GetHeight(i)
Next
Next
Set LWRC = Nothing
End Sub
This code works to get the values below
Data
Output
The Outputs I Get vs the Output I Want.

Visual Basic Confusion

I have been required to create a program that asks me to find the maximum value of one particular array. I am using multiple forms in this project and have used a user-defined data type and created multiple array under it. There is a first form that is related to this, which defines my defined data type is gStudentRecord and the arrays that define it are last name, Id, and GPA. This second form is where I write all of the code to display what I want. My question is how to get the Max GPA out of that array. I'm sorry if this isn't in very good format, this is the first time I've used Stackoverflow
Public Class frmSecond
Private Sub frmSecond_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Ctr As Integer
Dim Line As String
lstDisplay.Items.Clear()
lstDisplay.Items.Add("Name".PadRight(25) & "ID".PadRight(16) & "GPA".PadRight(20) & "Out of state".PadRight(10))
For Ctr = 0 To gIndex Step 1
Line = gCourseRoster(Ctr).LastName.PadRight(20) & gCourseRoster(Ctr).ID.PadRight(15) & gCourseRoster(Ctr).GPA.ToString.PadRight(15) & gCourseRoster(Ctr).OutOfState.ToString().PadLeft(5)
lstDisplay.Items.Add(Line)
Next
End Sub
Private Sub btnStats_Click(sender As Object, e As EventArgs) Handles btnStats.Click
Dim Ctr As Integer = 0
Dim Average As Double
Dim Sum As Double
Dim Found As Boolean = False
Dim Pass As Integer
Dim Index As Integer
lstDisplay.Items.Clear()
**For Ctr = 0 To gIndex Step 1
If gCourseRoster(Ctr).GPA > gCourseRoster(Ctr).GPA Then
lstDisplay.Items.Add(gCourseRoster(Ctr).GPA)
End If
Next**
Average = gComputeAverage(Sum)
lstDisplay.Items.Add("Number of Students: " & gNumberOfStudents)
lstDisplay.Items.Add("Average: " & Average)
End Sub
Private Function gComputeAverage(Sum As Double) As Double
Dim Ctr As Integer
Dim Average As Double
For Ctr = 0 To gIndex Step 1
Sum = Sum + gCourseRoster(Ctr).GPA
Next
Average = Sum / gNumberOfStudents
Return Average
End Function
End Class
You can use a Lambda expression to tease it out. The Cast part is converting from the gCourseRoster to a collection of Double by supplying the GPA to the Select statement.
Dim gList As New List(Of gCourseRoster)
gList.Add(New gCourseRoster With {.id = 1, .name = "Bob", .GPA = 3.9})
gList.Add(New gCourseRoster With {.id = 2, .name = "Sarah", .GPA = 3.2})
gList.Add(New gCourseRoster With {.id = 3, .name = "Frank", .GPA = 3.1})
Dim maxGPA = gList.Cast(Of gCourseRoster).Select(Function(c) c.GPA).ToList.Max
MessageBox.Show(maxGPA.ToString)
Output: 3.9

Using a variable and its value across multiple subs

Here is my code.
Module Module1
Dim a, x, y As Integer
Public Delegate Sub Areas()
Sub Main()
Dim Square As Areas
Dim Rectangle As Areas
Dim Add As Areas
Dim Area As [Delegate]
Square = New Areas(AddressOf areasquare)
Rectangle = New Areas(AddressOf arearect)
Add = New Areas(AddressOf addition)
Area = [Delegate].Combine(Square, Rectangle, Add)
Area.DynamicInvoke()
Console.WriteLine("the combined areas are equal to " & x * y + a * a)
Console.ReadKey()
End Sub
Class SqareArea
Public Function mult(ByVal a As Integer)
Return a * a
End Function
End Class
Class RectangleArea
Public Function mult(ByVal x As Integer, ByVal y As Integer)
Return x * y
End Function
End Class
Public Sub areasquare()
Dim a As Integer
Dim objSqareArea As New SqareArea()
Console.WriteLine("What is the measurement of one side of the square?")
a = Int32.Parse(Console.ReadLine)
Console.WriteLine("The area of the square is " & objSqareArea.mult(a))
End Sub
Sub arearect()
Dim x, y As Integer
Dim objRectangleArea As New RectangleArea()
Console.WriteLine("What is the length of the rectangle?")
x = Int32.Parse(Console.ReadLine)
Console.WriteLine("What is the width of the rectangle?")
y = Int32.Parse(Console.ReadLine)
Console.WriteLine("The area of the rectangle is " & objRectangleArea.mult(x, y))
End Sub
Public Sub addition()
Console.WriteLine("the combined areas are equal to " & x * y + a * a)
End Sub
End Module
I am multiplying two sets of numbers using variables from the user.
Then I want to take the products of both operations and add them together.
So I want to use the variables from other subs. How would I do that?
Take out
Dim a As Integer
in Public Sub areaSquare()
AND
Dim x, y As Integer
in Sub areaRect().
Module Module1
Dim a, x, y As Integer
Public Delegate Sub Areas()
Sub Main()
Dim Square As Areas
Dim Rectangle As Areas
Dim Add As Areas
Dim Area As [Delegate]
Square = New Areas(AddressOf areasquare)
Rectangle = New Areas(AddressOf arearect)
Add = New Areas(AddressOf addition)
Area = [Delegate].Combine(Square, Rectangle, Add)
Area.DynamicInvoke()
Console.WriteLine("the combined areas are equal to " & x * y + a * a)
Console.ReadKey()
End Sub
Class SqareArea
Public Function mult(ByVal a As Integer)
Return a * a
End Function
End Class
Class RectangleArea
Public Function mult(ByVal x As Integer, ByVal y As Integer)
Return x * y
End Function
End Class
Public Sub areasquare()
Dim objSqareArea As New SqareArea()
Console.WriteLine("What is the measurement of one side of the square?")
a = Int32.Parse(Console.ReadLine)
Console.WriteLine("The area of the square is " & objSqareArea.mult(a))
End Sub
Sub arearect()
Dim objRectangleArea As New RectangleArea()
Console.WriteLine("What is the length of the rectangle?")
x = Int32.Parse(Console.ReadLine)
Console.WriteLine("What is the width of the rectangle?")
y = Int32.Parse(Console.ReadLine)
Console.WriteLine("The area of the rectangle is " & objRectangleArea.mult(x, y))
End Sub
Public Sub addition()
Console.WriteLine("the combined areas are equal to " & x * y + a * a)
End Sub
End Module
You're declaring class level variables, but then diminishing their value during run-time.
My inputs:
Side of square: 5
Length of rectangle: 10
Width of rectangle: 4
Results:
Area of the square is 25
Area of the rectangle is 40
The combined areas are equal to 65
The combined areas are equal to 65

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]

VB program to calculate grades

So I am working on a program that will ask for the number of assignments, say 20, then run through a loop that many times asking for the total points earned on each assignment as well as the total points possible to get the final grade. For example if the user put in 2 assignments with assignment 1 earning 48 points out of 50 and assignment 2 earning 35 points out of 40 the program would display the grade as 92.
So far here is what I have:
Public Class Form1
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim amountAssignments As Integer
Dim pointsEarned As Integer = 0
Dim pointsEarnedTotal As Integer = 0
Dim pointsPossible As Integer = 0
Dim pointsPossibleTotal As Integer = 0
Dim Assignment As Integer = 1
Integer.TryParse(txtAmount.Text, amountAssignments)
Do Until Assignment > amountAssignments
txtAmount.Text = String.Empty
lblAmount.Text = "Enter Points Given on Assignment " & Assignment & ":"
Integer.TryParse(txtAmount.Text, pointsEarned)
pointsEarnedTotal = pointsEarnedTotal + pointsEarned
lblAmount.Text = "Enter Points Possible on Assignment " & Assignment & ":"
Integer.TryParse(txtAmount.Text, pointsPossible)
pointsPossibleTotal = pointsPossibleTotal + pointsPossible
Assignment = Assignment + 1
Loop
lblAmount.Text = "Enter the amount of Assignments: "
lblGrade.Text = (pointsEarnedTotal / pointsPossibleTotal)
End Sub
End Class
syntax is correct but when the program is run and the number of assignments put in and calculate entered the program displays the grade as NaN with no other input requested.
Could use another set of eye(s) to look over this and tell me where i screwed up logically.
Thank you in advance!
This program seems to not have some sort of user intervention when the loop starts. What I would do is surely have the user enter the amount of assignments on the textbox and then from there would ask the user to enter marks from an input box separated by a slash e.g I enter 45/50 so after input the program finds the index of "/",all characters before the '/' are the pointsEarned and can be added to the pointsEarnedTotal while all the characters after the '/' are placed in the pointsPossible and added to the pointsPossibleTotal
Try this and tell me how it goes...give me points if it works
` Private Sub butGetMarks_Click(sender As System.Object, e As System.EventArgs) Handles butGetMarks.Click
Dim assignments As Integer = 0
Dim totalAssignments As Integer
Integer.TryParse(txtAssignments.Text, totalAssignments)
Dim pointsEarned As Double = 0
Dim pointsEarnedTotal As Double = 0
Dim possibleEarned As Double = 0
Dim possibleEarnedTotal As Double = 0
Dim temp As String
For i As Integer = 1 To totalAssignments
temp = InputBox("Enter marks per assignment separated by /")
Dim i1 As Integer
i1 = temp.IndexOf("/") 'read index of /
pointsEarned = temp.Substring(0, i1) 'read from start until / character
possibleEarned = temp.Substring(i1 + 1) 'read from after / character onwards
'add to totals
possibleEarnedTotal += possibleEarned
pointsEarnedTotal += pointsEarned
Next i
MessageBox.Show(pointsEarnedTotal & "/" & possibleEarnedTotal)
End Sub`