Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions Aho-Corasick/Aho-Corasick.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# AhoNode class
class AhoNode:
def __init__(self):
self.goto = {}
self.out = []
self.fail = None


# creating aho forest
def aho_create_forest(patterns):
root = AhoNode()

for path in patterns:
node = root
for symbol in path:
node = node.goto.setdefault(symbol, AhoNode())
node.out.append(path)
return root


# Creating aho automata
def aho_create_statemachine(patterns):
root = aho_create_forest(patterns)
queue = []
for node in root.goto.values():
queue.append(node)
node.fail = root

while len(queue) > 0:
rnode = queue.pop(0)

for key, unode in rnode.goto.items():
queue.append(unode)
fnode = rnode.fail
while fnode is not None and key not in fnode.goto:
fnode = fnode.fail
unode.fail = fnode.goto[key] if fnode else root
unode.out += unode.fail.out

return root


def aho_find_all(s, root, callback):
node = root

for i in range(len(s)):
while node is not None and s[i] not in node.goto:
node = node.fail
if node is None:
node = root
continue
node = node.goto[s[i]]
for pattern in node.out:
callback(i - len(pattern) + 1, pattern)


# Printing the position of pattern found
def print_pattern(pos, patterns):
print("At pos %s found pattern: %s" % (pos, patterns))


if __name__ == "__main__":
patterns = []

# taking inputs
n = int(input("Enter no. of elements :- "))
for i in range(0, n):
ele = input("Enter element :- ")
patterns.append(ele)
s = input("Enter text :- ")

root = aho_create_statemachine(patterns)
aho_find_all(s, root, print_pattern)


"""
INPUT:
n=6
patterns = ['a', 'ab', 'abc', 'bc', 'c', 'cba']
s = "abcba"

OUTPUT:
At pos 0 found pattern: a
At pos 0 found pattern: ab
At pos 0 found pattern: abc
At pos 1 found pattern: bc
At pos 2 found pattern: c
At pos 2 found pattern: cba
"""
59 changes: 59 additions & 0 deletions Binary_Search/Binary search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/* Implenetation of Binary Search algorithm to find value 6 in a given array of numbers */

function BinarySearch( arr:number[] , n:number , val:number ) :number
{
var start = 0 //starting index of the array
var end = n-1 //ending index
var mid = 0
var ind = -1

while (start <= end)
{
mid = Math.floor((start + end) / 2)

//checking if value to be found is at the middle
if ( val == arr[mid] )
{
ind = mid
break
}

/* if value to be found is greater than the middle then the algorithm
searches to the right of the middle element in the array */
else if ( val > arr[mid] )
{
start = mid + 1
}
/* if value to be found is less than the middle then the algorithm
searches to the left of the middle element in the array */
else
{
end = mid - 1
}
}
return ind //returning the index of the value if found, else returns -1
}
var result = 0
var n = 0
var val = 6 //input value
console.log(" value to be found: ", val);
var n: number = 6 //no. of elements in the array
var arr = [1, 2, 3, 4, 5, 6]; //input array
console.log(" Array of numbers is: ", arr);
result = BinarySearch(arr, n, val)
if (result != -1) {
console.log(" value ", val," found at index no. ", result," in the array ");
}
else {
console.log(" value ", val," not found ");
}


/* OUTPUT:

value to be found: 6
Array of numbers is: [ 1, 2, 3, 4, 5, 6 ]
value 6 found at index no. 5 in the array
*/


88 changes: 88 additions & 0 deletions Binary_Search/Binary_Search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Rust program for Binary Search
use std::io;

fn main() {
println!(" Enter number of elements to be entered in the array ");
let mut size = String::new();

io::stdin().read_line(&mut size).expect("failed to read input.");
let size: usize = size.trim_end().parse().expect("invalid input");
let mut vector: Vec<usize> = Vec::with_capacity(size as usize);

println!("Enter element to be searched " );
let mut element = usize::new();

println!("Enter elements of array in a sorted array ");
let mut index = 0;

// Enter values into vector
while index < size {
index += 1;
// Note: Rust takes spaces as non-intergral value
let mut temp_arr = String::new();
io::stdin().read_line(&mut temp_arr).expect("failed to read input.");
let temp_arr: usize = temp_arr.trim_end().parse().expect("invalid input");
vector.push(temp_arr);
}

// Binary Search process
let mut leftpart = 0;
let mut rightpart = size - 1;
let mut midindex = 0;
let mut checkpoint = 0;
while leftpart <= rightpart {
midindex = leftpart + (rightpart - leftpart) / 2;

// Element found
if vector[midindex] == element{
checkpoint = 1;
println!("Element is found at index ");
println!("{:?}" , midindex + 1);
break;
}

else if vector[midindex] < element{
leftpart = midindex + 1;
}

else {
rightpart = midindex - 1;
}

}

if checkpoint == 0 {
println!("Element is not found in the array ");
}
}
/*
TEST CASE

INPUT
Enter number of elements to be entered in the array
3
Enter element to be searched
2
Enter elements of array in a sorted array
1
2
3

OUTPUT
Element is found at index
2

INPUT
Enter number of elements to be entered in the array
3
Enter element to be searched
5
Enter elements of array in a sorted array
1
2
3

OUTPUT
Element is not found in the array
*/

81 changes: 81 additions & 0 deletions Boyer_Moore_Algorithm/Boyer_Moore.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php
// PHP implementation of Boyer Moore Algorithm for Pattern Searching using
// Bad Character Heuristic

// Function for Boyer Moore's bad character heuristic
function badCharHeuristic(&$badChar, $str, $size){

// Initialize all occurrences as -1
for ($i = 0; $i < 256; $i++)
$badChar[$i] = -1;

// To fill actual value of last occurrence of characters
for ($i = 0; $i < $size; $i++)
$badChar[ord($str[$i])] = $i;
}

// Function that uses Bad Character Heuristic of Boyer Moore Algorithm
// to search pattern
function search($text, $pattern) {

$patternLength = strlen($pattern);
$textLength = strlen($text);
$i = 0;

$badChar = array();
badCharHeuristic($badChar, $pattern, $patternLength);

// s represents pattern shift with respect to text
$s = 0;

while ($s <= ($textLength - $patternLength)){

$j = $patternLength - 1;
// Reduce index j of pattern while characters of pattern and text match at current shift
while ($j >= 0 && $pattern[$j] == $text[$s + $j])
$j--;

// If the pattern is present at current shift, then index j will become -1, so
// Shift the pattern so that the next character in text aligns
// with the last occurrence of it in pattern.
// Else, Shift the pattern so that the bad character in text aligns with
// the last occurrence of it in pattern.
if ($j < 0){
$arr[$i++] = $s;
$s += ($s + $patternLength < $textLength) ?
$patternLength - $badChar[ord($text[$s + $patternLength])] : 1;
}
else
$s += max(1, $j - $badChar[ord($text[$s + $j])]);
}

for ($j = 0; $j < $i; $j++)
$result[$j] = $arr[$j];
return $result;
}

// Sample Input
$text = "I scream, you scream, we all scream for ice cream";
$pattern = "scream";

$occ = search($text, $pattern);
echo "Occurrences of pattern in text are as follows:\n";
foreach ($occ as $res){
echo "$res \n";
}

/*
Sample Input as mentioned in the code-
$text = "I scream, you scream, we all scream for ice cream"
$pattern = "scream"

Sample Output-
Occurrences of pattern in text are as follows:
2
14
29
8
*/
?>


Loading