I understand how to convert decimal to hexadecimal (little endian).
Dec : 579270022
Hex : 86F58622 (little endian)
My sample code:
Public Shared Function decimalToHexLittleEndian(ByVal _iValue As Long, ByVal _iBytes As Integer) As String
Dim sBigEndian As String = String.Format("{0:x" & (2 * _iBytes).ToString() & "}", _iValue)
Dim sLittleEndian = ""
For i = _iBytes - 1 To 0 Step -1
sLittleEndian += sBigEndian.Substring(i * 2, 2)
Next
Return sLittleEndian
End Function
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
TextBox2.Text = decimalToHexLittleEndian("579270022", 4)
End Sub
Now, my question is how convert hexadecimal (little endian) to decimal?
Reverse the pairs of characters and then use Convert.ToInt64(r, 16):
Dim h = "86F58622"
' Ensure an even length
If h.Length Mod 2 = 1 Then h = "0" & h
Dim r = ""
For i = 0 To h.Length - 1 Step 2
r = h.Substring(i, 2) & r
Next
Dim a = Convert.ToInt64(r, 16)
Console.WriteLine(a) ' outputs 579270022
Related
Struggling student here... I've been asked to find the min, max and mid-point value. However, I cannot figure this out; arrays/data storage is 3 chapters away. So, I'm hoping someone could help me out with this conundrum.
-I need to get the data from an individual element within an array in decimal. Any ideas? I've largely been unsuccessful with the 'array.getvalue' method & with the 'array.min' methods.
Dim numberOfInvoices As Integer
Dim totalOfInvoices As Decimal
Dim invoiceAverage As Decimal
Private Sub BtnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim subtotal As Decimal = CDec(txtEnterSubtotal.Text)
Dim discountPercent As Decimal = 0.25D
Dim discountAmount As Decimal = Math.Round(subtotal * discountPercent, 2)
Dim invoiceTotal As Decimal = subtotal - discountAmount
Dim minimum, maximum, middle, i As Decimal
Dim array(1) As Decimal
Dim midpoint As Integer
txtSubtotal.Text = FormatCurrency(subtotal)
txtDiscountPercent.Text = FormatPercent(discountPercent, 1)
txtDiscountAmount.Text = FormatCurrency(discountAmount)
txtTotal.Text = FormatCurrency(invoiceTotal)
numberOfInvoices += 1
totalOfInvoices += invoiceTotal
invoiceAverage = totalOfInvoices / numberOfInvoices
For i = 0 To numberOfInvoices - 1
array(i) = i
ReDim Preserve array(0 To numberOfInvoices - 1)
Next i
If numberOfInvoices = 1 Then
minimum = totalOfInvoices
middle = totalOfInvoices
maximum = totalOfInvoices
End If
If numberOfInvoices > 1 Then
midpoint = numberOfInvoices / 2
middle = array.GetValue(midpoint)
For Each i In array
If i < UBound(array) - 1 Then If array(i) > array(i + 1) Then maximum = array(i)
If i < UBound(array) - 1 Then If array(i) < array(i + 1) Then minimum = array(i)
Next i
End If
txtLargestInvoice.Text = maximum.ToString
txtSmallestInvoice.Text = minimum.ToString
txtMidPoint.Text = middle.ToString
txtNumberOfInvoices.Text = numberOfInvoices.ToString
txtTotalOfInvoices.Text = FormatCurrency(totalOfInvoices)
txtInvoiceAverage.Text = FormatCurrency(invoiceAverage)
txtEnterSubtotal.Text = ""
txtEnterSubtotal.Select()
End Sub
Private Sub BtnClearTotals_Click(sender As Object,
e As EventArgs) Handles btnClearTotals.Click
numberOfInvoices = 0
totalOfInvoices = 0
invoiceAverage = 0
txtNumberOfInvoices.Text = ""
txtTotalOfInvoices.Text = ""
txtInvoiceAverage.Text = ""
txtEnterSubtotal.Select()
End Sub
Private Sub BtnExit_Click(sender As Object,
e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Comments and explanations in-line
Private Sub OPCode2()
'You can declare and initialize an array in one line
Dim arr() As Double = {13.5, 18.0, 6.2, 11.8, 13.6}
'Just check intellisense for a list of methods and properties of arrays
Dim myAverage As Double = arr.Average()
Dim myMin As Double = arr.Min
Dim myMax As Double = arr.Max
Dim myMedian As Double
'The original array is lost when .Sort is applied
Array.Sort(arr)
Dim myLength As Integer = arr.Length
'If the lenght of the array is even you could also average
'the middle two values And return that number which
'may not be a value in the original array
myMedian = arr(CInt(myLength / 2)) 'returns the higher of the middle two if length is even
'or the actual middle value in the sorted array
MessageBox.Show($" The Average value is {myAverage}
The Maximum value is {myMax}
The Minimum value is {myMin}
The Median value is {myMedian}")
End Sub
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.
using winforms / vb.net
I am trying to count how many characters exist in "textbox3" after a specific character "." in a textbox.
examples:
2adf = 0 (no "." exists)
2adf. = 0
2adf.2 = 1
2adf.2a = 2
2adf.2af = 3
2adf.2afe = 4
I already have a function to search if there is a "."
if (CountCharacter(TextBox3.Text, ".") = 1) then
'a "." exists so count number of characters after "."
end if
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then cnt += 1
Next
Return cnt
End Function
I am not sure how to check the count after the "." though
You could use the string.IndexOf method for this task
Sub Main
Dim test = "2adf.2afe"
Dim result = CountCharsAfter(test, "."c)
Console.WriteLine(result)
End Sub
Public Function CountCharsAfter(input as string, charToSearch as Char) as Integer
DIm pos = input.LastIndexOf(charToSearch)
if pos = -1 then
return 0
else
return input.Length - (pos + 1)
End if
End Function
Try this
Dim NoChar As Integer = CalculateChra("12adf.2afe", ".")
Private Function CalculateChra(ByVal V_String As String, ByVal LastChar As Char) As Integer
Dim Start As String = Split(V_String, LastChar)(0) & "."
Dim M As String = V_String.Substring(Start.Length)
Return M.Length
End Function
dim n,cnt as integer
n=0
cnt=0
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = Chr(46) Then
n = Len(TextBox1.Text)
End If
If n <> 0 Then
cnt += 1
End If
MsgBox(" no.of charectors after '.' is/are : " & cnt - 1)
End Sub
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]
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`