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)
... |
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",... |
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(+... |
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�... |
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
... |
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"
el... |
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... |
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");... |
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 {
retur... |
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 fa... |
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 ... |
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 str... |
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 isPalindromeItera... |
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 palindr... |
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".isPalindr... |
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(isPal... |
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 ... |
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 vari... |
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_pang... |
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 Strin... |
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 t... |
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.... |
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"); // shou... |
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 && !$alpha... |
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... |
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) -... |
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("Tot... |
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;
bo... |
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.IsD... |
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 ... |
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 mixin... |
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 res... |
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[... |
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, ... |
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 ... |
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 + o... |
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... |
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... |
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()... |
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... |
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... |
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_lin... |
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 -... |
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->chi... |
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]
s... |
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:
... |
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)... |
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() {
... |
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 (pCurre... |
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];
... |
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:
... |
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 <... |
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->edg... |
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
... |
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 ... |
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 c... |
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) {
... |
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 ... |
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::uno... |
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 += tm... |
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 <<... |
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... |
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]
}
... |
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(... |
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
pr... |
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
#############################... |
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... |
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;
}
}
... |
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 << "... |
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 ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.