Skip to main content
gamedev.net
🔒 Locked

[.net] Random Searching Algorithm

Started by Hot_Tamalle Sep 26, 2005 at 12:53 PM 3 replies 400+ views
Original Post
Hot_Tamalle
Hot_Tamalle
Hi, Can anyone please tell me from where can i find a good random searching algorithm. I have a big file which i need to break into blocks and then find a word in them randomly. the file is not sorted in any manner!.... Help
Enselic
Enselic
I guess you don't need an extremly complex algorithm to do that. Just parse the file (there are a bunch of parsing classes within the .NET framework. Look into the System.IO namespace and/or the System.Xml namespace for instance) and then place the parsed words in an String vector. To get a random word you can do like this:
// _words is a a String[] containing the parsed wordsRandom _rnd = new Random();String randomWord = _words[ _rnd.Next( 0, _words.Length ) ];

Links: The Random Class
Hot_Tamalle
Hot_Tamalle
Can you be a little more specific?..i am a little new at this...
capn_midnight
capn_midnight
how about this?
Random r = new Random();string s = //your words read into a string;int startIndex = r.nextInt(s.Length);int begin = 0;if(startIndex > 0){    int begin = s.indexOf(" &*(-+={[\/".ToCharArray(), startIndex);}int end = s.indexOf(" !&*)-+=}]\:;,.?/".ToCharArray(), begin);string word s.substring(begin, end);


sorry, I work on enterprise web portals all day. No one is concerned about performance (or really even correctness) around here.
Enselic
Enselic
Ok. I have here a little program that is not an educational masterpiece, but hopefully you will get a clearer picture of what I mean.

"words.txt" is meant to be a text file, with one word on each row, like this:
MartinSvenErikBertilAdam

This is the (C#) program:
using System;using System.IO;namespace Test{	class MainClass	{		public static void Main(string[] args)		{			// Open the file			TextReader tr = new StreamReader( "words.txt" );						// This is our String array into which we load the words			String[] _words = new string[ 1000 ];						// Number of words			int i = -1;			// While there still are words to read, put them into the array			do {				i++;				_words[ i ] = tr.ReadLine();			} while( _words[ i ] != null );						// Don't forget to close			tr.Close();						// This class will create random numbers for us			Random _rnd = new Random();						// Print a random word			Console.WriteLine( "A random word from the file:" );			Console.WriteLine( _words[ _rnd.Next( 0, i ) ] );						Console.Read();		}	}}

Tell me if there is any unclarities.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.