filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/sorting/src/sleep_sort/sleep_sort.jl | count = 0
function sleep_and_print(n)
global count
sleep(n)
count += 1
println(n)
end
a = [5, 3, 6, 2, 3, 2, 2];
for i=1:length(a)
@async sleep_and_print(a[i])
end
# wait for all threads to complete
while count != length(a)
sleep(1)
end
|
code/sorting/src/sleep_sort/sleep_sort.js | /**
* Sleep Sort Implementation in JavaScript
*
* @author Ahmar Siddiqui <[email protected]>
* @github @ahhmarr
* @date 07/Oct/2017
* Part of Cosmos by OpenGenus Foundation
*/
function sleepNumber(number) {
// The timeout is (n^2) so that close numbers are no longer close.
// Example: 1 is really ... |
code/sorting/src/sleep_sort/sleep_sort.m | /* Part of Cosmos by OpenGenus Foundation */
//
// sleep_sort.m
// Created by DaiPei on 2017/10/12.
//
#import <Foundation/Foundation.h>
@interface SleepSort : NSObject
- (void)sort:(NSMutableArray<NSNumber *> *)array;
@end
@implementation SleepSort
- (void)sort:(NSMutableArray<NSNumber *> *)array {
dispat... |
code/sorting/src/sleep_sort/sleep_sort.php | <?php
//Sleep Sort in PHP
//Author: Amit Kr. Singh
//Github: @amitsin6h
//Social: @amitsin6h
//OpenGenus Contributor
// Part of Cosmos by OpenGenus Foundation
$list = range(1,10);
shuffle($list);
foreach($list as $li){
$pid = pcntl_fork();
if($pid == -1){
die('could not fork');
}else if($pid == 0){
sleep(... |
code/sorting/src/sleep_sort/sleep_sort.py | # Part of Cosmos by OpenGenus Foundation
import threading
import time
_lk = threading.Lock()
class sleep_sort_thread(threading.Thread):
def __init__(self, val):
self.val = val
threading.Thread.__init__(self)
def run(self):
global _lk
# Thread is made to sleep in proportion to... |
code/sorting/src/sleep_sort/sleep_sort.rb | # Part of Cosmos by OpenGenus Foundation
def sleep_sort(arr, time = 0.01)
require 'thread'
# We need a semaphore to synchronize the access of the shared resource result
mutex = Mutex.new
result = []
# For each element in the array, create a new thread which will sleep.
threads = arr.collect do |e|
Threa... |
code/sorting/src/sleep_sort/sleep_sort.scala | object Main
{
def sleep_sort(xs: List[Int]): List[Int] =
{
var r: List[Int] = Nil
var threads: List[Thread] = Nil
for (x <- xs)
{
val t = new Thread(new Runnable
{
def run()
{
Thread.sleep(x)
this.synchronized
{
r = r:+ x
... |
code/sorting/src/sleep_sort/sleep_sort.sh | #sleep sort in shell script only for positive numbers
# Part of Cosmos by OpenGenus Foundation
function f(){
sleep "$1"
echo "$1"
}
while [ -n "$1" ]
do
f "$1" &
shift
done
wait
|
code/sorting/src/sleep_sort/sleep_sort.swift | /* Part of Cosmos by OpenGenus Foundation */
//
// sleep_sort.swift
// Created by DaiPei on 2017/10/12.
//
import Foundation
import Dispatch
func sleepSort(_ array: [Int]) {
let group = DispatchGroup()
for i in 0..<array.count {
let queue = DispatchQueue(label: "com.my.queue")
queue.async(g... |
code/sorting/src/slow_sort/README.md | # Slow Sort
Slowsort is a recursive algorithm. It sorts in-place.
It is a stable sort. (It does not change the order of equal-valued keys.)
## Explantation
Input : {4, -9, 5, 8,-2, 4 78}
Output: {-9, -2, 4, 4, 5, 8, 78}
## Algorithm
function slowsort(A[], i, j)
if i ≥ j then
return
m := floor( (i+j... |
code/sorting/src/slow_sort/slow_sort.cpp | /* Part of Cosmos by OpenGenus Foundation */
#pragma once
#include <bits/stdc++.h>
using namespace std;
/**
* @brief implement the slowSort Algorithm
*
* @param vect_ vector to be sorted
* @param i ith index of vector
* @param j jth index of vector
*/
void slowSort( vector<int32_t>& vect_, int i, int j )
{
... |
code/sorting/src/slow_sort/slow_sort.java | import java.util.Arrays;
public class slow_sort {
/*
* Function that implements the slow sort algorithm
* @param arr[] Array of elements
* @param i Recursion leftmost index
* @param j Recursion rightmost index
*/
static void slowSort(int arr[], int i, int j)
{
if (i >= j) { // Return... |
code/sorting/src/stooge_sort/README.md | # Stooge Sort
Stooge sort is a recursive sorting algorithm.
The algorithm is defined as follows:
1) If the value at the start is larger than the value at the end, swap them.
2) If there are 3 or more elements in the list, then:
* Stooge sort the initial 2/3 of the list
* Stooge sort the final 2/3 of the list
... |
code/sorting/src/stooge_sort/stooge_sort.c | /* Part of Cosmos by OpenGenus Foundation */
#include <stdio.h>
void stooge_sort(int *input, int firs_num, int last_num)
{
int temp = 0;
int t = 0;
if(input[firs_num] > input[last_num])
{
temp = input[firs_num];
input[firs_num] = input[last_num];
input[last_num] = temp;
}
if((last_num - firs_num + 1) >= 3... |
code/sorting/src/stooge_sort/stooge_sort.cpp | // Part of Cosmos by OpenGenus
#include <bits/stdc++.h>
using namespace std;
// Function to implement stooge sort
void stoogesort(int arr[],int l, int h)
{
if (l >= h)
return;
// If first element is smaller than last,
// swap them
if (arr[l] > arr[h])
swap(arr[l], arr[h]);
... |
code/sorting/src/stooge_sort/stooge_sort.go | /* Part of Cosmos by OpenGenus Foundation */
package main
import "fmt"
/*
* If the value at the start is larger than the value at the end, swap them.
* If there are 3 or more elements in the list, then:
* Stooge sort the initial 2/3 of the list
* Stooge sort the final 2/3 of the list
* Stooge sort the initial 2/3 of ... |
code/sorting/src/stooge_sort/stooge_sort.java | //This is a java program to sort numbers using Stooge Sort
import java.util.Random;
public class StoogeSort
{
public static int N = 20;
public static int[] sequence = new int[N];
public static int[] stoogeSort(int[] L, int i, int j)
{
if (L[j] < L[i])
{
int swap = L[... |
code/sorting/src/stooge_sort/stooge_sort.js | // Part of Cosmos by OpenGenus Foundation
function stoogeSort(a) {
function sort(left, right) {
if (a[left] > a[right]) {
[a[left], a[right]] = [a[right], a[left]];
}
if (right - left > 1) {
const third = Math.floor((right - left + 1) / 3);
sort(left, right - third);
sort(left + t... |
code/sorting/src/stooge_sort/stooge_sort.py | #!/usr/bin/env python2
# Part of Cosmos by OpenGenus Foundation
def stooge_sort(a):
def sort(left, right):
if a[left] > a[right]:
a[left], a[right] = a[right], a[left]
if right - left > 1:
third = (right - left + 1) // 3
sort(left, right - third)
sort... |
code/sorting/src/topological_sort/readme.md | # Topological Sort
A topological sort is a simple algorithm that outputs the linear ordering of vertices/nodes of a DAG(Directed Acyclic Graph), where for each directed edge from node A to node B(A :arrow_right: B), node A appears before node B in ordering.
## Explanation:
There are two conditions for this algorithm ... |
code/sorting/src/topological_sort/topological_sort.c | #include <stdio.h>
// Part of Cosmos by OpenGenus Foundation
int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j... |
code/sorting/src/topological_sort/topological_sort.cpp | // A C++ program to print topological sorting of a DAG
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <list>
#include <stack>
using namespace std;
// Class to represent a graph
class Graph
{
int V; // No. of vertices'
// Pointer to an array containing adjacency listsList
list<int> *... |
code/sorting/src/topological_sort/topological_sort.java | import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class TopologicalSort
{
private Stack<Integer> stack;
public TopologicalSort()
{
stack = new Stack<Integer>();
}
public int [] topological(int adjacency_matrix[][], int source) throws Nul... |
code/sorting/src/topological_sort/topological_sort.py | from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def topologicalSortUtil(self, v, visited, stack):
visited[v] = True # Mark current node as vi... |
code/sorting/src/tree_sort/README.md | # Tree Sort
Tree sort is a sorting algorithm that is based on Binary Search Tree data structure. It first creates a binary search tree from the elements of the input list or array and then performs an in-order traversal on the created binary search tree to get the elements in sorted order.
Its typical use is sorting... |
code/sorting/src/tree_sort/tree_sort.c | #include <stdio.h>
#include <alloc.h>
// Part of Cosmos by OpenGenus Foundation
struct btreenode
{
struct btreenode *leftchild ;
int data ;
struct btreenode *rightchild ;
} ;
void insert ( struct btreenode **, int ) ;
void inorder ( struct btreenode * ) ;
void main( )
{
struct btreenode *bt ;
int ... |
code/sorting/src/tree_sort/tree_sort.cpp | //Tree Sort implemented using C++
// Part of Cosmos by OpenGenus Foundation
#include <vector>
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *left, *right;
};
//Function to create new Node
struct Node *newnode(int key)
{
struct Node *temp = new Node;
temp->data = key;
... |
code/sorting/src/tree_sort/tree_sort.go | package main
import "fmt"
// Part of Cosmos by OpenGenus Foundation
/**************************************
* Structures
**************************************/
// Define binary tree structure
//
// - data : the value in the tree
// - right : the sub-tree of greater or equal values
// - left : th... |
code/sorting/src/tree_sort/tree_sort.java | // Part of Cosmos by OpenGenus Foundation
public class Tree {
public static void main(String[] args) {
TreeSort myTree;
myTree = new TreeSort(4);
myTree.invert(new TreeSort(5));
myTree.invert(new TreeSort(8));
myTree.invert(new TreeSort(1));
myTree.traverse(new Key... |
code/sorting/src/tree_sort/tree_sort.js | // Part of Cosmos by OpenGenus Foundation
var BinarySearchTree = function(value) {
var instance = Object.create(BinarySearchTree.prototype);
instance.value = value;
// a BST where all values are higher than than the current value.
instance.right = undefined;
// a binary search tree (BST) where all values are... |
code/sorting/src/tree_sort/tree_sort.php | <?php
// Part of Cosmos by OpenGenus
namespace SF;
class TreeSort
{
public static function sort($input, $options = array())
{
$output = array();
$all = array();
$dangling = array();
// Initialize arrays
foreach ($input as $entry) {
$entry['children'] = array();
$entry['active'] = false;
... |
code/sorting/src/tree_sort/tree_sort.py | # Part of Cosmos by OpenGenus Foundation
class Node:
"""Base class to contain the tree metadata per instance of the class"""
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
def binary_insert(root, node):
"""This recursive function will insert the... |
code/sorting/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/sorting/test/test_sort.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
/*
* guide
*
* 1. substitute iterator (col:28)
* 2. substitute sort algorithm (col: 70)
* 3. run
*/
#define CATCH_CONFIG_MAIN
#ifndef SORT_TEST
#define SORT_TEST
#include "../../../test/c++/catch.hpp"
#include <forward_list>
#include <list>
#include <deque>
#incl... |
code/sorting/test/test_sort.py | """
Part of Cosmos by OpenGenus Foundation
"""
import random
import copy
# import bead_sort # result error
# import bead_sort_numpy # error
# import bucket_sort # error
# import circle_sort # error, tried
# import counting_sort # error, tried
# import radix_sort # error
# sort_func = bead_sort.bead_sort
# sort_func... |
code/sorting/test/test_sort.swift | /* Part of Cosmos by OpenGenus Foundation */
import Foundation
let maxSize = 100
class TestSort {
func test() {
let less = { (a: UInt32, b: UInt32) -> Bool in
return a < b
}
var origin = [UInt32](),
expect = origin,
actual = expect
// test wit... |
code/square_root_decomposition/src/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/square_root_decomposition/src/mos_algorithm/mos_algorithm.cpp | //Time Complexity : O((n+q)*sqrt(n))
#include <bits/stdc++.h>
#include <cmath>
/* Part of Cosmos by OpenGenus Foundation */
#define ll long long int
#define mod 1000000007
#define show(a) for (i = 0; i < a.size(); i++) cout << a[i] << " ";
#define fi first
#define se second
#define vi vector<int>
#define vs vector<... |
code/square_root_decomposition/src/mos_algorithm/sqrtdecomposition.py | # PROBLEM STATEMENT-> You are given an array A of size N and Q queries.(All indexes are 1 based).
# Each query can be of two types
# 1-> 1 i - add 1 to the ith element of the array A
# 2-> 2 K - print the Kth odd number of the array A if it exists, else print -1
def precalculate(n, array):
bucket... |
code/square_root_decomposition/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/string_algorithms/src/Longest_common_subsequence/longest_common_subsequence.c | #include <stdio.h>
#include <string.h>
/* Part of Cosmos by OpenGenus Foundation */
int i, j, m, n, LCS_table[20][20];
char S1[20] , S2[20], b[20][20];
void lcsAlgo() {
m = strlen(S1);
n = strlen(S2);
// Filling 0's in the matrix
for (i = 0; i <= m; i++)
LCS_table[i][0] = 0;
for (i = 0; i <= n; i++)
... |
code/string_algorithms/src/README.md | # cosmos #
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/string_algorithms/src/aho_corasick_algorithm/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/string_algorithms/src/aho_corasick_algorithm/aho_corasick_algorithm.cpp | #include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAXC = 26;
const int MAXS = 500;
int out[MAXS];
int f[MAXS];
int g[MAXS][MAXC];
int buildMatchingMachine(string arr[], int k)
{
memset(out, 0, sizeof out);
memset(g, -1, sizeof g);
int states = 1;
for (int i = 0; i < ... |
code/string_algorithms/src/aho_corasick_algorithm/aho_corasick_algorithm.java | import java.util.*;
public class AhoCorasick {
static final int ALPHABET_SIZE = 26;
Node[] nodes;
int nodeCount;
public static class Node {
int parent;
char charFromParent;
int suffLink = -1;
int[] children = new int[ALPHABET_SIZE];
int[] transitions = new int[ALPHABET_SIZE];
boolean leaf;
{
A... |
code/string_algorithms/src/aho_corasick_algorithm/aho_corasick_algorithm2.cpp | #include <vector>
#include <fstream>
#include <queue>
using namespace std;
const int MAXN = 1000005;
char word[MAXN];
int n;
struct trie_node
{
int nr;
trie_node *children[26];
trie_node *fail;
vector<trie_node* >out;
trie_node()
{
nr = 0;
for (int i = 0; i < 26; i++)
... |
code/string_algorithms/src/anagram_search/README.md | ## Anagram Search
An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.

### The... |
code/string_algorithms/src/anagram_search/anagram.scala | object Anagram {
def isAnagram(a: String, b: String): Boolean = {
val a1 = a.replaceAll("\\s", "")
val b1 = b.replaceAll("\\s", "")
if (a1.length != b1.length)
false
else
frequencyMap(a1.toLowerCase()) == frequencyMap(b1.toLowerCase())
}
def frequencyMap(str: String) = str.groupBy(ide... |
code/string_algorithms/src/anagram_search/anagram_search.c | #include <stdio.h>
#include <string.h>
int
main(void)
{
char string1[1000], string2[1000], temp;
int length_string1, length_string2;
scanf("%s", string1);
scanf("%s", string2);
length_string1 = strlen(string1);
length_string2 = strlen(string2);
/* If both strings are of different length, then they are not a... |
code/string_algorithms/src/anagram_search/anagram_search.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
* Checks if two strings are anagrams of each other, ignoring any whitespace.
*
* Create maps of the counts of every character in each string.
* As well as keep a set of all characters u... |
code/string_algorithms/src/anagram_search/anagram_search.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AnagramSearch
{
class Program
{
static void Main(string[] args)
{
printAnagramResult("Anagram", "Nag A Ram", anagram_search("Anagram", "Nag A Ram"));
... |
code/string_algorithms/src/anagram_search/anagram_search.go | //Part of the Cosmos Project by OpenGenus
//Find out if two strings are angram
//Written by Guilherme Lucas (guilhermeslucas)
package main
import (
"fmt"
"sort"
"strings"
)
func prepareString(w string) string {
s := strings.Split(w, "")
sort.Strings(s)
return strings.Join(s, "")
}
func isAnag... |
code/string_algorithms/src/anagram_search/anagram_search.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.Arrays;
import java.util.Scanner;
public class anagram_search {
static void isAnagram(String str1, String str2) {
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
... |
code/string_algorithms/src/anagram_search/anagram_search.js | // Part of Cosmos by OpenGenus Foundation
// Checks if two strings are anagrams of each other, ignoring any whitespace.
//
// Remove whitespaces in both strings.
// Make all characters in both strings lowercase.
// Use .reduce() to create a hash table for each word containing the counts for each letter.
// Compare bot... |
code/string_algorithms/src/anagram_search/anagram_search.py | """ Part of Cosmos by OpenGenus Foundation"""
import collections
def removeWhitespace(string):
return "".join(string.split())
"""
Checks if two strings are anagrams of each other, ignoring any whitespace.
First remove any whitespace and lower all characters of both strings.
Then create diction... |
code/string_algorithms/src/anagram_search/anagram_search.rb | FIRST_TWENTY_SIX_PRIMES = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
79, 83, 89, 97, 101 ].freeze
def anagram_number(word)
word.downcase.chars.map do |letter|
letter.ord - 'a'.ord
end.reject do |index|
index < 0 || index >= FIRST_TWENTY_SIX_PRIMES.size
end.map... |
code/string_algorithms/src/anagram_search/anagram_search.swift | /* Part of Cosmos by OpenGenus Foundation */
import Foundation
extension String {
/*
* Checks if two strings are anagrams of each other,
* ignoring case and whitespaces.
*/
func isAnagram(of other: String) -> Bool {
let selfChars = self.removingWhitespaces().lowercased()... |
code/string_algorithms/src/arithmetic_on_large_numbers/string_addition.cpp | #include <string>
#include <iostream>
#include <cassert>
std::string strAdd(std::string s, std::string r)
{
int re = 0;
std::string sum;
// precondition for empty strings
assert(s.length() > 0 && r.length() > 0);
if (r.length() < s.length())
r.insert(r.begin(), s.length() - r.length(), '0... |
code/string_algorithms/src/arithmetic_on_large_numbers/string_factorial.cpp | #include <vector>
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter The Number for Factorial" << endl;
cin >> n;
vector<int> digit;
digit.push_back(1);
for (int j = 1; j < n + 1; j++)
{
int x = 0, y = 0;
for (int i = digit.size() - 1; i >= 0; i--)
... |
code/string_algorithms/src/arithmetic_on_large_numbers/string_multiplication.cpp | #include <string>
#include <iostream>
using namespace std;
string strAdd(string s, string r)
{
int re = 0;
string digit;
if (r.length() < s.length())
r.insert(r.begin(), s.length() - r.length(), '0');
else if (r.length() > s.length())
s.insert(s.begin(), r.length() - s.length(), '0');
... |
code/string_algorithms/src/arithmetic_on_large_numbers/string_subtract.cpp | #include <string>
#include <iostream>
#include <algorithm>
using namespace std;
bool isSmaller(string str1, string str2)
{
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true;
if (n2 < n1)
return false;
for (int i = 0; i < n1; i++)
{
if (str1[i] < str2[i]... |
code/string_algorithms/src/boyer_moore_algorithm/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/string_algorithms/src/boyer_moore_algorithm/boyer_moore_algorithm.c | # include <limits.h>
# include <string.h>
# include <stdio.h>
/* Part of Cosmos by OpenGenus Foundation */
# define NO_OF_CHARS 256
int
max(int a, int b)
{
return ((a > b) ? a: b);
}
void
badCharHeuristic(char *str, int size,
int badchar[NO_OF_CHARS])
{
int i;
for (i = 0; i < NO_OF_CHARS; i++)
badchar[i] ... |
code/string_algorithms/src/boyer_moore_algorithm/boyer_moore_algorithm.cpp | #include <iostream>
#include <cstring>
#define NO_OF_CHARS 256
int max(int a, int b)
{
return (a > b) ? a : b;
}
void badCharHeuristic(char *str, int size, int badchar[NO_OF_CHARS])
{
int i;
for (i = 0; i < NO_OF_CHARS; i++)
badchar[i] = -1;
for (i = 0; i < size; i++)
badchar[(int) str... |
code/string_algorithms/src/boyer_moore_algorithm/boyer_moore_algorithm2.c | /* Part of Cosmos by OpenGenus Foundation */
/*
* Pointer based implementation of the Boyer-Moore String Search Algorithm
*/
#include <stdio.h>
#include <string.h>
/*
* Number of characters in the text alphabet used by the search and pattern strings
* For 8-bit strings, use 256
*/
#define NO_OF_CHARS 256
/*
*... |
code/string_algorithms/src/finite_automata/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/string_algorithms/src/finite_automata/c/c/makefile | main: main.c dfa.h dfa.c types.c types.h
gcc -o main main.c dfa.c types.c |
code/string_algorithms/src/finite_automata/c/dfa.c | /*
* Part of Cosmos by OpenGenus.
* Author : ABDOUS Kamel
*/
#include "dfa.h"
#include <stdlib.h>
/* This array is used when doing a dfs */
static dfs_color_t* dfs_colors;
/* Tells if a state is accessible, when removing useless states */
static bool* access_bits;
/* Stores the new ids of states, when removing u... |
code/string_algorithms/src/finite_automata/c/dfa.h | /*
* Part of Cosmos by OpenGenus.
* Author : ABDOUS Kamel
*/
#ifndef AUTOMATA_DFA_H
#define AUTOMATA_DFA_H
#include "types.h"
/*
* Definition of a DFA.
*/
typedef struct dfa_s
{
int alpha_size;
state_t* states;
int states_nb;
state_id_t start_id;
/*
* This is a transition matrix.
* -1 indicat... |
code/string_algorithms/src/finite_automata/c/main.c | /*
* Part of Cosmos by OpenGenus.
* Author : ABDOUS Kamel
*/
#include <stdio.h>
#include <stdlib.h>
#include "dfa.h"
int
main()
{
dfa_t dfa;
/* A DFA to recognize all strings with 01 as a substring */
allocate_dfa(3, &dfa);
/* States are labelled with positive integers */
dfa.start_id = 0;
dfa.states... |
code/string_algorithms/src/finite_automata/c/types.c | /*
* Part of Cosmos by OpenGenus.
* Author : ABDOUS Kamel
*/
#include "types.h"
#include <stdlib.h>
/*
* Allocate a new state_link_t and return a pointer to it.
*/
state_link_t* alloc_state_link(state_id_t id)
{
state_link_t* ret = malloc(sizeof(*ret));
ret->state = id;
ret->next = NULL;
return (ret);
}... |
code/string_algorithms/src/finite_automata/c/types.h | /*
* Part of Cosmos by OpenGenus.
* Author : ABDOUS Kamel
*/
#ifndef AUTOMATA_TYPES_H
#define AUTOMATA_TYPES_H
#include <stdbool.h>
/* States are labelled by positive integers instead of strings */
typedef int state_id_t;
/* A symbol is a single char */
typedef char symbol_t;
typedef enum dfs_color_e
{
WHITE,... |
code/string_algorithms/src/finite_automata/searchstringusingdfa.java | // Part of Cosmos by OpenGenus Foundation
import java.util.Scanner;
public class SearchStringUsingDFA
{
public static final int NO_OF_CHARS = 256;
public static int getNextState(char[] pat, int M, int state, int x)
{
if (state < M && x == pat[state])
return state + 1;
int ns... |
code/string_algorithms/src/finite_automata/searchstringusingdfa.rs | use std::io;
fn search(string: &str, pattern: &str, start: u64, prev_match: bool) -> (bool, u64) {
// Returns if start index is `ge` string length
if start >= string.len() as u64 {
return (false, start);
}
// Checks whether the char at string[start] equals the first char of pattern
if strin... |
code/string_algorithms/src/kasai_algorithm/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/string_algorithms/src/kasai_algorithm/kasai_algorithm.cpp | /*
*
* Kasai Algorithm
* https://www.geeksforgeeks.org/%C2%AD%C2%ADkasais-algorithm-for-construction-of-lcp-array-from-suffix-array/
*
*/
#include <iostream>
#include <vector>
#include <string>
std::vector<int> kasaiAlgorithm(std::string s, std::vector<int> suffix_array)
{
size_t m = 0;
std::vector<int> L... |
code/string_algorithms/src/kmp_algorithm/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/string_algorithms/src/kmp_algorithm/kmp.java | class KMP_String_Matching {
void KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
// create lps[] that will hold the longest
// prefix suffix values for pattern
int lps[] = new int[M];
int j = 0; // index for pat[]
// Pre... |
code/string_algorithms/src/kmp_algorithm/kmp.py | def getLPS(pattern):
m = len(pattern)
lps = [0] * (m + 1)
i = 0
j = -1
lps[i] = j
while i < m:
while j >= 0 and pattern[i] != pattern[j]:
j = lps[j]
i += 1
j += 1
lps[i] = j
return lps
text = "ABC ABCDAB ABCDABCDABDE"
pattern = "ABCDABD"
lps = g... |
code/string_algorithms/src/kmp_algorithm/kmp_algorithm.cpp | // C++ program for implementation of KMP pattern searching
// algorithm
#include <string>
#include <iostream>
using namespace std;
void computeLPSArray(string pat, int M, int *lps);
// Prints occurrences of txt[] in pat[]
void KMPSearch(string pat, string txt)
{
int M = pat.length();
int N = txt.length();
... |
code/string_algorithms/src/levenshtein_distance/README.md | # Levenshtein Distance
The Levenshtein distance between two strings measures the similarity between them by calculating the **minimum number of one-character insertions, deletions, or substitutions required to change one string into another**. This edit distance is often used in spell chekers, plagiarism detectors, an... |
code/string_algorithms/src/levenshtein_distance/levenshteindistance.java | // Part of Cosmos by OpenGenus Foundation
class LevenshteinDistance {
private String a, b;
private int n, m;
private int[][] dp;
public LevenshteinDistance(String a, String b) {
this.a = a;
this.b = b;
n = a.length();
m = b.length();
dp = new int[n + 1][m + 1];
... |
code/string_algorithms/src/lexicographically_largest_palindrome_subsequence/Lexicographyically_largest_palindrome_subsequence.cpp | /* C++ Program to find lexicographically largest palindrome subsequence
In this Program only input line contains a non-empty string S consisting of lowercase English letters only. Its length does not exceed 10.
Here, Characters in the strings are compared according to their ASCII codes and the one with largest ASCII c... |
code/string_algorithms/src/lipogram_checker/lipogram_checker.cpp | // Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <string>
const std::string alphabets = "abcdefghijklmnopqrstuvwxyz";
void
panLipogramChecker(std::string phrase)
{
using std::cout;
using std::endl;
for (unsigned int i = 0; i < phrase.length(); i++)
phrase[i] = tolower(phrase... |
code/string_algorithms/src/lipogram_checker/lipogram_checker.cs | using System;
/*
* Part of cosmos by OpenGenus Foundation
* */
namespace lipogram_checker
{
class Program
{
/// <summary>
/// Method to check if a string is lipogram or not
/// </summary>
/// <param name="str">String To Check</param>
/// <returns>Integer Value</returns... |
code/string_algorithms/src/lipogram_checker/lipogram_checker.js | /* Checker */
const alphabet = [..."abcdefghijklmnopqrstuvwxyz"];
const countUnused = str =>
alphabet.reduce(
(unused, char) => unused + !str.toLowerCase().includes(char),
0
);
const checkLipogram = str => {
let unused = countUnused(str);
return unused >= 2
? "Not a pangram but might a lipogram"
... |
code/string_algorithms/src/lipogram_checker/lipogram_checker.py | """
A pangram or holoalphabetic sentence is a sentence using every letter of a given alphabet at least once.
The best-known English pangram is "The quick brown fox jumps over the lazy dog."
A pangrammatic lipogram is a text that uses every letter of the alphabet but excludes one of them.
"""
# Part of Cosmos by OpenGe... |
code/string_algorithms/src/longest_palindromic_substring/longest_palindromic_substring.cpp | // Part of Cosmos by OpenGenus
#include <iostream>
#include <string>
using namespace std;
// expand in both directions of low and high to find
// maximum length palindrome
string expand(string str, int low, int high)
{
int len = str.length();
// run till str[low.high] is a palindrome
while (low >= 0 && high < len ... |
code/string_algorithms/src/longest_palindromic_substring/longest_palindromic_substring.js | /*
Path of Cosmos by OpenGenus
To find the longest palindromic substring in JavaScript
Example : Input String : "agbdcdbty" the palindromic substring is "bdcdb"
*/
// A utility function to check if a substring is a palindrome
function isPalindrome(str){
var rev = str.split("").reverse... |
code/string_algorithms/src/longest_palindromic_substring/longest_palindromic_substring.py | def expand_center(s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l + 1 : r]
def longest_pal_substr(s):
ans = ""
for c in range(len(s)):
s1 = expand_center(s, c, c)
s2 = expand_center(s, c, c + 1)
ans = max(ans, s1, s2, key=len)
... |
code/string_algorithms/src/manachar_algorithm/manachar_longest_palindromic_subs.cpp | #include <string>
#include <iostream>
#include <cmath>
/* Part of Cosmos by OpenGenus Foundation */
using namespace std;
#define SIZE 100000 + 1
size_t P[SIZE * 2];
// Transform S into new string with special characters inserted.
string convertToNewString(const string &s)
{
string newString = "@";
for (size... |
code/string_algorithms/src/manachar_algorithm/manachar_longest_palindromic_subs.py | # Part of Cosmos by OpenGenus Foundation
def get_palindrome_length(string, index):
length = 1
while index + length < len(string) and index - length >= 0:
if string[index + length] == string[index - length]:
length += 1
else:
break
return length - 1
def interleave(s... |
code/string_algorithms/src/morse_code/morsecode.cpp | #include <iostream>
#include <string>
#include <vector>
std::pair<char, std::string> pairing(char alpha, std::string morse_code);
std::string finder(const std::vector<std::pair<char, std::string>> &mp, std::string value);
std::string wordToMorse(const std::vector<std::pair<char, std::string>> &mp, std::string input);
... |
code/string_algorithms/src/morse_code/morsecode.go | // Part of Cosmos by OpenGenus Foundation
package main
import (
"fmt"
"strings"
)
var (
morseAlphabet = map[rune]string{
'A': ".-", 'B': "-...", 'C': "-.-.", 'D': "-..", 'E': ".", 'F': "..-.",
'G': "--.", 'H': "....", 'I': "..", 'J': ".---", 'K': "-.-", 'L': ".-..",
'M': "--", 'N': "-.", 'O': "---", 'P': ".... |
code/string_algorithms/src/morse_code/morsecode.js | // String algorithms | morse code | javascript
// Part of OpenGenus Foundation
const TO_MORSE_MAP = {
A: ".-",
B: "-...",
C: "-.-.",
D: "-..",
E: ".",
F: "..-.",
G: "--.",
H: "....",
I: "..",
J: ".---",
K: "-.-",
L: ".-..",
M: "--",
N: "-.",
O: "---",
P: ".--.",
Q: "--.-",
R: ".-.",... |
code/string_algorithms/src/morse_code/morsecode.php | <?php
/* Part of Cosmos by OpenGenus Foundation */
/* Example Usage:
echo morseEncode('HELLO');
echo morseDecode('.... . .-.. .-.. ---');
*/
function morseDecode($str)
{
$toCharMorseMap = ["A"=> ".-", "B"=> "-...", "C"=> "-.-.", "D"=> "-..", "E"=> ".", "F"=> "..-.", "G"=> "--.", "H"=> "....", "I"=> "..", "... |
code/string_algorithms/src/morse_code/morsecode.py | from functools import reduce
morseAlphabet = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-"... |
code/string_algorithms/src/naive_pattern_search/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/string_algorithms/src/naive_pattern_search/naive_pattern_search.cpp | // # Part of Cosmos by OpenGenus Foundation
#include <cstddef>
#include <cstring>
int search(const char *pattern, const char *text) {
/**
* @brief Searches for the given pattern in the provided text,
*
*
* @param pat Pattern to search for
* @param txt Text to search in
*
* @returns [int] positi... |
code/string_algorithms/src/naive_pattern_search/naive_pattern_search.py | # Part of Cosmos by OpenGenus Foundation
def search(pat, txt):
M = len(pat)
N = len(txt)
# Iterate pat[]
for i in range(N - M + 1):
# For current index i, check for pattern match
for j in range(M):
if txt[i + j] != pat[j]:
break
if j == M - 1: # if p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.