Splitting a String into Pairs - vb.net

How would I go on splitting a string into pairs of letter in VB?
for example: abcdefgh
split into: ab cd ef gh

I'll throw my hat in the ring:
Dim test As String = "abcdefgh"
Dim results As New List(Of String)
For i As Integer = 0 To test.Length - 1 Step 2
If i + 1 < test.Length Then
results.Add(test.Substring(i, 2))
Else
results.Add(test.Substring(i))
End If
Next
MessageBox.Show(String.Join(" ", results.ToArray))

The following allows for odd length strings. If the string is zero-length, I'm not sure what you'd want to do, you'll want to address that case.
Dim src As String = "abcdef"
Dim size As Integer
If src.Length > 0 Then
If src.Length Mod 2 = 0 Then
size = (src.Length / 2) - 1
Else
size = ((src.Length + 1) / 2) - 1
End If
Dim result(size) As String
For i = 0 To src.Length - 1 Step 2
If i = src.Length - 1 Then
result(i / 2) = src.Substring(i, 1)
Else
result(i / 2) = src.Substring(i, 2)
End If
Next
End If

In C# you would do like this:
Dictionary<String, String> Split(String input)
{
if (input.Count % 2 == 0)
{
Dictionary<string, string> Pairs = new Dictionary( );
for (int L = 0, R = 1; L < input.Count && R <= input.Count; ++L, ++R)
{
Char
Left = input[L],
Right = input[R];
Pairs.Add(
Left.ToString(),
Right.ToString());
}
}
else
{
throw new NotEvenException( );
}
return Pairs( );
}
void Main()
{
var Pairs = Split("ABCDEFGH");
foreach(string Key in Split("ABCDEFGH"))
{
Console.Write("{0}{1}\n", Key, Pairs[Key]);
}
}
/*
Output:
AB
CD
EF
GH
*/
Now, I know what you think: This isn't what I want! But I say: It is actually, at least partly.
Since I presume you're working in VB.net, the basic structure of what you want performed is outlined in the short snippet above.
For example: The method Count (of the object String) exists in both C# and in VB.
Hope it helps a bit at least!

Related

multidimensional array linq query

i have 5 dimensional array, when using linq to query, the results are sorted in dimensional way:
array(a)(b)(c)(d)(e) , dimension = 1
using for next:
For e = 0 To dimension - 1
For d = 0 To dimension - 1
For c = 0 To dimension - 1
For b = 0 To dimension - 1
For a = 0 To dimension - 1
listbox.Items.Add(array(a, b, c, d, e).disc)
Next
Next
Next
Next
Next
this would result in:
abcde
00000
10000
01000
...
if i use linq:
listbox.Items.AddRange((From item In array Select item.disc).ToArray)
this would result in:
abcde
00000
00001
00010
...
how can i achieve the first result with linq?
Public Class ArrayExt
Public Shared Function GetFirstFastestEnumerator(Of T)(source As Array) As IEnumerable(Of T)
Dim srcRank = source.Rank
Dim indices = New Integer((srcRank) - 1) {}
Dim len = source.Length
For i = 0 To srcRank - 1
indices(i) = source.GetLowerBound(i)
Next
Dim curRank As Integer = 0
For i = 0 To len - 1
Return CType(source.GetValue(indices), T)
While (curRank < srcRank)
If (indices(curRank) < source.GetUpperBound(curRank)) Then
indices(curRank) = indices(curRank) + 1
curRank = 0
Exit While
Else
indices(curRank) = source.GetLowerBound(curRank)
curRank = curRank + 1
End If
End While
Next
End Function
End Class
You need a custom Iterator to go through the array in the rank order you want, which is opposite the built-in order.
public static class ArrayExt {
public static IEnumerable<T> GetFirstFastestEnumerator<T>(this Array src) {
var srcRank = src.Rank;
var indices = new int[srcRank];
var len = src.Length;
for (var j1 = 0; j1 < srcRank; ++j1)
indices[j1] = src.GetLowerBound(j1);
int curRank = 0;
for (var j1 = 0; j1 < len; ++j1) {
yield return (T)src.GetValue(indices);
while (curRank < srcRank) {
if (indices[curRank] < src.GetUpperBound(curRank)) {
++indices[curRank];
curRank = 0;
break;
}
else {
indices[curRank] = src.GetLowerBound(curRank);
++curRank;
}
}
}
}
}
Which you can use either with LINQ or foreach. Replace arrayType with the class stored in array.
listbox.Items.AddRange((From item In array.GetFirstFastestEnumerator<arrayType>() Select item.disc).ToArray)
Or Visual Basic version:
Public Module Ext
<Extension()> _
Public Iterator Function GetFirstFastestIterator(Of T)(source As Array) As IEnumerable(Of T)
Dim srcRank = source.Rank
Dim indices = New Integer((srcRank) - 1) {}
Dim len = source.Length
For i = 0 To srcRank - 1
indices(i) = source.GetLowerBound(i)
Next
Dim curRank As Integer = 0
For i = 0 To len - 1
Yield CType(source.GetValue(indices), T)
While (curRank < srcRank)
If (indices(curRank) < source.GetUpperBound(curRank)) Then
indices(curRank) = indices(curRank) + 1
curRank = 0
Exit While
Else
indices(curRank) = source.GetLowerBound(curRank)
curRank = curRank + 1
End If
End While
Next
End Function
End Module

