filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/string_algorithms/src/palindrome_checker/palindrome.c
#include <stdio.h> /* * Part of Cosmos by OpenGenus Foundation */ int isPalindromeIterative(char *input, int length) { int start = 0, end = length - 1; while (start < end) if (input[start++] != input[end--]) return (0); return (1); } int is_palindrome_recursive(char *input, int length) { if (length <= 1) return (1); else if (input[0] != input[length - 1]) return (0); else return (is_palindrome_recursive(input + 1, length - 2)); } int main(void) { printf("Is hello a palindrome (iterative): %d\n", isPalindromeIterative("hello", 5)); printf("Is racecar a palindrome (iterative): %d\n", isPalindromeIterative("racecar", 7)); printf("Is aba a palindrome (iterative): %d\n", isPalindromeIterative("aba", 3)); printf("Is hello a palindrome (recursive): %d\n", is_palindrome_recursive("hello", 5)); printf("Is racecar a palindrome (recursive): %d\n", is_palindrome_recursive("racecar", 7)); printf("Is aba a palindrome (recursive): %d\n", is_palindrome_recursive("aba", 3)); return (0); }
code/string_algorithms/src/palindrome_checker/palindrome.clj
;; Part of Cosmos by OpenGenus Foundation (require '[clojure.string :as str]) (defn palindrome? [word] (let [w (str/lower-case word)] (= w (str/reverse w)))) (defn print-palindromes [words] (doseq [word words] (if (palindrome? word) (println word "is a palindrome")))) (def words '("otto", "hello", "did", "eve", "lucas", "zZz", "sis", "clojure")) ;; otto is a palindrome ;; did is a palindrome ;; eve is a palindrome ;; zZz is a palindrome ;; sis is a palindrome (print-palindromes words)
code/string_algorithms/src/palindrome_checker/palindrome.cpp
#include <iostream> #include <string> using namespace std; // Part of Cosmos by OpenGenus Foundation bool isPalindromeRecursive(string input) { if (input.begin() >= (input.end() - 1)) return true; if (*input.begin() != *(input.end() - 1)) return false; return isPalindromeRecursive(string(++input.begin(), --input.end())); // Check if the substring created by removing a character // is also a palindrome } bool isPalindromeReverse(string input) { return input == string(input.rbegin(), input.rend()); // Check if the string is equal to its reverse } bool isPalindromeIterative(string input) { int start = 0; int end = input.length() - 1; while (start < end) if (input[start++] != input[end--]) return false; return true; } // main function begins here int main() { cout << boolalpha << isPalindromeRecursive("alpha") << endl; // should output false cout << isPalindromeRecursive("racecar") << endl; // should output true cout << isPalindromeRecursive("abba") << endl; // should output true cout << isPalindromeReverse("alpha") << endl; // should output false cout << isPalindromeReverse("racecar") << endl; // should output true cout << isPalindromeReverse("abba") << endl; // should output true cout << isPalindromeIterative("alpha") << endl; // should output false cout << isPalindromeIterative("racecar") << endl; // should output true cout << isPalindromeIterative("abba") << endl; // should output true }
code/string_algorithms/src/palindrome_checker/palindrome.cr
# Part of Cosmos by OpenGenus Foundation class String def palindrome? self == to_s.reverse end end puts "test".palindrome? puts "hahah".palindrome?
code/string_algorithms/src/palindrome_checker/palindrome.cs
using System; using System.Linq; namespace PalindromeChecker { class Program { static void Main(string[] args) { Console.WriteLine(IsPalindrome("Borrow or rob?")); // should output true Console.WriteLine(IsPalindrome("To be, or not to be.")); // should output false Console.WriteLine(IsPalindrome("A Toyota�s a Toyota.")); // should output true Console.WriteLine(IsPalindrome("It's peanut butter jelly time!")); // should output false Console.WriteLine(IsPalindrome("A Santa dog lived as a devil God at NASA.")); // should output true Console.WriteLine(IsPalindrome("Man is not what he thinks he is, he is what he hides.")); // should output false Console.WriteLine(IsPalindrome("Are we not pure? �No, sir!� Panama�s moody Noriega brags. �It is garbage!� Irony dooms a man�a prisoner up to new era.")); // should output true } static bool IsPalindrome(string str) { string s = new string(str.ToLower().Where(c => Char.IsLetterOrDigit(c)).ToArray()); char[] arr = s.ToCharArray(); Array.Reverse(arr); string r = new string(arr); return s == r; } } }
code/string_algorithms/src/palindrome_checker/palindrome.erl
% Part of Cosmos by OpenGenus Foundation -module(palindrome). -export([is_palindrome/1). is_palindrome(String) -> String =:= lists:reverse(String).
code/string_algorithms/src/palindrome_checker/palindrome.ex
# Part of Cosmos by OpenGenus Foundation defmodule Palindrome do def is_palindrome(str), do: str == String.reverse(str) end IO.puts Palindrome.is_palindrome("hahah") IO.puts Palindrome.is_palindrome("hello")
code/string_algorithms/src/palindrome_checker/palindrome.go
/// Part of Cosmos by OpenGenus Foundation /// Find out if a given string is palindrome /// Contributed by: Guilherme Lucas (guilhermeslucas) package main import ( "fmt" "strings" ) func palindrome(array string) bool { array = strings.ToLower(array) size := len(array) var l int var r int l = 0 r = size - 1 for l <= r { if array[l] != array[r] { return false } l = l + 1 r = r - 1 } return true } func main() { if (palindrome("Anna")) { fmt.Println("anna is palindrome") } else { fmt.Println("anna is not palindrome") } if (palindrome("HelLo")) { fmt.Println("hello is palindrome") } else { fmt.Println("hello is not palindrome") } }
code/string_algorithms/src/palindrome_checker/palindrome.hs
module Main where import Data.Char (toLower) palindrome s = lowered == reverse lowered where lowered = map toLower s main = do if palindrome "Tacocat" then putStrLn "tacocat is a palindrome" else putStrLn "tacocat is not a palindrome" if palindrome "HelLo" then putStrLn "hello is a palindrome" else putStrLn "hello is not a palindrome"
code/string_algorithms/src/palindrome_checker/palindrome.java
import java.io.*; import java.lang.*; class Palindrome{ public static void main(String args[]){ String s = "sos"; String reverse = new StringBuffer(s).reverse().toString(); //Convert string to StringBuffer, reverse it and convert StringBuffer into String using toString() if(s.equals(reverse)){ //Compares s and reverse of s and if they are same print Yes else print No System.out.println("Yes"); } else System.out.println("No"); } }
code/string_algorithms/src/palindrome_checker/palindrome.js
// Author: Amit Kr. Singh // Github: @amitsin6h // Social: @amitsin6h // OpenGenus Contributor // Contributor: Igor Antun // Github: @IgorAntun /* Checker */ const checkPalindrome = str => [...str].reverse().join("") === str; /* Tests */ checkPalindrome("malayalam"); // should return true checkPalindrome("racecar"); // should return true checkPalindrome("opengenus"); // should return false checkPalindrome("alpha"); // should return false checkPalindrome("github"); // should return false checkPalindrome("level"); // should return true checkPalindrome("rotator"); // should return true
code/string_algorithms/src/palindrome_checker/palindrome.kt
class Palindrome { fun main(args : Array<String>) { val kayakString = "kayak" val levelString = "level" val sosString = "sos" val reviverString = "reviver" val listOfPalindromes = listOf<String>(kayakString, levelString, sosString, reviverString) fun checkIfPalindrome(list : List<String>) : Boolean { return (list[0] == list[0].reversed() && list[1] == list[1].reversed() && list[2] == list[2].reversed() && list[3] == list[3].reversed()) } checkIfPalindrome(listOfPalindromes) } }
code/string_algorithms/src/palindrome_checker/palindrome.lua
function isPalindrome(myString) return myString == string.reverse(myString) end -- Tests print(isPalindrome("racecar")) -- should return true print(isPalindrome("madam")) -- should return true print(isPalindrome("something")) -- should return false print(isPalindrome("computer")) -- should return false
code/string_algorithms/src/palindrome_checker/palindrome.php
<?php // Author: Napat R. // Github: @peam1234 /* Checker */ function checkPalindrome($input) { return $input === strrev($input); } /* Tests */ echo checkPalindrome('rotator').'<br>'; // should return true echo checkPalindrome('stats').'<br>'; // should return true echo checkPalindrome('morning').'<br>'; // should return false ?>
code/string_algorithms/src/palindrome_checker/palindrome.purs
module Palindrome where import Control.Monad.Aff (Aff) import Control.Monad.Aff.Console (CONSOLE,log) import Data.String (toLower) import Data.String.Yarn (reverse) import Prelude (Unit,bind, pure,unit,(==)) palindromeChecker::String->Aff(console::CONSOLE)Unit palindromeChecker string = do _<- if string == toLower (reverse string) then do log "Palindrome Matching" else do log "Palindrome Not Matching" pure unit main::Aff(console::CONSOLE)Unit main= do _<- palindromeChecker "Tharun" _<- palindromeChecker "MalaYaLam" pure unit
code/string_algorithms/src/palindrome_checker/palindrome.py
def isPalindromeRecursive(string): if len(string) == 2 or len(string) == 1: return True if string[0] != string[len(string) - 1]: return False return isPalindromeRecursive(string[1 : len(string) - 1]) def isPalindromeReverse(string): return string == string[::-1] def isPalindromeIterative(string): start = 0 end = len(string) - 1 while start < end: start = start + 1 end = end - 1 if string[start] != string[end]: return False return True if __name__ == "__main__": print(isPalindromeRecursive("alpha")) # should output false print(isPalindromeRecursive("racecar")) # should output true print(isPalindromeRecursive("abba")) # should output true print(isPalindromeReverse("alpha")) # should output false print(isPalindromeReverse("racecar")) # should output true print(isPalindromeReverse("abba")) # should output true print(isPalindromeIterative("alpha")) # should output false print(isPalindromeIterative("racecar")) # should output true print(isPalindromeIterative("abba")) # should output true
code/string_algorithms/src/palindrome_checker/palindrome.rb
# Part of Cosmos by OpenGenus Foundation class String def palindrome? self == to_s.reverse end end puts 'test'.palindrome? puts 'hahah'.palindrome?
code/string_algorithms/src/palindrome_checker/palindrome.rs
// Part of Cosmos by OpenGenus Foundation fn is_palindrome(input: &str) -> bool { let reversed: String = input.chars().rev().collect(); reversed == input } fn main() { println!("{:?}", is_palindrome("test")); println!("{:?}", is_palindrome("hahah")); }
code/string_algorithms/src/palindrome_checker/palindrome.sh
#!/bin/sh # Check if a given string is palindrome palindrome() { str=$1 revstr=$(echo "$1" | rev) if [ "$str" = "$revstr" ] ; then return 0 fi return 255 } # Example # Palindrome if palindrome "aba" ; then echo "Palindrome" else echo "Not Palindrome" fi # Not Palindrome if palindrome "abcdef" ; then echo "Palindrome" else echo "Not Palindrome" fi
code/string_algorithms/src/palindrome_checker/palindrome.swift
/* Part of Cosmos by OpenGenus Foundation */ extension String { public func isPalindrome() -> Bool { return self == String(self.characters.reversed()) } } func test() { print("opengenus".isPalindrome()) // false print("cosmos".isPalindrome()) // false print("level".isPalindrome()) // true print("rotator".isPalindrome()) // true } test()
code/string_algorithms/src/palindrome_checker/palindrome.ts
/* Part of Cosmos by OpenGenus Foundation */ /* Checker */ export function isPalindrome(str: string): boolean { return str.split("").reverse().join("") === str; }; /* Tests */ console.log(isPalindrome("malayalam")); // should return true console.log(isPalindrome("racecar")); // should return true console.log(isPalindrome("opengenus")); // should return false console.log(isPalindrome("alpha")); // should return false console.log(isPalindrome("github")); // should return false console.log(isPalindrome("level")); // should return true console.log(isPalindrome("rotator")); // should return true
code/string_algorithms/src/palindrome_substring/palindrome_substring.c
#include <stdio.h> #define true 1 #define false 0 /* * Utilises 'iattempt' palindrome.c implementation. * Part of Cosmos by OpenGenus Foundation. */ int isPalindromeIterative(char *input, int length) { int start = 0, end = length; while (start < end) if (input[start++] != input[end--]) return false; return true; } int countPalindromeSubstrings(char *input, int length) { int start = 0, end = 0; int response = 0; int original_end = length - 1; while(start < original_end){ for(end = 1; end <= (original_end - start); ++end) response += isPalindromeIterative(&input[start], end); ++start; } return response; } int main(void) { printf("Number of Possible Palindrome Substrings: %d\n", countPalindromeSubstrings("abaab", 5)); return (0); }
code/string_algorithms/src/pangram_checker/README.md
## PANGRAM A pangram is a sentence in which every letter of a given alphabet appears at least once. The most famous pangram in the english language is "The quick brown fox jumps over a lazy dog". _We only try to implement pangram checker algorithms for sentences in english language._ #### Algorithm 1. Set a flag variable and check the input string for every alphabet in the language starting from 'a'. 2. Change the flag variable and add a break statement as soon as the first missing letter is encountered. 3. If every letter is comapared and it's presence evaluated to be true then exit the loop. 4. If the value of flag is unchanged, the sentence is a pangram. 5. Else, the sentence is not a pangram. #### Complexity The Time complexity for the above algorithm will be O(n), where n is the length of input string.
code/string_algorithms/src/pangram_checker/pangram.cpp
/* * pangram.cpp * by Charles (@c650) * * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <string> #include <vector> #include <cctype> /* * Return whether or not str is a pangram, in O(n) time. */ static bool is_pangram(const std::string& str); static void test_pangram(const std::string& test_string, const bool should_be_pangram); int main(void) { /* test for correct ones */ test_pangram("We promptly judged antique ivory buckles for the next prize.", true); test_pangram("How razorback jumping frogs can level six piqued gymnasts.", true); test_pangram("Sixty zippers were quickly picked from the woven jute bag.", true); test_pangram("The quick brown fox jumps over a lazy dog.", true); test_pangram("Waltz, nymph, for quick jigs vex bud.", true); /* test to make sure it doesn't false flag */ test_pangram("", false); test_pangram("I love C++", false); test_pangram("The alphabet", false); test_pangram("131;1)_()[]", false); return 0; } static bool is_pangram(const std::string& str) { const int ALPHA_LEN = 'z' - 'a' + 1; const char ALPHA_BASE = 'a'; std::vector<bool> alphabet(ALPHA_LEN, false); /* we'll flag each character. */ int count = 0; for (const auto& c : str) { /* if the character c isn't alphabetical, or if we've already seen that character, skip it. */ if (!std::isalpha(c) || alphabet[std::tolower(c) - ALPHA_BASE]) continue; /* denote that we saw this character. */ alphabet[std::tolower(c) - ALPHA_BASE] = true; /* increment count. */ ++count; } return count == ALPHA_LEN; } static void test_pangram(const std::string& test_string, const bool should_be_pangram) { std::cout << "Testing if \"" << test_string << "\" is a pangram.\n\t"; if (is_pangram(test_string) == should_be_pangram) std::cout << "Success!"; else std::cout << "WRONG!"; std::cout << "\n"; }
code/string_algorithms/src/pangram_checker/pangram.java
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; // Part of Cosmos by OpenGenus Foundation public class Pangram { public static void main(String args[]) throws Exception { Scanner s = new Scanner(System.in); System.out.println("Enter the String to check for Pangram : "); String sm = s.nextLine(); int count = 0 , k = 0; for(int i = 65 , j = 97 ; (i <= 90 && j <= 122) ; i++ , j++) { k = 0; while(k < sm.length()) { if(sm.charAt(k) != ' ') { if((sm.charAt(k) == (char)i) || (sm.charAt(k) == (char)j)){ count++; break; } } k++; } } if(count == 26) System.out.println("Pangram"); else System.out.println("Not Pangram"); } }
code/string_algorithms/src/pangram_checker/pangram.rb
def pangram?(candidate) ([*'a'..'z'] - candidate.downcase.chars).empty? end
code/string_algorithms/src/pangram_checker/pangram_checker.c
/* * Pangram is a sentence containing every alphabet. * Part of Cosmos by OpenGenus Foundation */ #include<stdio.h> int main() { /* * s: stores the sentence. * letter: Keep track of each alphabet. * count: Keep track of the count. */ char s[10000]; int i, letter[26] = { 0 }, count = 0; puts("\n Enter the String:"); scanf("%[^\n]s", s); for (i = 0; s[i] != '\0'; i++) { if ('a' <= s[i] && s[i] <= 'z') { if (letter[s[i] - 'a'] == 0) { letter[s[i]-'a'] = 1; count++; } } else if('A' <= s[i] && s[i] <= 'Z') { if (letter[s[i]-'A'] == 0) { `letter[s[i]-'A'] = 1; count++; } } } if (count == 26) printf("\n String %s is a Pangram.",s); else printf("\n String %s is NOT a Pangram.",s); return (0); }
code/string_algorithms/src/pangram_checker/pangram_checker.go
package main import "fmt" func main() { for _, s := range []string{ "The quick brown fox jumps over the lazy dog.", `Watch "Jeopardy!", Alex Trebek's fun TV quiz game.`, "Not a pangram.", } { if pangram(s) { fmt.Println("Yes:", s) } else { fmt.Println("No: ", s) } } } func pangram(s string) bool { var missing uint32 = (1 << 26) - 1 for _, c := range s { var index uint32 if 'a' <= c && c <= 'z' { index = uint32(c - 'a') } else if 'A' <= c && c <= 'Z' { index = uint32(c - 'A') } else { continue } missing &^= 1 << index if missing == 0 { return true } } return false }
code/string_algorithms/src/pangram_checker/pangram_checker.js
/* Part of Cosmos by OpenGenus Foundation */ /* Checker */ const alphabet = [..."abcdefghijklmnopqrstuvwxyz"]; const checkPangram = str => alphabet.every(char => str.toLowerCase().includes(char)); /* Test */ checkPangram("Totally not a panagram"); // should return false checkPangram("Still not a panagram"); // should return false checkPangram("The quick brown fox jumps over a lazy dog"); // should return true checkPangram("Pack my box with five dozen liquor jugs"); // should return true checkPangram("The five boxing wizards jump quickly"); // should return true
code/string_algorithms/src/pangram_checker/pangram_checker.m
function trueFalse = isPangram(string) % Part of Cosmos by OpenGenus Foundation trueFalse= isempty(find(histc(lower(string),(97:122))==0,1)); end
code/string_algorithms/src/pangram_checker/pangram_checker.php
<?php // Part of Cosmos by OpenGenus Foundation function pangram_checker($text) { $text = strtolower($text); $alphabet = array_fill(0, 26, false); $count = 0; $length = strlen($text); for ($i = 0; $i < $length; $i++) { $ord = ord($text[$i]); if ($ord >= 97 && $ord <= 122 && !$alphabet[$ord - 97]) { $alphabet[$ord - 97] = true; $count++; } } return $count === 26; } echo pangram_checker('hello') ? 'true' : 'false', "\n"; // false echo pangram_checker('The quick brown fox jumps over the lazy dog') ? 'true' : 'false', "\n"; // true
code/string_algorithms/src/pangram_checker/pangram_checker.py
def pangram_checker(text): # Part of Cosmos by OpenGenus Foundation # Arr is a list that contains a bool value # for each letter if it appeared in the sentence # If the entire list is true the string is a pangram. arr = [False] * 26 for c in text: if (c >= "a" and c <= "z") or (c >= "A" and c <= "Z"): # The character is a letter. c = c.lower() c = ord(c) - ord("a") arr[c] = True # Checking if arr is all true value for index in arr: if not index: return False return True
code/string_algorithms/src/pangram_checker/pangram_checker.swift
// // pangram_checker.swift // test // // Created by Kajornsak Peerapathananont on 10/15/2560 BE. // Copyright © 2560 Kajornsak Peerapathananont. All rights reserved. // // Part of Cosmos by OpenGenus Foundation import Foundation let alphabet = "abcdefghijklmnopqrstuvwxyz" func pangram_checker(string : String) -> Bool { return alphabet.characters.map({string.lowercased().contains($0)}).reduce(true, {$0 && $1}) } func testPangramChecker(){ print(pangram_checker(string: "Totally not a pangram")) print(pangram_checker(string: "The quick brown fox jumps over a lazy dog")) print(pangram_checker(string: "Pack my box with five dozen liquor jugs")) print(pangram_checker(string: "This is not a pangram")) }
code/string_algorithms/src/pangram_checker/pangram_checker.ts
/* Part of Cosmos by OpenGenus Foundation */ /* Checker */ export function isPangram(str: string): boolean { const alphabet: Array<string> = [..."abcdefghijklmnopqrstuvwxyz"]; return alphabet.every((char: string): boolean => { return str.toLowerCase().includes(char) }); } /* Test */ isPangram("Totally not a panagram"); // should return false isPangram("Still not a panagram"); // should return false isPangram("The quick brown fox jumps over a lazy dog"); // should return true isPangram("Pack my box with five dozen liquor jugs"); // should return true isPangram("The five boxing wizards jump quickly"); // should return true
code/string_algorithms/src/password_strength_checker/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/password_strength_checker/pw_checker.cpp
// C++ program for check password strength // // main.cpp // pw_checker // #include <iostream> #include <string> using namespace std; int main() { // criteria bool has_upper_letter = false; bool has_lower_letter = false; bool has_digits_letter = false; bool has_approved_length = false; bool storng_password = false; // password input string input_password = "XmkA78Ji"; // check password has_approved_length = input_password.length() >= 8 ? true : false; if (has_approved_length) { for (size_t i = 0; i < input_password.length(); i++) { if (isupper(input_password[i]) && has_upper_letter == false) has_upper_letter = true; else if (islower(input_password[i]) && has_lower_letter == false) has_lower_letter = true; else if (isdigit(input_password[i]) && has_digits_letter == false) has_digits_letter = true; // handle all valid if (has_upper_letter && has_lower_letter && has_digits_letter && has_approved_length) { storng_password = true; break; } } // displaying error if (storng_password) cout << "Password is strong\n"; else { cout << "Password is week\n"; if (!has_upper_letter) cout << "You must have one upper case letter\n"; if (!has_lower_letter) cout << "You must have one lower case letter\n"; if (!has_digits_letter) cout << "You must have one digits case letter\n"; } } else cout << "You must have 8 digits lenght\n"; return 0; }
code/string_algorithms/src/password_strength_checker/pw_checker.cs
using System; using System.Linq; /* * part of cosmos from opengenus foundation * */ namespace password_strength_check { class Program { static bool chk_strength(string password) { return (password.Length > 8 && password.Any(ch => !char.IsLetterOrDigit(ch)) && password.Any(char.IsDigit) && password.Any(char.IsUpper)); } static void Main(string[] args) { string passwd = "Gurkirat1337"; if (chk_strength(passwd)) { Console.WriteLine("Strong!!!"); } else { Console.WriteLine("Weak :("); } Console.ReadKey(); } } }
code/string_algorithms/src/password_strength_checker/pw_checker.java
public class Password { public static void main(String[] args) { // password to check String password = "XmkA78Ji"; System.out.println(checkPassword(password)); } public static boolean checkPassword(String password) { boolean hasUpperLetter = false; boolean hasLowerLetter = false; boolean hasDigit = false; final int MIN_LENGTH = 8; // the minimum length of the password for (int i = 0; i < password.length(); i++) { if (Character.isUpperCase(password.charAt(i))) hasUpperLetter = true; if (Character.isLowerCase(password.charAt(i))) hasLowerLetter = true; if (Character.isDigit(password.charAt(i))) hasDigit = true; } if(password.length() < MIN_LENGTH) System.out.println("The password is to short"); if(!hasUpperLetter) System.out.println("The password doesn't have a upper case letter"); if(!hasLowerLetter) System.out.println("The password doesn't have a lower case letter"); if(!hasDigit) System.out.println("The password doesn't have a digit"); return (hasUpperLetter && hasLowerLetter && hasDigit && password.length() >= MIN_LENGTH); } }
code/string_algorithms/src/password_strength_checker/pw_checker.js
function scorePassword(pass) { var score = 0; if (!pass) return score; // award every unique letter until 5 repetitions var letters = new Object(); for (var i = 0; i < pass.length; i++) { letters[pass[i]] = (letters[pass[i]] || 0) + 1; score += 5.0 / letters[pass[i]]; } // bonus points for mixing it up var variations = { digits: /\d/.test(pass), lower: /[a-z]/.test(pass), upper: /[A-Z]/.test(pass), nonWords: /\W/.test(pass) }; variationCount = 0; for (var check in variations) { variationCount += variations[check] == true ? 1 : 0; } score += (variationCount - 1) * 10; return parseInt(score); } function checkPassStrength(pass) { var score = scorePassword(pass); if (score > 80) return "strong"; if (score > 60) return "good"; if (score >= 30) return "weak"; return ""; }
code/string_algorithms/src/password_strength_checker/pw_checker.py
# coding=utf-8 # Author: Vitor Ribeiro # This a program to check the security of passwords. # Passwords must be at least 8 characters long. # Passwords must contain at least one uppercase letter and one number. import re, pyperclip # First you need to copy your password to the clipboard, the program will do the rest. password = pyperclip.paste() eightLettersRegex = re.compile(r"\S{8,}") oneUppercaseRegex = re.compile(r"[A-Z]") oneNumberRegex = re.compile(r"\d") check = { eightLettersRegex: "Your password must be 8 letters", oneUppercaseRegex: "Your password must have at least one uppercase Letter.", oneNumberRegex: "Your password must have at least one number.", } print("Analyzing your password.") count = 1 for regex, msg in check.items(): mo = regex.search(password) if mo == None: print(msg) break if count == len(check): print("Good! Your password is strong enough!") count += 1 print("End.")
code/string_algorithms/src/rabin_karp_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/rabin_karp_algorithm/rabinKarp.cpp
typedef long long ll; const ll MOD = 1e9 + 7; const int base = 27; int n; ll h[ms], p[ms]; string s; ll getkey(int l, int r){ // (l, r) int res = h[r]; if(l > 0) res = ((res - p[r - l + 1] * h[l-1]) % MOD + MOD) % MOD; return res; } void build(){ p[0] = 1; h[0] = s[0]; for(int i = 1; i < n; ++i){ p[i] = (p[i-1] * base) % MOD; h[i] = ((h[i-1] * base) + s[i]) % MOD; } }
code/string_algorithms/src/rabin_karp_algorithm/rabin_karp.c
/* * Part of Cosmos by OpenGenus Foundation * Rabin-Karp is a linear time pattern finding * algorithm. */ #include <stdio.h> #include <string.h> #define d 256 /* Base (assuming characters are from ascii set) */ /* * Return 1, if strings match else 0 */ int is_str_equal(char str1[], char str2[], int txt_shift, int len) { int i; for (i = 0; i < len; i++) if (str1[i] != str2[txt_shift+i]) return (0); return (1); } /* * Main search algorithm function * Search algorithm taken from CLRS book */ void rabin_karp_search(char pat[], char txt[], int q) { int n = strlen(txt); int m = strlen(pat); int p = 0; /* hash value for pattern */ int t = 0; /* hash value for text */ int h = 1; int i,s; /* Precompute constant h = d^(m-1)(mod q) * do not use ^ for power as without modulo, * number can get really large. Use loop * h is going to be used multiple times, so precompute it. */ for (i = 0; i < m-1; i++) h = (h*d) % q; /* * Preprocessing: * Calculate hash(p) of complete search pattern(pat[0...m-1]) * Calculate hash(t) of substring text[0...m-1] */ for (i = 0; i < m; i++) { p = (d*p + pat[i]) % q; t = (d*t + txt[i]) % q; } /* Matching */ for (s = 0; s < n-m; s++) { if ((p == t) && (is_str_equal(pat, txt, s, m))) printf("String found at location: %d\n", s+1); if (s < n-m) { t = (d*(t-txt[s]*h) + txt[s+m]) % q; /* Take care of -ve mod values (add q) */ if (t < 0) t += q; } } } /* * Test Code: Main function to test the algorithm */ int main(void) { char txt[1000], pat[100]; int txt_len, pat_len; int q = 1001; //A big enough prime modulus /* Get user inputs */ printf("Enter test string: "); fgets(txt, sizeof(txt), stdin); printf("Enter pattern to find: "); fgets(pat, sizeof(pat), stdin); /* Calculate string lengths */ txt_len = strlen(txt); pat_len = strlen(pat); /* fgets also gives '\n', so remove it from input strings */ if (txt[txt_len-1] == '\n') txt[txt_len-1] = '\0'; if (pat[pat_len-1] == '\n') pat[pat_len-1] = '\0'; rabin_karp_search(pat, txt, q); return (0); }
code/string_algorithms/src/rabin_karp_algorithm/rabin_karp.java
// Following program is a Java implementation // of Rabin Karp Algorithm given in the CLRS book // Part of Cosmos by OpenGenus Foundation public class RabinKarp { // d is the number of characters in input alphabet public final static int d = 256; /* pat -> pattern txt -> text q -> A prime number */ static void search(String pat, String txt, int q) { int M = pat.length(); int N = txt.length(); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be "pow(d, M-1)%q" for (i = 0; i < M-1; i++) h = (h*d)%q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d*p + pat.charAt(i))%q; t = (d*t + txt.charAt(i))%q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters on by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt.charAt(i+j) != pat.charAt(j)) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) System.out.println("Pattern found at index " + i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver program to test above function */ public static void main(String[] args) { String txt = "Welcome to HackOctoberFest OpenGenus cosmos"; String pat = "cosmos"; int q = 101; // A prime number search(pat, txt, q); } }
code/string_algorithms/src/rabin_karp_algorithm/rabin_karp.py
# Rabin Karp Algorithm in python using hash values # d is the number of characters in input alphabet d = 2560 def search(pat, txt, q): M = len(pat) N = len(txt) i = 0 j = 0 p = 0 t = 0 h = 1 for i in range(M - 1): h = (h * d) % q for i in range(M): p = (d * p + ord(pat[i])) % q t = (d * t + ord(txt[i])) % q for i in range(N - M + 1): if p == t: for j in range(M): if txt[i + j] != pat[j]: break j += 1 if j == M: print("Pattern found at index " + str(i)) if i < N - M: t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q if t < 0: t = t + q # Driver program to test the above function txt = "ALL WORLDS IS A STAGE AND ALL OF US ARE A PART OF THE PLAY" pat = "ALL" q = 101 # A prime number search(pat, txt, q)
code/string_algorithms/src/remove_dups/remove_dumps.py
# Part of Cosmos by OpenGenus Foundation def remove_dups(string): res = string[0] for ch in string: if res[-1] != ch: res += ch return res input_string = input("Enter string: ") res_str = remove_dups(input_string) print("Resultant string: ", res_str)
code/string_algorithms/src/remove_dups/remove_dups.c
#include <stdio.h> /* Part of Cosmos by OpenGenus Foundation */ void remove_dups(char *ptr_str) { char *str_temp = ptr_str + 1; while (*str_temp != '\0') { if (*ptr_str != *str_temp) { ptr_str++; *ptr_str = *str_temp; } str_temp++; } ptr_str++; *ptr_str = '\0'; } int main() { char str[256]; printf("Enter string: "); fgets(str, 256, stdin); remove_dups(str); printf("Resultant string: %s\n", str); return (0); }
code/string_algorithms/src/remove_dups/remove_dups.cpp
#include <iostream> //Part of Cosmos by OpenGenus Foundation void removeDups(std::string &str) { std::string resStr; resStr.push_back(str.front()); for (std::string::iterator it = str.begin() + 1; it != str.end(); ++it) if (*it != resStr.back()) resStr.push_back(*it); std::swap(str, resStr); } int main() { std::string str; std::cout << "Enter string: " << std::endl; std::getline(std::cin, str); removeDups(str); std::cout << "Resultant string: " << str << std::endl; return 0; }
code/string_algorithms/src/remove_dups/remove_dups.js
const removeDups = str => [...str].filter((c, i) => c !== str[i + 1]).join(""); console.log(removeDups("lol")); console.log(removeDups("aabbccdd")); console.log(removeDups("llllllllllloooooooooooooolllllllllll"));
code/string_algorithms/src/remove_dups/remove_dups.rs
fn remove_dup(string: &str) -> String { let mut chars: Vec<char> = string.chars().collect(); chars.dedup(); chars .iter() .map(|c| c.to_string()) .collect::<Vec<String>>() .join("") } // rustc --test remove_dups.rs // ./remove_dups OR remove_dups.exe #[test] fn simple_test() { assert_eq!("abcd", remove_dup("abbcccdddd")); assert_eq!( "lol", remove_dup("llllllloooooooooooooooooolllllllllllllll") ); }
code/string_algorithms/src/reverse_word_string/reverse_word_string.cpp
// Reverse the words in a given string #include <algorithm> #include <cstdlib> #include <cstring> #include <iostream> #include <vector> std::vector<std::string> reverseWords(std::string s) { std::string temp; int c = 1; temp.resize(s.length()); for (char ch : s) { if (isspace(ch)) c++; } std::vector<std::string> str(c); int k = 0, ind = 0; for (int i = 0; i < s.length(); ++i) { if (!isspace(s[i])) { temp[k] = (s[i]); k++; } if ((isspace(s[i])) || i == s.length() - 1) { str[ind] = temp; // std::cout<<"temp is :"<<temp; temp.clear(); temp.resize(s.length()); ind++; k = 0; } } std::reverse(str.begin(), str.end()); return str; } int main() { std::string s; std::cout << "Enter the sentence : "; getline(std::cin, s); std::cout << "After Reversal of Words in String : \n"; std::vector<std::string> str = reverseWords(s); for (std::string s : str) std::cout << s << " "; return 0; } /*Sample Input-Output Enter the sentence : I still know what you did last summer After Reversal of Words in String : summer last did you what know still I */ // summer last did you what know still I // summer last did you what know still I
code/string_algorithms/src/reverse_word_string/reverse_word_string.js
function reverseString(string) { const reversedString = string.split(' ').reverse().join(' '); console.log(reversedString); } reverseString('I know what you did last summer'); // summer last did you what know I reverseString('OpenGenus cosmos'); // cosmos OpenGenus
code/string_algorithms/src/reverse_word_string/reverse_word_string.py
# Reversing a string in Python s = input("Enter a string: ") s1 = "" m = list(s) m.append(" ") l = [] for i in range(len(m)): if m[i] != " ": s1 += m[i] else: l.append(s1) s1 = "" print("The Reversed String: ", *l[::-1]) # INPUT # Enter a string: Code is Life # # OUTPUT: # The Reversed String: Life is Code
code/string_algorithms/src/reverse_word_string/reverse_word_string.rs
use std::io::*; fn reverse_words(words: String) -> Vec<String> { words .split_whitespace() .map(|s| s.to_string()) .rev() .collect() } fn main() { print!("Enter the sentence: "); stdout().flush().unwrap(); let mut sentence = String::new(); stdin() .read_line(&mut sentence) .expect("Cannot read user input"); let result = reverse_words(sentence); println!("{}", result.join(" ")); }
code/string_algorithms/src/string_matching/NaiveStringmatching.py
def naive(txt,wrd): lt=len(txt) #length of the string lw=len(wrd) #length of the substring(pattern) for i in range(lt-lw+1): j=0 while(j<lw): if txt[i+j]==wrd[j]: j+=1 else: break else: print('found at position',i)
code/string_algorithms/src/suffix_array/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/suffix_array/suffix_array.java
import java.util.Arrays; public class SuffixArray { public static void main(String[] args) { System.out.println(Arrays.toString(suffixArray("Hello world"))); } public static String[] suffixArray(String word) { String[] suffix = new String[word.length() + 1]; String tmp = "$"; for (int i = suffix.length - 1; i > 0; i--) { suffix[i] = tmp; tmp = word.charAt(i - 1) + tmp; } suffix[0] = tmp; return suffix; } }
code/string_algorithms/src/sum_of_numbers_string/sum_of_numbers_string.py
# ADDING ALL NUMBERS IN A STRING. st = input("Enter a string: ") a = "" total = 0 for i in st: if i.isdigit(): a += i else: total += int(a) a = "0" print(total + int(a)) # INPUT: # Enter a string: 567hdon2 # OUTPUT: # 569
code/string_algorithms/src/trie_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/trie_pattern_search/trie_pattern_search.cpp
#include <iostream> #include <string> #include <stdlib.h> #include <vector> #define alphas 26 using namespace std; typedef struct Node { Node *child[alphas]; int leaf; }trieNode; trieNode* getNode() { trieNode *t = new trieNode; if (t) { for (int i = 0; i < alphas; i++) t->child[i] = NULL; t->leaf = 0; } return t; } void insert(trieNode *root, string s) { trieNode *head = root; int len = s.length(); for (int i = 0; i < len; i++) { if (head->child[s[i] - 'a'] == NULL) head->child[s[i] - 'a'] = getNode(); head = head->child[s[i] - 'a']; } head->leaf = 1; } void walk(trieNode *root) { trieNode *head = root; for (int i = 0; i < alphas; i++) if (head->child[i] != NULL) { cout << char(i + 'a') << " "; walk(head->child[i]); } } bool noChildren(trieNode *root) { trieNode *head = root; for (int i = 0; i < 26; i++) if (head->child[i]) return false; return true; } bool notLeaf(trieNode *root) { if (root->leaf == 1) return false; return true; } bool deletes(trieNode *root, string s, int l, int len) { if (root) { if (l == len) { root->leaf = 0; if (noChildren(root)) return true; return false; } else { int index = s[l] - 'a'; if (deletes(root->child[index], s, l + 1, len)) { free(root->child[index]); root->child[index] = NULL; return notLeaf(root) && noChildren(root); } } } return false; } int main() { int n; cin >> n; vector<string> str; string s; for (int i = 0; i < n; i++) { cin >> s; str.push_back(s); } trieNode *root = getNode(); for (int i = 0; i < n; i++) insert(root, str[i]); walk(root); cout << endl; cin >> s; deletes(root, s, 0, n); walk(root); return 0; }
code/string_algorithms/src/z_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/z_algorithm/z_algorithm.cpp
#include <string> #include <iostream> void Zalgo(std::string s, std::string pattern) { using namespace std; string k = pattern + "&" + s; size_t Z[k.length()]; //Z-array for storing the length of the longest substring //starting from s[i] which is also a prefix of s[0..n-1] size_t l = 0, r = 0; for (size_t i = 1; i < k.length(); i++) { if (i > r) { l = i; r = i; while (r < k.length() && k[r] == k[r - l]) r++; Z[i] = r - l; r--; } else { int p = i - l; if (Z[p] < r - i + 1) Z[i] = Z[p]; else { l = i; while (r < k.length() && k[r] == k[r - l]) r++; Z[i] = r - l; r--; } } } for (size_t i = 1; i < k.length(); i++) if (Z[i] == pattern.length()) cout << "Found Pattern at " << i - pattern.length() - 1 << endl; } int main() { using namespace std; string s = "atababatggagabagt"; //original string string pattern = "aba"; //pattern to be searched in string Zalgo(s, pattern); return 0; } /*Output: * Found Pattern at 2 * Found Pattern at 4 * Found Pattern at 12 */
code/string_algorithms/src/z_algorithm/z_algorithm.py
def getZarr(str, Z): n = len(str) Left = 0 Right = 0 for i in range(1, n): if i > Right: Left = i Right = i while Right < n and str[Right - Left] == str[Right]: Right += 1 Z[i] = Right - Left Right -= 1 else: k = i - Left if Z[k] < Right - i + 1: Z[i] = Z[k] else: Left = i while Right < n and str[Right - Left] == str[Right]: Right += 1 Z[i] = Right - Left Right -= 1 def search(text, pattern): concat = pattern + "$" + text size = len(concat) Z = [0] * size getZarr(concat, Z) for i in range(0, size): if Z[i] == len(pattern): print("Pattern found at " + str(i - len(pattern))) text = "namanchamanbomanamansanam" pattern = "aman" search(text, pattern) """ Output Pattern found at 2 Pattern found at 8 Pattern found at 17 """
code/string_algorithms/src/z_algorithm/z_algorithm_z_array.cpp
/* * Complexity = O(length of string) * s = aaabaab => z[] = {-1,2,1,0,2,1,0} * s = aaaaa => z[] = {-1,4,3,2,1} * s = abacaba => z[] = {-1,0,1,0,3,0,1} * Part of Cosmos by OpenGenus Foundation */ #include <iostream> using namespace std; #define mod 1000000007 #define all(v) v.begin(), v.end() #define rep(i, a, b) for (i = (ll)a; i < (ll)b; i++) #define revrep(i, a, b) for (i = (ll)a; i >= (ll)b; i--) #define strep(it, v) for (it = v.begin(); it != v.end_(); ++it) #define ii pair<ll, ll> #define MP make_pair #define pb push_back #define f first #define se second #define ll long long int #define vi vector<ll> ll modexp(ll a, ll b) { ll res = 1; while (b > 0) { if (b & 1) res = (res * a); a = (a * a); b /= 2; } return res; } #define rs resize long long readLI() { register char c; for (c = getchar(); !(c >= '0' && c <= '9'); c = getchar()) ; register long long a = c - '0'; for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) a = (a << 3) + (a << 1) + c - '0'; return a; } const int N = 100009; string a; ll i, z[N]; void z_function(string s) { ll l = 0, r = 0, n = s.length(); rep(i, 1, n){ if (i <= r) z[i] = min(r - i + 1, z[i - l]); while (i + z[i] < n and s[z[i]] == s[i + z[i]]) z[i]++; if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } } int main() { std::ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> a; z[0] = -1; //Not possible of zero length z_function(a); rep(i, 0, a.length()) cout << z[i] << " "; return 0; }
code/string_algorithms/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/string_algorithms/test/test_naive_pattern_search.cpp
/** * @file test_naive_pattern_search.cpp * @author zafar hussain ([email protected]) * @brief test naive_pattern_search.cpp * @version 0.1 * @date 2022-10-16 * * @copyright Copyright (c) 2022 * */ #include <assert.h> #include "./../src/naive_pattern_search/naive_pattern_search.cpp" int main() { assert(search("z", "const char *txt") == false); assert(search("", "const char *txt") == false); assert(search("xt", "") == false); assert(search("xt", "const char *txt") == 13); assert(search("*", "const char *txt") == 11); assert(search("c", "const char *txt") == 0); assert(search(" c", "const char *txt") == 5); assert(search("t ", "const char *txt") == 4); return 0; }
code/theory_of_computation/src/deterministic_finite_automaton/dfa.cpp
#include "dfa.hh" #include <stdlib.h> #include <string.h> using namespace std; void dfa_makeNextTransition(dfa* dfa, char symbol) { int transitionID; DFAState* pCurrentState = dfa->states[dfa->currentStateID]; for (transitionID = 0; transitionID < pCurrentState->numberOfTransitions; transitionID++) { if (pCurrentState->transitions[transitionID].condition(symbol)) { dfa->currentStateID = pCurrentState->transitions[transitionID].toStateID; return; } } dfa->currentStateID = pCurrentState->defaultToStateID; } void dfa_addState(dfa* pDFA, dfaState* newState) { newState->id = pDFA->noOfStates; pDFA->states[pDFA->noOfStates] = newState; pDFA->noOfStates++; } void dfa_addTransition(DFA* dfa, int fromStateID, int(*condition)(char), int toStateID) { DFAState* state = dfa->states[fromStateID]; state->transitions[state->noOfTransitions].condition = condition; state->transitions[state->noOfTransitions].toStateID = toStateID; state->noOfTransitions++; } dfaState* dfa_createState(bool actionable, std::string actionName) { dfaState* newState = (dfaState*)malloc(sizeof(dfaState)); strcpy(newState->actionName, actionName); newState->defaultToStateID = -1; newState->actionable = actionable; newState->id = -1; newState->noOfTransitions = 0; return newState; } dfa* dfa_createDFA() { dfa* dfa = (dfa*)malloc(sizeof(dfa)); dfa->noOfStates = 0; dfa->startStateID = -1; dfa->currentStateID = -1; return dfa; } void dfa_reset(dfa* dfa) { dfa->currentStateID = dfa->startStateID; }
code/theory_of_computation/src/deterministic_finite_automaton/dfa.hh
#ifndef DFA_H #define DFA_H #endif #define MAX_TRANSITION 50 #define MAX_STATES 100 using namespace std; typedef struct { int (*condition)(char); int stateId; } dfaTransition; typedef struct { int id; bool actionable; int noOfTransitions; std::string actionName; dfaTransition transitions[MAX_TRANSITIONS]; int defaultToStateId; } dfaState; typedef struct { int startStateId; int currentStateId; int noOfStates; dfaState* states[MAX_STATES]; } dfa; dfa* dfa_createDFA(); void dfa_reset(dfa* dfa); //makes the dfa ready for consumption. i.e. sets the current state to start state. void dfa_makeNextTransition(dfa* dfa, char c); void dfa_addState(dfa* pDFA, dfaState* newState); dfaState* dfa_createState(int hasAction, char* actionName); void dfa_addTransition(dfa* dfa, int fromStateID, int(*condition)(char), int toStateID);
code/theory_of_computation/src/deterministic_finite_automaton/dfa.py
class DFA(object): """Class for Deterministic Finite Atomata""" def __init__(self, transitions, start, accepting): self.start = start self.accepting = accepting self.transitions = transitions def accepts(self, word): curr_state = self.start for char in word: try: curr_state = self.transitions[curr_state][char] except KeyError: print( "WARNING: Missing entry in transition assumed leading to dead state" ) return False return curr_state in self.accepting def minimize(self): actions = set() for state, state_transitions in self.transitions.items(): actions.update(state_transitions.keys()) reachable_states = set() new_states_reached = set([self.start]) while new_states_reached: reachable_states.update(new_states_reached) newer_states_reached = set() while new_states_reached: state = new_states_reached.pop() try: for next_state in self.transitions[state].values(): if next_state not in reachable_states: newer_states_reached.add(next_state) except KeyError: pass new_states_reached = newer_states_reached try: for state in reachable_states: for action in actions: next_state = self.transitions[state][action] except KeyError: reachable_states.add(None) partitions = [set(), set()] partition_number = {} for state in reachable_states.intersection(self.accepting): partitions[0].add(state) partition_number[state] = 0 for state in reachable_states.difference(self.accepting): partitions[1].add(state) partition_number[state] = 1 n_since_change = 0 while n_since_change < len(partitions): i = 0 while i < len(partitions): for action in actions: next_state_partition_numbers = { partition_number[self.transitions[state].get(action)] for state in partitions[i] } if len(next_state_partition_numbers) > 1: n_since_change = 0 new_partition_numbers = {} new_partition_numbers[next_state_partition_numbers.pop()] = i for number in next_state_partition_numbers: new_partition_numbers[number] = len(partitions) partitions.append(set()) partition_copy = set(partitions[i]) partitions[i] = set() for state in partition_copy: number = partition_number[ self.transitions[state].get(action) ] partition_number[state] = new_partition_numbers[number] partitions[number].add(state) else: n_since_change += 1 i += 1 new_states = range(1, len(partitions) + 1) new_transitions = dict([(state, {}) for state in new_states]) new_accepting = [] for state in new_states: old_state = next(iter(partitions[state - 1])) if old_state in self.accepting: new_accepting.append(state) for action in actions: new_transitions[state][action] = ( partition_number[self.transitions[old_state].get(action)] + 1 ) new_start = partition_number[self.start] + 1 new_dfa = DFA( transitions=new_transitions, start=new_start, accepting=new_accepting ) return new_dfa def main(): print("Automata for strings of even length") dfa = DFA( transitions={ 1: {"a": 2, "b": 2}, 2: {"a": 3, "b": 3}, 3: {"a": 4, "b": 4}, 4: {"a": 1, "b": 1}, 5: {"a": 2, "b": 3}, }, start=4, accepting=[2, 4], ) words = ["", "a", "aa", "aaa", "abab"] print() print("Tests for DFA:-") for word in words: print("'{}' accepted? {}".format(word, dfa.accepts(word))) minimized_dfa = dfa.minimize() print() print("Tests for minimized DFA:-") for word in words: print("'{}' accepted? {}".format(word, minimized_dfa.accepts(word))) print() print("Number of states in DFA: ", len(dfa.transitions)) print("Number of states in minimized DFA: ", len(minimized_dfa.transitions)) if __name__ == "__main__": main()
code/theory_of_computation/src/non_deterministic_finite_automata_to_finite_automata/ndfa_to_dfa.cpp
#include <bits/stdc++.h> #define pb push_back using namespace std; const int N=109; int n, m; vector<int> nt[N][N]; int dt[N][N]; vector<int> ds[N]; int tot; void print_dfa() { cout << "\n DFA Table:\n"; cout << "================\n"; cout << "Q\t"; for(int j=0; j<m; j++) { cout << j << "\t"; } cout << endl; for(int i=0; i<tot; i++) { cout << "["; for(int k=0; k < ds[i].size(); k++) cout << ds[i][k]; cout << "]\t"; for(int j=0; j<m; j++) { cout << "["; for(int k=0; k<ds[dt[i][j]].size(); k++) { cout << ds[dt[i][j]][k]; } cout << "]\t"; } cout << endl; } cout << endl; } int main() { n = 4, m = 2; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { int sz; cin >> sz; nt[i][j].resize(sz); } } for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { for(int k=0; k < nt[i][j].size(); k++) { cin >> nt[i][j][k]; } } } queue<int> q; vector<int> v; v.pb(0); q.push(0); ds[tot++] = v; while(!q.empty()) { int top = q.front(); q.pop(); for(int j=0; j<m; j++) { vector<int> cur; for(int i=0; i < ds[top].size(); i++) { for(int k=0; k < nt[ds[top][i]][j].size(); k++) { cur.pb(nt[ds[top][i]][j][k]); } } sort(cur.begin(), cur.end()); cur.resize(unique(cur.begin(), cur.end()) - cur.begin()); int prev = -1; for(int i=0; i<tot; i++) { if(ds[i] == cur) { prev = i; break; } } if(prev == -1) { ds[tot] = cur; q.push(tot); dt[top][j] = tot; tot++; } else { dt[top][j] = prev; } } } print_dfa(); return 0; }
code/theory_of_computation/src/nondeterministic_finite_atomaton/nfa.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <math.h> int row = 0; struct node { int data; struct node* next; char edgetype; }typedef node; node* push(node* first , char edgetype , int data) { node* new_node = (node*)malloc(sizeof(node)); new_node->edgetype = edgetype; new_node->data = data; new_node->next = NULL; if (first==NULL) { first = new_node; return new_node; } first->next = push(first->next,edgetype,data); return first; } int nfa(node** graph, int current, char* input, int* accept, int start) { if (start==(int)strlen(input)) return accept[current]; node* temp = graph[current]; while (temp != NULL) { if (input[start]==temp->edgetype) if (nfa(graph,temp->data,input,accept,start+1==1)) return 1; temp=temp->next; } return 0; } void generate(char** arr, int size, char *a) { if (size==0) { strcpy(arr[row], a); row++; return; } char b0[20] = {'\0'}; char b1[20] = {'\0'}; b0[0] = '0'; b1[0] = '1'; generate((char**)arr, size-1, strcat(b0,a)); generate((char**)arr, size-1, strcat(b1,a)); return; } int main() { int n; int i, j; scanf("%d", &n); node* graph[n+1]; for (i=0;i<n+1;i++) graph[i]=NULL; int accept[n+1]; for (i=0; i<n; i++) { int index,acc,number_nodes; scanf("%d%d%d",&index,&acc,&number_nodes); accept[index]=acc; for (j=0;j<number_nodes;j++) { int node_add; int edge; scanf("%d%d",&edge,&node_add); graph[index] = push(graph[index],'0'+edge,node_add); } } int size = 1, count = 0; if (accept[1]==1) { printf("e\n"); count++; } while (count < 11) { char** arr; int power = pow(2,size); arr = (char**)malloc(power*sizeof(char*)); for (i=0;i<power;i++) arr[i] = (char*)malloc(size*sizeof(char)); char a[20] = {'\0'}; generate((char**)arr,size,a); for (i=0; i<power; i++) { char input[20] = {'\0'}; for (j=0; j<size; j++) { char foo[2]; foo[0] = arr[i][size-1-j]; foo[1] = '\0'; strcat(input,foo); } int result = nfa(graph,1,input,accept,0); if (result==1) { printf("%s\n",input); count++; } if (count==10) return 0; } size++; row=0; } return 0; }
code/theory_of_computation/src/nondeterministic_finite_atomaton/nfa.py
from dfa import ( DFA, ) # located at code/theory_of_computation/src/deterministic_finite_automaton/dfa.py class NFA(object): """Class for Non-deterministic Finite Atomata""" DEAD = -1 def __init__(self, transitions, start, accepting): self.start = start self.accepting = accepting self.transitions = transitions def accepts(self, word, _start=None): if _start is None: curr_state = self.start else: curr_state = _start if len(word) == 0: return curr_state in self.accepting else: try: choices = self.transitions[curr_state][word[0]] for choice in choices: if self.accepts(word[1:], _start=choice): return True return False except KeyError: print( "WARNING: Missing entry in transition assumed leading to dead state" ) return False def determinize(self): states = set(self.transitions.keys()) actions = set() for state, out_transitions in self.transitions.items(): actions.update(out_transitions.keys()) dfa_start = frozenset([self.start]) dfa_states_left = set([dfa_start]) mappings = {dfa_start: 1} dfa_transitions = {} while len(dfa_states_left) > 0: dfa_state = dfa_states_left.pop() dfa_transitions[mappings[dfa_state]] = {} for action in actions: dfa_next_state = set() for nfa_state in dfa_state: try: dfa_next_state.update(self.transitions[nfa_state][action]) except KeyError: pass dfa_next_state = frozenset(dfa_next_state) if dfa_next_state not in mappings: mappings[dfa_next_state] = len(mappings) + 1 dfa_states_left.add(dfa_next_state) dfa_transitions[mappings[dfa_state]][action] = mappings[dfa_next_state] dfa_accepting = [ mappings[dfa_state] for dfa_state in mappings.keys() if not dfa_state.isdisjoint(self.accepting) ] return DFA(transitions=dfa_transitions, start=1, accepting=dfa_accepting) def main(): print("Automata that accepts strings with 'a' as 3rd character from last") nfa = NFA( transitions={ 1: {"a": [1, 2], "b": [1]}, 2: {"a": [3], "b": [3]}, 3: {"a": [4], "b": [4]}, 4: {}, }, start=1, accepting=[4], ) words = ["a", "aa", "aaa", "abab", "abaaab"] print() print("Tests for NFA:-") for word in words: print("{} accepted? {}".format(word, nfa.accepts(word))) print() print("Tests for DFA, obtained by determinizing NFA:-") dfa = nfa.determinize() for word in words: print("'{}' accepted? {}".format(word, dfa.accepts(word))) print() print("Number of states in NFA: ", len(nfa.transitions)) print("Number of states in DFA: ", len(dfa.transitions)) if __name__ == "__main__": main()
code/unclassified/src/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/unclassified/src/add_1_to_no_represented_as_array_of_digit/add_1_to_no_represented_as_array_of_digit.py
# Given a non-negative number represented as an array of digits, add 1 to the number # Ignore the leading zeros and start from the first non-zero digit ar = list(map(int, input("Enter the elements: ").split())) i = 0 while i < len(ar): if ar[i] != 0: break else: i = i + 1 string = "" for j in range(i, len(ar)): string = string + str(ar[j]) k = int(string) + 1 print("The final array: ", *list(str(k))) # INPUT: # Enter the elements: 0 0 8 0 1 2 # OUTPUT: # The final array: 8 0 1 3
code/unclassified/src/add_one_to_number/add_one_to_number.cpp
#include <cstdlib> #include <iostream> #include <vector> // Add 1 to number /* Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is at the head of the list. */ /* Here we are calculating the number of trailing zeroes to the left that we need to exclude while printing the output For example : if the input is 0,0,1,2,3,4 => The output should be 1,2,3,5 and NOT 0,0,1,2,3,5 So, here we are finding the number of continuos 0's in the input that we need to exclude in the output */ std::vector<int> plusOne(std::vector<int> &A) { std::vector<int> A1(A.size()); A1 = A; int c = 0, ind = 0; if (A[0] == 0) { c = 1; while (1) { if (A[ind] + A[ind + 1] == 0) { c++; ind++; } else break; } } // cout<<" C is : " <<c<<"\n"; for (int i = A.size() - 1; i >= 0; --i) { if (A[i] < 9) { A[i]++; if (A1[0] == 0 && A.size() > 1) return std::vector<int>(A.begin() + c, A.end()); else return A; } A[i] = 0; } std::vector<int> result(A.size() + 1); result[0] = 1; return result; } int main() { int n; std::cout << "Enter the size of the array : "; std::cin >> n; std::vector<int> A(n); std::cout << "Enter the elements of the array :\n"; for (int i = 0; i < n; ++i) std::cin >> A[i]; std::cout << "Sum is : "; std::vector<int> result = plusOne(A); for (int i = 0; i < result.size(); ++i) std::cout << result[i] << " "; return 0; } /* Sample Input - Output: Enter the size of the array : 10 Enter the elements of the array : 0 0 4 5 2 0 9 7 1 2 Sum is : 4 5 2 0 9 7 1 3 Enter the size of the array : 6 Enter the elements of the array : 0 0 1 6 5 2 Sum is : 1 6 5 3 */
code/unclassified/src/array_to_set/arraytoset_iterator.cpp
#include <iostream> #include <set> // This program converts an array to a set in C++ using iterators // See the corresponding article here: https://iq.opengenus.org/convert-array-to-set-cpp/ int main() { int a[] = {4, 11, 5, 3, 1, 6}; std::set<int> s(std::begin(a), std::end(a)); for (int i : s) { std::cout << i << " "; } std::cout << "\n"; return 0; }
code/unclassified/src/autobiographical_numbers/README.md
# Autobiographical Numbers ### Problem Description: Given a string, return "true" if it is an autobiographical number or false otherwise. An Autobiographical Number is a number where each number at a given index represents the number of times it (the index value) appears in the given string. For example: - String s = "1000" -> returns false. s[0] = '1', but 0 appears "three" times in the string - hence it is NOT an autobiographical number. - String s = 302200 -> returns false. s[0] = '3' and 0 appears "three" times in the string, so the zero index is valid. s[1] = '0' and 1 appears "zero" times in the string, so the first index is valid. s[2] = '2' and 2 appears "two" times in the string, so it is valid. s[3] = '2', but 3 appears "one" time in the string, so it is NOT valid. Hence, it returns false. - String s = 2020 -> returns true Because the string contains 2 zeroes, 0 ones, 2 twos, and 0 threes. ### Problem Solution approach: The idea to solve this problem would be: Let's say the input is a string. 1) Make a hash_table, let's call it indexCounter and initialize an integer index to 0. Record indexCounter[index] = convertToInteger(currentChar). Repeat for all chars in the string. the index will be incremented by 1 every repetition. 2) Make another hash table, let's call it eleCounter. This table simply records how many times each element occurs. 3) Loop through each pair of elements present in the indexCounter. Check if the value at indexCounter for that index and the count of elements for that index (from eleCounter) is the same or not. Even if one value mismatches, return false immediately. 4) if we still make it to the end, return true. 5) See the autobiographical_numbers.cpp file for a in-code example (C++).
code/unclassified/src/autobiographical_numbers/autobiographical_numbers.cpp
// Part of OpenGenus Cosmos #include <iostream> #include <string> #include <unordered_map> int main() { std::string s2 = "22535320"; // Input string // string s2 = "72100001000"; // Uncomment this for a "TRUE" answer example. std::unordered_map<int, int> indexCounter; std::unordered_map<int, int> eleCounter; int index = 0; for (char c : s2) { indexCounter[index] = (c - '0'); // c - '0' converts the char to a proper integer. index++; } for (char c : s2) eleCounter[(c - '0')]++; // c - '0' converts the char to a proper integer. for (auto &par : indexCounter) { if (eleCounter[par.first] != par.second) { std::cout << "false" << std::endl; return 0; // return false; } } // return true; std::cout << "true" << std::endl; }
code/unclassified/src/average/average.c
// Part of Cosmos by OpenGenus Foundation // Code written by Adeen Shukla (adeen-s) #include <stdio.h> int main() { int n, tmp = 0, i; double sum = 0.0; printf("Enter the total number of inputs : "); scanf("%d", &n); printf("\nEnter the numbers\n"); for (i = 0; i < n; i++, sum += tmp) { scanf("%d", &tmp); } printf("\nAverage = %2.2f\n", (sum / n)); return (0); }
code/unclassified/src/average/average.cpp
/// Part of Cosmos by OpenGenus Foundation /// Find of average of numbers in an array /// Contributed by: Pranav Gupta (foobar98) /// Modified by: Arnav Borborah (arnavb) #include <iostream> #include <string> #include <sstream> #include <vector> using namespace std; int main() { vector<int> elements; cout << "Enter the numbers you want to find the average of: "; int sum = 0; string input; getline(cin, input); istringstream is(input); for (int element; is >> element;) // Read numbers until the user enters a newline { elements.push_back(element); sum += element; } double avg = static_cast<double>(sum) / elements.size(); cout << "Average of numbers: " << avg << endl; }
code/unclassified/src/average/average.cs
/* Takes values from CLI Arguments How to run $ mcs average.cs $ mono average.exe 1 2 3 4 5 */ using System; namespace Average { class Program { public static void Main(string[] argv) { float sum = 0.0f; float n; foreach(string num in argv) { sum += float.Parse(num); } Console.WriteLine(sum / argv.Length); } } }
code/unclassified/src/average/average.erl
% Part of Cosmos by OpenGenus Foundation % Finds the average of an array of numbers. % Contributed by: Michele Riva (micheleriva) -module(average). -export([average/1]). average(List) -> lists:sum(List) / length(List).
code/unclassified/src/average/average.es6.js
// Part of Cosmos by OpenGenus Foundation // Find of average of numbers in an array // Contributed by: Michele Riva (micheleriva) export const average = numbers => { const sum = numbers.reduce((a, b) => a + b, 0); return sum / numbers.length; }; /* Test */ const n = [10, 20, 30, 40]; average(n); // => 25
code/unclassified/src/average/average.ex
## Part of Cosmos by OpenGenus Foundation ## Find of average of numbers in an array ## Contributed by: Michele Riva (micheleriva) defmodule Average do def get(numbers) do Enum.sum(numbers) / length(numbers) end end # Test n = [10, 20, 30, 40] IO.puts Average.get(n) #=> 25
code/unclassified/src/average/average.go
/// Part of Cosmos by OpenGenus Foundation /// Find of average of numbers in an array /// Contributed by: Guilherme Lucas (guilhermeslucas) package main import "fmt" func average(array []float32) float32 { var sum float32; sum = 0.0 for i := 0; i < len(array); i++ { sum = sum + array[i] } return sum / float32(len(array)) } func main() { var n int var input float32 array := make([]float32, n) fmt.Println("How many elements do you want to input?") fmt.Scanf("%d", &n) for i := 0; i < n; i++ { fmt.Scanf("%f", &input) array = append(array, input) } fmt.Println("The median is: ", average(array)) }
code/unclassified/src/average/average.java
import java.util.*; // Part of Cosmos by OpenGenus Foundation class Average { /** * @param arr array of integers to get the average of. * @param n number of elements. * @return the average calculated as sum(arr)/n */ static double getAverage(ArrayList<Integer> arr) { if (arr.isEmpty()) { return 0.0; } double sum = 0; for(int value : arr) { sum += value; } return sum / arr.size(); } public static void main(String args[]) { ArrayList<Integer> arr = new ArrayList<Integer>(); Scanner scan = new Scanner(System.in); System.out.println("Enter elements in array (-1)exit "); int n; while ((n = scan.nextInt()) != -1) arr.add(n); System.out.printf("Average = %2.2f\n",getAverage(arr)); } }
code/unclassified/src/average/average.js
/* Part of Cosmos by OpenGenus Foundation */ // finds the average of an array of numbers. //Using map function function getAverage(numbers) { var sum = 0; numbers.map(function(number) { sum += number; }); return sum / numbers.length; } nums = [10, 20, 30, 40, 50]; console.log(getAverage(nums));
code/unclassified/src/average/average.nims
## Returns average of given sequence of floats proc average(numbers: seq[float]): float = for num in numbers: result += num result / numbers.len.float ## Test let numList: seq[float] = @[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] average(numList).echo # 5.5
code/unclassified/src/average/average.php
<?php // finds the average of an array of numbers. function getAverage($numbers) { $sum = 0; for($i=0; $i<count($numbers); $i++) { $sum += $numbers[$i]; } return ($sum / count($numbers)); } echo getAverage([10,20,30,40,50]); ?>
code/unclassified/src/average/average.py
## Part of Cosmos by OpenGenus Foundation ## Find of average of numbers in an array ## Contributed by: Pranav Gupta (foobar98) n = int(input("Enter no. of elements: ")) a = [] # empty list for i in range(0, n): # every number in a new line x = int(input("Enter number: ")) a.append(x) avg = sum(a) / n print("Average of numbers in list: " + str(round(avg, 2)))
code/unclassified/src/average/average.rb
# Part of Cosmos by OpenGenus Foundation def sum(*nums) nums.inject(&:+).fdiv(nums.size) end
code/unclassified/src/average/average.rs
// Part of Cosmos by OpenGenus Foundation fn average(arr :&Vec<i32>) -> i32 { let mut sum = 0; for n in arr.iter() { sum += *n; } sum / arr.len() as i32 } fn main() { let vec = vec![1 , 2, 3, 4, 5, 6, 7, 8, 9, 10]; print!("{}", average(&vec)); }
code/unclassified/src/average/average.scala
object Average extends App{ def average(num:Array[Double]):Double = { val sum:Double = num.foldLeft(0.0){(a, b) => a + b} sum / num.size } val arr:Array[Double] = Array(1, 2, 3, 4, 5) println(average(arr)) }
code/unclassified/src/average/average.sh
#!/bin/bash echo -e "please press 'SPACEBAR' and not 'ENTER' after each input\n" read -p "Enter The numbers " NM #Here 'sum' is the sum of numbers 'len' is the length of the integer string inserted 'count' is the count of numbers in integer string sum=0 len=`echo ${#NM}` i=1 size=0 count=0 ########################################################################################################## #A loop to read each number add it to 'sum' and increment count simultaneously while [ "$size" -lt "$len" ] do a=`echo "$NM"|cut -d " " -f $i` if [[ -z "$a" ]] then if [[ "$i" -eq 1 ]] then echo -e "ENter The numbers again no element on position $i\n" else i=$[$i+1] size=$[$size+1] fi else sum=$[$sum+$a] count=$[$count+1] la=`echo "${#a}"` size=$[$size+$la] i=$[$i+1] fi done ########################################################################################################## #calculate the average and print the result res=`echo "scale=2;$sum/$count"|bc` echo -e "Avergae is $res\n" ##########################################################################################################
code/unclassified/src/average/average.swift
import Foundation let nums = [10.0,20,30,40,50] let average = nums.reduce(0.0, +) / Double(nums.count) print(average)
code/unclassified/src/average/readme.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter # Average The aim is to find the average of n numbers. The value n and the elements are taken as input from the user --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/unclassified/src/biggest_of_n_numbers/biggest_of_n.js
// Part of cosmos from opengenus foundation const biggestOfN = array => Math.max.apply(null, array); console.log(biggestOfN([10, 0, -1, 100, 20])); console.log(biggestOfN([9090, 0, -100, 1, 20]));
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.c
#include <stdio.h> int main() { int n , max , tmp; printf("Enter numbers of elements : "); scanf("%d",&n); printf("Enter numbers\n"); scanf("%d",&tmp); max = tmp; for(int i=0; i<n-1; i++) { scanf("%d",&tmp); if (max<tmp) { max = tmp; } } printf("Maximum is %d\n",max); return 0; }
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.cpp
// Part of cosmos from opengenus foundation #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> arr; std::cout << "Keep entering numbers (EOF to stop): "; for (int num; std::cin >> num;) arr.push_back(num); sort(arr.begin(), arr.end()); std::cout << "biggest number : " << arr.back(); }
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.cs
namespace BiggestOfNumbers { public class BiggestOfNumbers { public void main() { Console.WriteLine("Enter numbers of elements : "); int n = Console.ReadLine(); Console.WriteLine("Enter numbers : "); int tmp = Console.ReadLine(); int max = tmp; for(int i=0; i<n-1; i++) { tmp = Console.ReadLine(); if (max<tmp) { max = tmp; } } Console.WriteLine("Maximum is {0}",max); } } }