I am a little stuck with a simple Question: how to generate a simple random Boolean?
If am correct, a Boolean 0 = false and 1 = true, but how to suse that?
Current code:
Dim RandGen As New Random
Dim RandBool As Boolean
RandBool = Boolean.Parse(RandGen.Next(0, 1).tostring)
Or just simply:
Random rng = new Random();
bool randomBool = rng.Next(0, 2) > 0;
Saves some processing power of parsing text, whereas a simple compare is enough.
Edit: Second parameter is exclusive, so should be .Next(0, 2).
Dim RandGen As New Random
Dim RandBool As Boolean
RandBool = RandGen.Next(0, 2).ToString
TextBox1.Text = RandBool
Maybe something like this?
string[] trueOrFalse = { "false", "true"};
bool RandBool = bool.Parse(trueOrFalse[RandGen.Next(0,2)]);
Related
I'm trying to build a static array of randomly generated strings of a specific length. I've based what I have so far from here, but each index in the array has the same string, instead of a different strings. What am I doing wrong?
Dim Target As String
Target = InputBox("Input target string")
Dim StringArray(10) As String
For i = 1 To 10
StringArray(i) = GenerateString(Len(Target))
Debug.Print(StringArray(i))
Next
Function GenerateString(size As Integer) As String
Dim LegalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim Rnd As New Random()
Dim Builder As New System.Text.StringBuilder()
Dim Ch As Char
For i As Integer = 0 To size - 1
Ch = LegalCharacters(Rnd.Next(0, LegalCharacters.Length))
Builder.Append(Ch)
Next
Return Builder.ToString()
End Function
This: Dim Rnd As New Random() is where the error happens.
When you instantiate a new Random(), it takes the current time as seed. Since you instantiate it again in every iteration AND all the iteration steps happen at the "same" time (in very fast succession), each Random() generates the same output.
You have to instantiate it once before the iterator and pass it in the function as argument or you could also make it a static property of the class.
TL;DR: You will have to re-use the same Random() instead of creating a new one for each iteration.
This should be the correct code:
Dim Target As String
Target = InputBox("Input target string")
Dim StringArray(10) As String
Dim Rnd As New Random()
For i = 1 To 10
StringArray(i) = GenerateString(Len(Target), Rnd)
Debug.Print(StringArray(i))
Next
Function GenerateString(size As Integer, Rnd as Random) As String
Dim LegalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim Builder As New System.Text.StringBuilder()
Dim Ch As Char
For i As Integer = 0 To size - 1
Ch = LegalCharacters(Rnd.Next(0, LegalCharacters.Length))
Builder.Append(Ch)
Next
Return Builder.ToString()
End Function
For a school project we need to make a BoardGame, Now I have made a list of location for the NPC.
These locations are stored in a txt file named player2.txt, as followed http://pastebin.com/ZhbSvjSt
Im using the following the code to read them from the file.
http://pastebin.com/UjLSeWrQ
Dim TurnP2 As String = IO.File.ReadAllLines(".\player2.txt")(Turn)
Dim source As String = TurnP2
Dim result() As String = Split(source, ",")
But now I'm stuck, I have no clue how to splits these 3 numbers into variable.
For example Take the first row 1,1,5
I need it to place these numbers in the following variables:
CoX = 1
CoY = 1
CoZ = 5
Can anyone help me further?
Also sorry for using pastebin, but I got a strange error while trying to post.
Regards Jurre
I would create a Class:
Private Class Coords
Public coordX As Integer
Public coordY As Integer
Public coordz As Integer
End Class
And then I would fill a list:
Dim source As String() = System.IO.File.ReadAllLines(".\player2.txt")
Dim ListCoords = New List(Of Coords)
For Each Val As String In source
Dim s As String() = Val.Split(",")
ListCoords.Add(New Coords With {.coordX = s(0).ToString, _
.coordY = s(1).ToString, _
.coordz = s(2).ToString})
Next
You will have a list of loaded coordinates:
You have multiple lines, so are CoX,CoY,CoZ arrays?
You can use a loop to initialize them. Presuming always valid data:
Dim TurnP2 As String() = IO.File.ReadAllLines(".\player2.txt")
Dim CosX(TurnP2.Length - 1) As Int32
Dim CosY(TurnP2.Length - 1) As Int32
Dim CosZ(TurnP2.Length - 1) As Int32
For i As Int32 = 0 To TurnP2.Length - 1
Dim values = TurnP2(i).Split(","c)
CosX(i) = Int32.Parse(values(0))
CosY(i) = Int32.Parse(values(1))
CosZ(i) = Int32.Parse(values(2))
Next
I need some help at inserting my data (username and password) into a mssql database.
with linq to sql this is my solution but at the -> marked line I always get an EntityCommandExecutionException. I have a html website with two textboxes where I get the String out of and send the request via javascript - ajax to vb.net.
I'm doing research now for a long time and i can't find any solution.
As you can see I want to check if there is a datarow with this username but it doesn't work in the situation when there is no datarow in the table. That means the query should be 'NULL' or am I wrong?
Public Shared Function addData(ByVal username As String, ByVal passwort As String)
Dim db = New LoginContext
Dim benutzer = New Benutzer
Dim available As Boolean = False
Dim sha As New SHA1CryptoServiceProvider
Dim vName = (_
From b In db.BenutzerSet
Where b.Name = username.ToLower()
Select b)
-> If vName.Count() = 0 Or vName Is Nothing Then
benutzer.Name = username.ToLower()
Dim bytesToHash() As Byte
bytesToHash = System.Text.Encoding.ASCII.GetBytes(passwort)
bytesToHash = sha.ComputeHash(bytesToHash)
Dim encPassword As String = ""
For Each b As Byte In bytesToHash
encPassword += b.ToString("x2")
Next
benutzer.Passwort = encPassword
db.BenutzerSet.Add(benutzer)
db.SaveChanges()
available = True
Else
available = False
End If
Return available
End Function
Thanks for your help.
Use vName.Any() to check if there are any records in your Query!
-> If vName.Any() = false Then
also change Dim benutzer = New Benutzer to Dim benutzer As New Benutzer
I don't have an answer to your question, but here's some feedback:
The check vName.Count() = 0 Or vName Is Nothing is in the wrong order since VB executes them from left to right. If vName is actually Nothing, you'll get a NullReferenceException, since vName.Count() is executed first.
LINQ operators (such as Where and Select) will actually never return Nothing, so you don't have to check vName Is Nothing; it is redundant.
Using vName.Any() has the same result as vName.Count() == 0, but is more readable, and results most of the time in a more efficient SQL query.
Very good that you are hashing your passwords. But to be safe, you should add a salt and don't use SHA as a hashing algoritm for storing passwords.
I have tried a couple different ways and cannot seem to get the result I want using vb.net.
I have an array of strings. {"55555 ","44444", " "}
I need an array of integers {55555,44444}
This is a wpf page that is sending the array as a parameter to a crystal report.
Any help is appreciated.
You can use the List(Of T).ConvertAll method:
Dim stringList = {"123", "456", "789"}.ToList
Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str))
or with the delegate
Dim intList = stringList.ConvertAll(AddressOf Int32.Parse)
If you only want to use Arrays, you can use the Array.ConvertAll method:
Dim stringArray = {"123", "456", "789"}
Dim intArray = Array.ConvertAll(stringArray, Function(str) Int32.Parse(str))
Oh, i've missed the empty string in your sample data. Then you need to check this:
Dim value As Int32
Dim intArray = (From str In stringArray
Let isInt = Int32.TryParse(str, value)
Where isInt
Select Int32.Parse(str)).ToArray
By the way, here's the same in method syntax, ugly as always in VB.NET:
Dim intArray = Array.ConvertAll(stringArray,
Function(str) New With {
.IsInt = Int32.TryParse(str, value),
.Value = value
}).Where(Function(result) result.IsInt).
Select(Function(result) result.Value).ToArray
You can use the Array.ConvertAll method:
Dim arrStrings() As String = {"55555", "44444"}
Dim arrIntegers() As Integer = Array.ConvertAll(arrStrings, New Converter(Of String, Integer)(AddressOf ConvertToInteger))
Public Function ConvertToInteger(ByVal input As String) As Integer
Dim output As Integer = 0
Integer.TryParse(input, output)
Return output
End Function
Maybe something like this:
dim ls as new List(of string)()
ls.Add("55555")
ls.Add("44444")
ls.Add(" ")
Dim temp as integer
Dim ls2 as List(Of integer)=ls.Where(function(x) integer.TryParse(x,temp)).Select(function(x) temp).ToList()
Maybe a few more lines of code than the other answers but...
'Example assumes the numbers you are working with are all Integers.
Dim arrNumeric() As Integer
For Each strItemInArray In YourArrayName
If IsNumeric(strItemInArray) Then
If arrNumeric Is Nothing Then
ReDim arrNumeric(0)
arrNumeric(0) = CInt(strItemInArray)
Else
ReDim Preserve arrNumeric(arrNumeric.Length)
arrNumeric(arrNumeric.Length - 1) = CInt(strItemInArray)
End If
End If
Next
My $.02
Dim stringList() As String = New String() {"", "123", "456", "789", "a"}
Dim intList() As Integer
intList = (From str As String In stringList
Where Integer.TryParse(str, Nothing)
Select (Integer.Parse(str))).ToArray
Everything is much easier ))
Dim NewIntArray = YouStringArray.Select(Function(x) CInt(x)).ToArray
I want to be able to effectively search an array for the contents of a string.
Example:
dim arr() as string={"ravi","Kumar","Ravi","Ramesh"}
I pass the value is "ra" and I want it to return the index of 2 and 3.
How can I do this in VB.NET?
It's not exactly clear how you want to search the array. Here are some alternatives:
Find all items containing the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))
Find all items starting with the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))
Find all items containing any case version of "ra" (returns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))
Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
-
If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.
Example:
Function ContainsRa(s As String) As Boolean
Return s.Contains("Ra")
End Function
Usage:
Dim result As String() = Array.FindAll(arr, ContainsRa)
Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:
Public Class ArrayComparer
Private _compareTo As String
Public Sub New(compareTo As String)
_compareTo = compareTo
End Sub
Function Contains(s As String) As Boolean
Return s.Contains(_compareTo)
End Function
Function StartsWith(s As String) As Boolean
Return s.StartsWith(_compareTo)
End Function
End Class
Usage:
Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))
If you want an efficient search that is often repeated, first sort the array (Array.Sort) and then use Array.BinarySearch.
In case you were looking for an older version of .NET then use:
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result As New List(Of Integer)
For i As Integer = 0 To arr.Length
If arr(i).Contains("ra") Then result.Add(i)
Next
End Sub
End Module
check this..
string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
Array.IndexOf(strArray, "C"); // not found, returns -1
Array.IndexOf(strArray, "CDE"); // found, returns index
compare properties in the array if one matches the input then set something to the value of the loops current position, which is also the index of the current looked up item.
simple eg.
dim x,y,z as integer
dim aNames, aIndexes as array
dim sFind as string
for x = 1 to length(aNames)
if aNames(x) = sFind then y = x
y is then the index of the item in the array, then loop could be used to store these in an array also so instead of the above you would have:
z = 1
for x = 1 to length(aNames)
if aNames(x) = sFind then
aIndexes(z) = x
z = z + 1
endif
VB
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()
C#
string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();
-----Detailed------
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim searchStr = "ra"
'Not case sensitive - checks if item starts with searchStr
Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Case sensitive - checks if item starts with searchStr
Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Not case sensitive - checks if item contains searchStr
Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
Stop
End Sub
End Module
Never use .ToLower and .ToUpper.
I just had problems in Turkey where there are 4 "i" letters. When using ToUpper I got the wrong "Ì" one and it fails.
Use invariant string comparisons:
Const LNK as String = "LINK"
Dim myString = "Link"
Bad:
If myString.ToUpper = LNK Then...
Good and works in the entire world:
If String.Equals(myString, LNK , StringComparison.InvariantCultureIgnoreCase) Then...
This would do the trick, returning the values at indeces 0, 2 and 3.
Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))