How to do this in Visual basic?

How to do the "a++" and "b++" in Visual basic?
What is the another codes for there in Vb?
The names there are just example.
int a = 0;
int b = 0;
{
if (ans1.Text == "James")
{
a++;
}
else
{
b++;
}
if (ans2.Text == "Ryan")
{
a++;
}
else
{
b++;
}
if (ans3.Text == "Mac")
{
a++;
}
else
{
b++;
}
t1.Text = a.ToString();
t2.Text = b.ToString();
}
Like this:
a += 1
b += 1
(...)
Like this
DIM a as integer = 0
DIM b as integer = 0
If ans1.Text = "James" Then
a += 1
Else
b += 1
End If
If ans2.Text = "Ryan" Then
a += 1
Else
b += 1
End If
If ans3.Text = "Mac" Then
a += 1
Else
b += 1
End If
t1.Text = a.ToString()
t2.Text = b.ToString()
Your question has already been answered but I think it would be useful to see how you could simplify your code:
Dim correctAnswers As Integer = 0
Dim totalQuestions As Integer = 3'you need to modify this is you add more questions
'increment the number of correct answers for each one we find
correctAnswers += If(ans1.text = "James", 1, 0)
correctAnswers += If(ans2.text = "Ryan", 1, 0)
correctAnswers += If(ans3.text = "Mac", 1, 0)
'show the number of correct and incorrect answers
t1.Text = correctAnswers.ToString()
t2.Text = (totalQuestions - correctAnswers).ToString() 'show the number of incorrect questions
Neither the postfix nor prefix ++ are defined in Visual Basic.
Your only realistic option is to use a = a + 1 (or, in later BASICs, a += 1) instead (note the lack of a ; for a statement terminator). But note that this will not evaluate to the previous value of a and the entire construct is not an expression in the C / C++ sense. You could build a function to mimic a++ but that would be too obfuscating.

Visual Basic .NET Help

