Search for number in an array - arrays

I'm having some trouble with the exercise I got given from my teacher.
Exercise:
Write a program to input 5 numbers. Ask the user to a input a number for searching the array. The program should search for this number and tell the user if it has been found in the array or not. For example, if it has been found then the position of the array which the number occupies should be display. For example "Your number is 6. It has been fond in the position 3 of the list."
Obviously, I can just use a for loop and get 5 numbers and put them into the array. But Im not sure how to check if then the number the user wants to search for is in the array.
Heres my attempt http://pastebin.com/t2DcdSvU Im not sure how to put it into code tags :S

First, obtain you user input. So let's say you have your array, and a target value. For the example, let's just say your user input created the following:
Dim numbers = {1, 2, 9, 6, 4}
Dim target = 2
Now all you need to do is loop through the array, and compare the target, to the current value of the array.
For x = 0 To 4
If target = numbers(x) Then
MsgBox "Your number is " + target ", found at position " + x
Exit For
End If
Next x

You can use that same concept to search the array.
Assuming you won't have a sorted array, you can simply use a for loop to check each value of the array and compare with the entered value to search.
Use a for loop or whatever construct you want to populate the array, then use another to loop through the array and for each value, do a compare and determine if the user entered a number that's in the array.
If you get a match, print out the resulting index number and return.
Here's a sample of code that will do what you need:
Dim value As Integer
value = 0
' This loop goes from 0 to 4.
For index As Integer = 0 To 4
value = myArray(index)
' Exit condition if the value is the user number.
If (value = usernum) Then
Console.writeline("Your number was " & usernum & " found at: " & index & "\n")
Exit For
End If
Next

Related

Trouble looping through a data file and storing integers in an array

I am having a problem with a loop. I am writing a program that loops through lottery drawings and does some different analysis' on the drawings. The problem I am having is since a loop is 0-based but there is no number 0 in lottery drawings I cant figure out how to start the loop at 1 instead of 0. Also, when I cut out an integer, if the integer is a single digit the loop doesn't see the zero before the single digit and counts all of the 0-9 in all of the integers. I am trying to grab an integer and then tick that element of the array. Here is the loop.
'Choices(59) is passed into the loop from a click event
Private Sub GetFrequency(Choices() As Integer)
Dim Size As Integer = UsersChosenHistory.Length() 'Size
Dim Number As Integer = 1
Dim Start As Integer = 0
Dim Finish As Integer = 3'Grab 3 chars, a space + 2 digit Integer
For i As Integer = 1 To Size - 1 Step 1
Number.ToString("d2")'I've also tried Number.ToString("D2") (Capitol D)
Number = UsersChosenHistory.Substring(Start, Finish) 'Grab an integer
Choices(Number) += "1" 'Store it in the corresponding array element
Start += 1
Next
End Sub
When running through the loop with the F11 key the single digits do not show the leading "0" even though the data file does include the "0", and as I mentioned above the array shows a "0" as the first digit in the frequence grid. I'm really confused with this loop, any help will be greatly appreciated. I'm just learning VB.Net and this has me stumped. Thanks in advance.
For i As Integer = 0 To Size - 1 Step 1
Number = int.Parse(UsersChosenHistory.Substring(i*3,3).Replace(" ",""))
Choices(Number) += "1"
Next
For the "0" issue, ignore it. Choices(0) will never be incremented.

Trying to get numbers from InputBox, split them then add each number into the array

I have InputBox asking user to input 5 numbers then trying to add each number to the array size 5. But I am getting error. The loop is adding numbers to the array Can anyone help?
You are aware that split makes the array.
Message is your array not arraynums.
Your for loop is 0 to 5 which is 6.
Read documentation, e.g. Split Function
Dim i
Dim arrayNums
Dim message
Dim userInput
message = InputBox("Please Enter 5 numbers!")
arrayNums = Split( message)
For i=0 To ubound(arrayNums)
msgbox(arrayNums(i))
Next
You're on the right track. You can just Split the results and that will create an array. Then, you can test the UBound() of the array to see if you have your 5 numbers.
Here's a loop that continues until 5 numbers are entered:
Do
a = Split(InputBox("Please enter 5 numbers, separated by spaces:"))
Loop Until UBound(a) = 4
' Now, a(0) through a(4) are your 5 numbers.
Of course, you'll probably also want to validate the 5 entries to ensure they're actually numbers. The IsNumeric() function can help.

Unique values in Excel

