A software engineer's blog

About this Blog

Welcome to my blog! My name is Nikos and I am an engineer. In this blog I will post algorithms and software related stuff that I find interesting or I had a hard time to find online.

Monday, October 3, 2022

FreeBasic implementation of the Brute Force Algorithm



This is my single threaded implementation of the Brute Force algorithm for FreeBasic. The following algorithm uses the StringUtils.Join method of the Kiwi framework. Kiwi can be found on GitHub at https://github.com/nsiatras/kiwi

I transferred this algorithm from Java. The Java algorithm can be found here

/'
    Brute Force Algorithm for FreeBasic 

    Author: Nikos Siatras
    https://github.com/nsiatras
'/

#include once "kiwi\kiwi.bi" ' Kiwi framework is used only for the StringUtils.Join method

Dim Shared fCharList(...) as String * 1  = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
Dim Shared fCharactersListLength as Integer = ubound(fCharList)

/'
	The OnBruteForceWordGenerated sub is called everytime a new word
	is generated from the BruteForce algorithm.
	For this example I choose only to write to word on the screen
'/
Sub OnBruteForceWordGenerated(word as String)
	print word
End Sub

/'
	Change characters to each other and generate BruteForce words
'/
Sub ChangeCharacter(position as Integer, sb(any) as String, wordLength as Integer)

	Dim i as Integer
	Dim x as Integer
	Dim generatedWord as String
	
	for i = 0 to fCharactersListLength
		sb(position) = fCharList(i)
		if position = wordLength - 1 then
			generatedWord = StringUtils.Join(sb(), "")
			OnBruteForceWordGenerated(generatedWord)
		else
		 ChangeCharacter(position + 1, sb(), wordLength)
		end if
	next i	
		
End Sub

/'
	Start Brute Force Generation
	@wordLength is the word's length (how many characters a word can have)
'/
Sub StartBruteForce(wordLength as Integer)

	Dim stringBuilder(wordLength) as String 
	Dim currentChar as String = fCharList(0)
	
	for i as Integer = 1 to wordLength
		 stringBuilder(i-1) = currentChar
	next i 
	
    ChangeCharacter(0, stringBuilder(), wordLength)

End Sub


' Begin Brute Force from 1 to 18 characters
for i as Integer = 1 to 18
	StartBruteForce(i)
next i

0 comments:

Post a Comment