How can I get this code into a loop?
contact.first_name = list.Item(0)
contact.middle_name = list.Item(1)
contact.last_name = list.Item(2)
contact.age = list.Item(3)
contact.mobile_phone = list.Item(4)
contact.home_phone = list.Item(5)
contact.work_phone = list.Item(6)
contact.home_street = list.Item(7)
contact.home_city = list.Item(8)
contact.home_state = list.Item(9)
contact.home_zip = list.Item(10)
contact.work_street = list.Item(11)
contact.work_city = list.Item(12)
contact.work_state = list.Item(13)
contact.work_zip = list.Item(14)
You can't. Even if you used something like reflection to enumerate the fields in contact and assign them that way, since there's no inherent ordering of those members, you'd still not be able to do the loop.
First, you would need some way to associate index with the name of a property. Probably the best way to do this is to create a list of pairs that store the property name and an index:
Class Info
Public Property Name As String
Public Property Index As Integer
End Class
Then, you'd need to create a list with elements that represent the associations:
Dim associations = {
New Info With { .Name = "first_name", .Index = 0 }, _
New Info With { .Name = "second_name", .Index = 1}, ... }
Now, you could use a simple For loop and Reflection to set the properties:
Dim contType = contact.GetType()
Dim empty As Object(0)
For Each assoc In associations
contType.GetProperty(assoc.Name) _
.SetValue(contact, list.Item(assoc.Index), empty)
Next
I'm not a VB expert and I didn't try the code, but something along these lines should work. Anyway, it really depends on the scenario - in some cases, there is no better way than what you're using currently.
I assume you want to loop list.Item. You can do it but you'll end up with more code than you have already.
For example
For i As Integer = 0 To list.Item.Count - 1
Select Case i
Case 1
contact.middle_name = list.Item(i)
Case 2
contact.last_name = list.Item(i)
Case 3
contact.age = list.Item(i)
...
End Select
Next
As you can see it probably is not worth doing.
If you need it to go to infinity, you probably want a function that takes a contact, a list, and a starting index.
Public Sub FillContact(ByVal contact As Contact, values As IList(Of Object),
startingIndex As Integer)
'error checking here, such as ensuring you have a contact and value
'list and that startingIndex + number of properties < values.Count
contact.first_name = values(startingIndex)
contact.middle_name = values(startingIndex + 1)
'...
contact.work_state = value(startingIndex + 13)
contact.work_zip = value(startingIndex + 14)
End Sub
Then you can call this function in a loop, something like
Dim contacts As New List(Of Contact)
'load the values
Dim values() As Object = GetValues()
For i = 0 To values.Length Step NumberOfProperties
Dim nextContact As New Contact()
FillContact(nextContact, values, i)
contacts.Add(nextContact)
Next
I managed to get it working in a loop statement.
For x As Integer = 1 To list.Count / 15
Dim contact As New Contact
my_contacts.Add(contact)
Next
Dim i As Integer = 0
For Each contact In my_contacts
With contact
.first_name = list.Item(i)
i += 1
.middle_name = list.Item(i)
i += 1
.last_name = list.Item(i)
i += 1
.age = list.Item(i)
i += 1
.mobile_phone = list.Item(i)
i += 1
.home_phone = list.Item(i)
i += 1
.work_phone = list.Item(i)
i += 1
.home_street = list.Item(i)
i += 1
.home_city = list.Item(i)
i += 1
.home_state = list.Item(i)
i += 1
.home_zip = list.Item(i)
i += 1
.work_street = list.Item(i)
i += 1
.work_city = list.Item(i)
i += 1
.work_state = list.Item(i)
i += 1
.work_zip = list.Item(i)
i += 1
End With
Next
Easy, use a ForEach loop to iterate through the members in contact. I am assuming "contact" is a class with all the members listed as being public.
Next use a counter variable (i) to go from 0 to (list.Items.Count - 1). Initialize this counter variable OUTSIDE the ForEach loop.
Then assign the first listitem (When i = 0) to the first member in contact. After assigning, increment i (i+=1) and then close the loop.
Now i will automatically increment each time the loop runs and will assign the required data to the contact member.

permutations gone wrong