I need to get a value which has the maximum number of occurrences in the unique data set from a big column based on a condition. I just need one value and not the array.
See below the example data that I am working with. I have done it in MATLAB but want to know it in Excel.
So in the above data for example, I want to get the unique values for lanes based on the value of #safea. So if #safea=102 then unique values of lanes=(2,3,1). But I want the value from these set of data which has maximum number of occurrences. In this case it is 2 because 2 has come up 5 times whereas 3 has come up once and 1 has come up as only 1 time.
Another example:
If I select #safea as 162, then the number of unique values in lanes (5 and 4) but 5 has come up 4 times and 4 has come up as only 1 time so the final answer that I want is '5'.
If you don't mind using VBA, I've devised a Function you can use for what you want. Given the #safea values are in column A and the lane values are in column B, you can use this:
Function MODEIF(criteria As Integer) As Integer
Dim count As Integer
count = Application.WorksheetFunction.CountA(Range("A:A"))
Dim list() As Integer
Dim size As Integer
size = 0
Do While count > 0
If (Range("A" & count) = criteria) Then
ReDim Preserve list(size)
list(size) = Range("B" & count)
size = size + 1
End If
count = count - 1
Loop
MODEIF = Application.WorksheetFunction.Mode(list)
End Function
Just put this Function in a Module, go to the spreadsheet, and type =MODEIF(102) or whatever #safea value you want the mode for and it will give you the answer.
You could also use this worksheet function to get a conditional MODE:
=MODE(IF(**your #safea value here**=$A$2:$A$22,$B$2:$B$22))
This is an array formula. Confirm entry by pressing Ctrl+Shift+Enter (not just Enter).

Compare largest number among a list of XML input parse using Excel VBA

Set node = xmldoc.SelectNodes("//Attribute[#name='XSHIP_LOCATION']")
For Each n In node
result = n.Text
logmsg = "XSHIP_LOCATION: " & result
Call PrintLog(logmsg, logline)
Next n
For every line in xml that contains name=XSHIP_LOCATION, the value of that attribute will be read. How can i compare the list of results read from XML and pick the highest number?
Example of result = 1, 2,1,3,5,4,1,2
I would like to find the largest number from the list of inputs read from XML which is 5 in this case using .
Can anyone kind enough to help this newbie? Thanks
why not add a second variable to capture the maximum value, then each iteration through the loop, compare the maximum to the result.... as such
result = n.Text '->your code
if result > max then max = result
logmsg = "XSHIP_LOCATION: " & result '--> your code
Note that if n is NOT a number, this will throw an error.

Largest word in an Array

Hey i'm having problems creating a simple button for a programme which finds the largest word in an array and puts it into a textbox. I've done most of the coding (I hope) was wondering if somebody could help me actually with the code that finds the largest text in the array as I am struggling the most with that.
Private Sub btnLongName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLongName.Click
Dim LongName As String
Dim LengthOfLongestName As Integer
Dim UltimateName As String
For i As Integer = 0 To 5
LongName = Members(i).Name
LengthOfLongestName = Len(LongName)
If Members(i).Name.Length > LengthOfLongestName Then
End If
Next i
txtResult.Text = "The longest name is " & UltimateName & " ."
End Sub
End Class
Thanks for your time - its for college homework, struggling big time on it :(
edit: I've edited the code
Since this is homework, I won't write the code for you; instead I'll try to give you some hints that will point you in the right direction.
Declare a variable of an appropriate type to hold the <longest value so far>, initialize it with the "shortest" value for that type.
Loop through all the values in the array (perhaps with a For or For Each loop)
Pseudo-code for the inside your loop:
If the Length of <the value being checked> exceeds _
the Length of the <longest value so far> Then
Assign <the value being checked> to the <longest value so far>
End If
When the loop finishes, the <longest value so far> will be the longest value in the array.
Notes
You can use MSDN as a reference on how to use a For loop or a For Each loop (If you haven't learned For loops yet, you can also use a Do Loop)
<the value being checked> will be different on each iteration through the loop; it should correspond to each consecutive value in your array. You can verify that this is working by setting a breakpoint.
You can get the length of a string by saying myString.Length
If you've learned about Functions, consider writing a function that takes an array as a parameter, and returns the longest value in the array.
There are certainly ways you could do this with LINQ, but I don't think that is the goal of the assignment ;-]
In response to Edit 1:
Your If statement needs to be inside of some sort of loop (For, For Each, Do, etc) I think this is the key concept that you are missing.
Instead of comparing LongName.Length to LengthOfLongestName, you need to compare the length of an entry in your array to LengthOfLongestName
You're on the right track with Members(0).Name.Length, but you can't just check element 0; you have to check every element in the array.
Given your current code, you'll probably be assigning <An entry in your array>.Name to LongName
The last index in a one-dimensional array is <array>.Length - 1 or <array>.GetUpperBound(0).
The following doesn't really address anything in your assignment, but I hope it will give you some ideas on how to go through all the items in your list:
' A For loop that does a message box for each of the numbers from 0 to 5 '
For i as Integer = 0 To 5
MessageBox.Show(i)
Next i
' Code that does a message box with the names of the 2nd, 3rd and last '
' entries in Members '
' (Remember that the first item is at 0, the second item is at 1, etc...) '
MessageBox.Show(Members(1).Name)
MessageBox.Show(Members(2).Name)
MessageBox.Show(Members(Members.GetUpperBound()).Name)
In response to Edit 2:
You're getting warmer...
You should only update LongName and LengthOfLongName if the current value is the longest you've seen so far (i.e. they should be assigned inside of the If statement)
You have to go to the last index of the array, not 5. See above (the response to your first edit) on how to get that last index.
You don't really need the UltimateName variable; you can just use LongName ;-]
You might want to use <stringVariable>.Length instead of Len(<stringVariable>) to be consistent.
What you are missing is a loop that checks each member, and putting the If statement inside it and make it compare the length of the name to the longest name that you have found so far. If the name is longer, put it in the variable for the longest found, and update the length variable.
You can either initialise the variables with the name of the first member and loop from the second member and on, or you can initialise the variables with an empty string and loop all the members. Personally I prefer the latter one.

Resources