I have written code to implement an algorithm I found on string permutations. What I have is an arraylist of words ( up to 200) and I need to permutate the list in levels of 5. Basically group the string words in fives and permutated them. What I have takes the first 5 words generates the permutations and ignores the rest of the arraylist?
Any ideas appreciated.
Private Function permute(ByVal chunks As ArrayList, ByVal k As Long) As ArrayList
ReDim ItemUsed(k)
pno = 0
Permutate(k, 1)
Return chunks
End Function
Private Shared Sub Permutate(ByVal K As Long, ByVal pLevel As Long)
Dim i As Long, Perm As String
Perm = pString ' Save the current Perm
' for each value currently available
For i = 1 To K
If Not ItemUsed(i) Then
If pLevel = 1 Then
pString = chunks.Item(i)
'pString = inChars(i)
Else
pString = pString & chunks.Item(i)
'pString += inChars(i)
End If
If pLevel = K Then 'got next Perm
pno = pno + 1
SyncLock outfile
outfile.WriteLine(pno & " = " & pString & vbCrLf)
End SyncLock
outfile.Flush()
Exit Sub
End If
' Mark this item unavailable
ItemUsed(i) = True
' gen all Perms at next level
Permutate(K, pLevel + 1)
' Mark this item free again
ItemUsed(i) = False
' Restore the current Perm
pString = Perm
End If
Next
K above is = to 5 for the number of words in one permutation but when I change the for loop to the arraylist size I get an error of index out of bounds
Index out of bounds error usually happens when you start the loop from 1 to length. The the for loop as following.
For i = 0 to array.length - 1
You will get this error.
When you do
For i = 1 To K
The last value of i will be the size of your array.
chunks.Item(i)
Will crash when i equals the size of the array since the index starts at 0.
I would suggest you change your for loop to
For i = 0 To K - 1
Or you change the way you access the values in your arrays to
chunks.Item(i-1)
C++ Permutation
#include <stdio.h>
void print(const int *v, const int size)
{
if (v != 0)
{
for (int i = 0; i < size; i++)
{
printf("%4d", v[i] );
}
printf("\n");
}
} // print
void permute(int *v, const int start, const int n)
{
if (start == n-1) {
print(v, n);
}
else {
for (int i = start; i < n; i++) {
int tmp = v[i];
v[i] = v[start];
v[start] = tmp;
permute(v, start+1, n);
v[start] = v[i];
v[i] = tmp;
}
}
}
main()
{
int v[] = {1, 2, 3, 4};
permute(v, 0, sizeof(v)/sizeof(int));
}

Developing Fibonacci Series in VB

I am trying to write a code for Fibonacci series in VB, but some of the values in my series are incorrect. Can somebody help me with the code?
Below is what I have so far.
Private Function FibNumber(number As Integer) As Integer
If (number > 2) Then
FibNumber = (FibNumber(number - 2) + FibNumber(number - 1))
Else
FibNumber = 1
End If
End Function
Private Sub command1_click()
Dim x As Integer
x = Text1.Text
Call FibNumber(number)
End Sub
Well, I did a quick search and I came up with the following in the first couple of results:
Private Function FibNumber(number As Integer) As Integer
If (number > 2) Then
FibNumber = (FibNumber(number - 2) + FibNumber(number - 1))
Else
FibNumber = 1
End If
End Function
I know this is way old, but I think the issue could be with how compgeek is calling the function.
Instead of:
Call FibNumber(number)
It should be:
Call FibNumber(x)
My solution:
Private Function FibNumber(number As Integer) As Integer
If (number > 2) Then
FibNumber = (FibNumber(number - 2) + FibNumber(number - 1))
Else
FibNumber = 1
End If
End Function
Private Sub command1_click()
Dim x As Integer
x = Text1.Text
Call FibNumber(number)
End Sub
It's a Java function, and believe me; Fibonacci wont get much more faster or complex than
this particular version. It is optimized to operate at about 100 times faster than the original recursive one.
Tip: You might need to change maxN to extend parameter length!
For example if you want to input numbers between 0 and 199, you must increase the maxN to 200
static final int maxN = 72;
static long knownF[] = new long[maxN];
static long F(int i) {
if (knownF[i] != 0) {
return knownF[i];
}
long t = i;
if (i < 0) {
return 0;
}
if (i > 1) {
t = F(i - 1) + F(i - 2);
}
return knownF[i] = t;
}
Module Module1
Sub Main()
Console.WriteLine("The Fibonacci Series")
Console.WriteLine("Enter how many elements-")
Dim n As Integer = Console.ReadLine
If (n = 1) Then
Dim a As Integer = 1
Console.WriteLine("{0}", a)
Else
Dim a As Integer = 1
Dim b As Integer = 2
Console.WriteLine("{0}", a)
Console.WriteLine("{0}", b)
Dim i As Integer = 1
While (i < n - 1)
Dim c As Integer = a + b
Console.WriteLine(" {0}", c)
a = b
b = c
i = i + 1
End While
End If
Console.ReadKey()
End Sub
End Module