filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.java | import java.util.Scanner;
public class BiggestOfNNumbers
{
public static void main(String[] args)
{
Scanner data = new Scanner(System.in);
System.out.print("Enter numbers of elements");
int n = data.nextInt();
System.out.println("Enter " + n + " numbers");
... |
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.nims | ## Find Biggest of given sequence of integers using built in proc
proc biggestNum(numbers: seq[int]): int =
max(numbers)
## Find Biggest of given sequence of integers by iteration
proc biggestNumNative(numbers: seq[int]): int =
for num in numbers:
if num > result:
result = num
## Tests
biggestNum(@[3, 2... |
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.py | elements = []
n = int(input("Enter number of elements:"))
for i in range(0, n):
elements.append(int(input("Enter element:")))
elements.sort()
print("Largest element is : ", elements[n - 1])
|
code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers2.cpp | #include <iostream>
using namespace std;
int main()
{
int n, max, tmp;
cout << "Enter numbers of elements : ";
cin >> n;
cout << "Enter numbers\n";
cin >> tmp;
max = tmp;
for (int i = 0; i < n - 1; i++)
{
cin >> tmp;
if (max < tmp)
max = tmp;
}
cout <... |
code/unclassified/src/biggest_of_n_numbers/readme.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Biggest Of n numbers
The aim is to find the maximum numbers among the n given numbers. The value n and the elements are taken as input from the user.
---
<p align="center">
A massive collaborative effort by <a... |
code/unclassified/src/biggest_suffix/biggest_suffix.c | #include <stdio.h>
#include <string.h>
int equality(char *s1, char *s2, int x)
{
if(strcmp(s1 + strlen(s1) - x, s2 + strlen(s2) - x) == 0)
return 1;
return 0;
}
char *biggest_suffix(char *s1, char *s2)
{
int i;
int shortest_string; /* Finds the number of characters that needs to traversed to check smallest subs... |
code/unclassified/src/biggest_suffix/biggest_suffix.js | /**
*
* @param {string} longest One of the two strings for biggest common suffix
* @param {string} shortest One of the two strings for biggest common suffix. It serves terminating condition for algorithm
* @param {number} accumulator counter for common characters found
* @returns {number} counter for no of charact... |
code/unclassified/src/biggest_suffix/readme.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Biggest Suffix
The aim is to find the biggest suffix of two strings where the strings are taken as input from the user.
# Algorithm
After taking both the strings as input we find the length of the smaller stri... |
code/unclassified/src/fifteen_puzzle/fifteen.c | /**
* fifteen.c
*
* Implements Game of Fifteen (generalized to d x d).
*
* Usage: fifteen d
*
* whereby the board's dimensions are to be d x d,
* where d must be in [DIM_MIN,DIM_MAX]
*
* Note that usleep is obsolete, but it offers more granularity than
* sleep and is simpler to use than nanosleep; `man uslee... |
code/unclassified/src/fifteen_puzzle/log.txt | 8|7|6
5|4|3
2|1|0
8|7|6
5|4|3
2|0|1
8|7|6
5|0|3
2|4|1
8|7|6
5|3|0
2|4|1
8|7|0
5|3|6
2|4|1
|
code/unclassified/src/fifteen_puzzle/makefile | fifteen: fifteen.c
clang -ggdb3 -O0 -std=c11 -Wall -Werror -o fifteen fifteen.c -lcs50 -lm
clean:
rm -f *.o a.out core fifteen log.txt
|
code/unclassified/src/fifteen_puzzle/readme.md | # Fifteen Puzzle
The 15-puzzle (also called Gem Puzzle, Boss Puzzle, Game of Fifteen, Mystic Square and many others) is a sliding puzzle that consists of a frame of numbered square tiles in random order with one tile missing.
The puzzle also exists in other sizes, particularly the smaller 8-puzzle.
If the size is ... |
code/unclassified/src/flutter_res/README.md | [This Article](https://iq.opengenus.org/getting-started-with-flutter-development/) has been made to put forward and efforts have been made seeing to
the emergence of the new Mobile Technology which is giving equal
competition to the ones that are already existing in the it industry.
This article contains the following ... |
code/unclassified/src/jaccard_similarity/README.md | # Jaccard Similarity Coefficient #
The Jaccard similarity coefficient is a statistic used for comparing the similarity and diversity of sample sets.
The Jaccard coefficient measures similarity between finite sample sets, and is defined as the size of the intersection
divided by the size of the union of the sample sets... |
code/unclassified/src/jaccard_similarity/jaccard.c |
/* A simple C program to create Jaccard’s indices adjusted for differences in species richness across site */
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <float.h>
#define R 524
#define C 46
#define MAX 100
void main()
{
time_t toc;
int M[R][C], B[R][... |
code/unclassified/src/jaccard_similarity/jaccard.java | package org.apache.commons.text.similarity;
import java.util.HashSet;
import java.util.Set;
/**
* Measures the Jaccard similarity (aka Jaccard index) of two sets of character
* sequence. Jaccard similarity is the size of the intersection divided by the
* size of the union of the two sets.
*
* <p>
* For further ... |
code/unclassified/src/jaccard_similarity/jaccard.js | /**
* Calculates union of two given sets
* @param {Set} setA
* @param {Set} setB
*/
const union = (setA, setB) => {
const _union = new Set(setA);
for (let elem of setB) {
_union.add(elem);
}
return _union;
};
/**
* Calculates intersection of two given sets
* @param {Set} setA
* @param {Set} setB
*/... |
code/unclassified/src/jaccard_similarity/jaccard.nims | ## Calculates Jaccard Similarity
proc jaccardSimilarity[T](setA: set[T], setB: set[T]): float =
card(setA * setB) / card(setA + setB)
jaccardSimilarity({0, 1, 2, 5, 6}, {0, 2, 3, 5, 7, 9}).echo
|
code/unclassified/src/jaccard_similarity/jaccard.py | #!/usr/bin/env python
def jaccard_similarity(x, y):
intersection_cardinality = len(set.intersection(*[set(x), set(y)]))
union_cardinality = len(set.union(*[set(x), set(y)]))
return intersection_cardinality / float(union_cardinality)
print(jaccard_similarity([0, 1, 2, 5, 6], [0, 2, 3, 5, 7, 9]))
|
code/unclassified/src/josephus_problem/README.md | # Josephus Problem Algorithm
Josephus Problem is a theoretical Counting Game Problem.
n people stand in a circle and are numbered from 1 to n in clockwise direction.
Starting from 1 in clockwise direction each person kills the k<sup>th</sup> person next to him and this continues till
a single person is left. The t... |
code/unclassified/src/josephus_problem/josephus.c | /*Part of Cosmos by OpenGenus Foundation*/
#include <stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void position()
{
struct node *p,*q;
int n,gap;
printf("Enter no of horses:\n");
scanf("%d",&n);
printf("Enter gap:\n");
scanf("%d",&gap);
p=q=(struct node... |
code/unclassified/src/josephus_problem/josephus.cpp | //Part of Cosmos by OpenGenus Foundation
#include <iostream>
using namespace std;
int josephus(int n, int k)
{
// Returns the safe position of n items
// that have every kth item counted out
// Note that the indice returned is zero-indexed
if (n == 1)
return 0;
return (josephus(n - 1, k) +... |
code/unclassified/src/josephus_problem/josephus.go | package main
import (
"fmt"
"strconv"
)
func safePosition(n int,k int) int {
if n <= 1 {
return 0
}
return (safePosition(n-1, k) + k) % n
}
func main() {
var n int
var k int
fmt.Println("Enter the number of people:")
fmt.Scanf("%d\n", &n)
fmt.Println("Enter the kth value of people getting executed:")
fm... |
code/unclassified/src/josephus_problem/josephus.js | function josephus(n, k) {
// Returns the safe position of n items
// that have every kth item counted out
// Note that the indice returned is zero-indexed
if (n == 1) {
return 0;
}
return (josephus(n - 1, k) + k) % n;
}
function test(n, k, expected) {
const result = josephus(n, k);
if (result == e... |
code/unclassified/src/josephus_problem/josephus.py | def safePos(n, k):
if n == 1:
return 0
return (safePos(n - 1, k) + k) % n
n = int(input("Enter the number of people : "))
k = int(input("Enter the kth value of people getting executed : "))
print(
"The Safe position to stand is", safePos(n, k) + 1
) # Answer is for 1 based indexing
|
code/unclassified/src/krishnamurthy_number/README.md | # What is A Krishnamurthy number?
It's a number whose sum total of the factorials of each digit is equal to the number itself.
## Here's what I mean by that:
### "145" is a **Krishnamurthy** Number because,
#### 1! + 4! + 5! = 1 + 24 + 120 = 145
### "40585" is also a **Krishnamurthy** Number.
#### 4! + 0! + 5! + 8... |
code/unclassified/src/krishnamurthy_number/krishnamurthyNumber.py | # helper function
def factorial(n):
fact = 1
while n != 0:
fact *= n
n -= 1
return fact
def checkKrishnamurthy(n):
sumOfDigits = 0 # will hold sum of FACTORIAL of digits
temp = n
while temp != 0:
# get the factorial of of the last digit of n and add it to sumOfDigit... |
code/unclassified/src/lapindrom_checker/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Lapindrome Checker
The aim is to find if the string is lapindrome or not. The string is taken as input from the user.
Lapindrome is defined as a string which when split in the middle, gives two halves having th... |
code/unclassified/src/lapindrom_checker/lapindrome_checker.cpp | // part of cosmos by opengenus foundation
#include <iostream>
#include <algorithm> // used for sort()
using namespace std;
bool isLapindrome(string str)
{
int mid = str.length() / 2;
int delim = (str.length() % 2) == 0 ? mid : mid + 1;
string first_half = str.substr(0, mid);
string second_half = st... |
code/unclassified/src/lapindrom_checker/lapindrome_checker.py | # part of cosmos by opengenus foundation
def isLapindrome(string):
mid = len(string) // 2
delim = mid
if len(string) % 2 == 1:
delim += 1 # if string has odd number of characters
first_half = string[:mid]
second_half = string[delim:]
first_half = "".join(sorted(first_half))
seco... |
code/unclassified/src/leap_year/leap_year.c | #include <stdio.h>
bool checkLeapYear(int year)
{
if (year % 400 == 0)
return true;
if (year % 100 == 0)
return false;
if (year % 4 == 0)
return true;
return false;
}
int main()
{
int year1 , year2;
printf("Enter the first year: ");
scanf("%d",&year1);
printf(... |
code/unclassified/src/leap_year/leap_year.cpp | #include <iostream>
bool isLeapYear(int year)
{
if (year % 400 == 0)
return true;
if (year % 100 == 0)
return false;
return year % 4 == 0;
}
void findLeapYears(int a, int b)
{
std::cout << "The leap years between " << a << " and " << b << " are : \n";
for (int i = a; i <= b; i++)... |
code/unclassified/src/leap_year/leap_year.cs | using System;
namespace LeapTest
{
public class Program
{
private static bool isLeap(int year)
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public static void Main()
{
int startYear, endYear;
Console.Wri... |
code/unclassified/src/leap_year/leap_year.go | package main
import "fmt"
func IsLeapYear(year int) bool {
if year%400 == 0 {
return true
}
if year%100 == 0 {
return false
}
if year%4 == 0 {
return true
}
return false
}
func LeapYearsInRange(min, max int) []int {
var res []int
for i := min; i <= max; i++ {
if IsLeapYear(i) {
res = append(res,... |
code/unclassified/src/leap_year/leap_year.java | import java.io.InputStreamReader;
import java.util.Scanner;
class LeapYear {
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public static void main(String []args) {
Scanner in = new Scanner(new InputStreamReader(System.in));
System.out.println("E... |
code/unclassified/src/leap_year/leap_year.nim | func find_leap_year(start, last: int): seq[int] =
for y in start..last:
if (y mod 4 == 0 and y mod 100 != 0) or (y mod 400 == 0):
result.add(y)
when isMainModule:
echo find_leap_year(2000, 2020)
|
code/unclassified/src/leap_year/leap_year.py | # This program takes two inputs (years)
# and returns all leap years between them
# using normal for...in loop and List Comprehension loop
year_1 = int(input("Enter the first year: "))
year_2 = int(input("Enter the second year: "))
print("Normal way -----------------------------------")
leaps = []
for y in range(yea... |
code/unclassified/src/leap_year/leap_year.rs | // Part of Cosmos by OpenGenus
// find_leap_year takes in 2 years as start and end value
// and returns a vector containing the leap years between the given years.
// [start, end); end year in not included
fn find_leap_years(start: i32, end: i32) -> Vec<i32> {
(start..end)
.filter(|y| (y % 4 == 0 && y % 100... |
code/unclassified/src/leap_year/leap_years.js | function getLeapYears(start, end) {
var startYear = Math.ceil(start / 4) * 4;
var endYear = Math.floor(end / 4) * 4;
var leapYears = [];
if (isNaN(startYear) || isNaN(endYear)) return ['Invalid input'];
while (startYear <= endYear) {
if ( startYear % 100 || !(startYear % 400)) {
leap... |
code/unclassified/src/leap_year/readme.txt | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Leap year
The aim is to find leap years between two given years which are taken as input from the user.
Leap year is a year that contains 366 days.
"A leap year (also known as an intercalary year or bissextile ... |
code/unclassified/src/magic_square/magic_square.c | // Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
#include<string.h>
void MagicSquare(int n)
{
int magic[n][n],num;
memset(magic, 0, sizeof(magic));
// Initialize position for 1
int i = n/2;
int j = n-1;
// One by one put all values in magic square
for(num = 1; num <= n*n; ... |
code/unclassified/src/magic_square/magic_square.php | <?php
/* Part of Cosmos by OpenGenus Foundation */
/* Usage:
magicSquare(3);
*/
magicSquare(3);
function magicSquare($num) {
$magicSquare = array();
for ($row = 0; $row < $num; $row++) {
for ($col = 0; $col < $num; $col++) {
$rowMatrix = ((($num + 1) / 2 + $row + $col) % $num);
$colMatrix = ((($num +... |
code/unclassified/src/magic_square/magic_square.py | # MAgic Square generation for odd numbered squares
import numpy as np
N = input("Enter the dimension. Note that it should be odd : ")
magic_square = np.zeros((N, N), dtype=int)
n = 1
i, j = 0, N // 2
while n <= N ** 2:
magic_square[i, j] = n
n += 1
new_i, new_j = (i - 1) % N, (j + 1) % N
if magic_squ... |
code/unclassified/src/magic_square/magic_square.swift | import Foundation
let dimension = 5 // this should be an odd number
var magicSquare = Array<Array<Int>>()
for _ in 0..<dimension
{
magicSquare.append(Array<Int>(repeating: 0, count: dimension))
}
var i = dimension / 2
var j = dimension - 1
var num = 1
while num < dimension * dimension
{
if i == -1 && j == ... |
code/unclassified/src/majority_element/majority_element.cpp | #include <iostream>
#include <vector>
using namespace std;
int n;
vector<int> v;
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
int tmp;
cin >> tmp;
v.push_back(tmp);
}
int m, i = 0;
for (int k = 0; k < n; k++)
{
int x = v[k];
if (!i)
... |
code/unclassified/src/majority_element/majority_element_randomized.cpp | #include <iostream>
#include <vector>
using namespace std;
int n;
vector<int> v;
// Randomized algorithm with expected runtime: O(n), and Space: O(1)
int majorityElement(vector<int>& nums) {
int pos = 0, n = nums.size(), freq;
while(1) {
freq = 0;
for(int x : nums)if(x == nums[pos])++freq;
... |
code/unclassified/src/maximum_subarray_sum/maximum_subarray_sum.cpp | // Part of Cosmos by OpenGenus Foundation
// C++ implementation of simple algorithm to find
// Maximum Subarray Sum in a given array
// this implementation is done using Kadane's Algorithm which has a time complexity of O(n)
#include <iostream>
#include <vector>
#include <climits>
int maxSubarraySum(const std::vect... |
code/unclassified/src/median_of_two_sorted_arrays/median_of_two_sorted_arrays.c | #include <math.h>
#include <stdio.h>
int main()
{
int t;
scanf("%d", &t);
for (int i = 0; i < t; ++i)
{
int n;
scanf("%d", &n);
int a[n], temp;
for (int i = 0; i < n; ++i) //input
{
scanf("%d", &a[i]);
}
for (int i = 0; i < n; ++i) /... |
code/unclassified/src/median_two_sortedArrayOfDifferentLength/medianOfTwoSortedArrayOfDifferentLength.cpp | #include <bits/stdc++.h>
using namespace std;
double findMedian(int arr1[], int n1, int arr2[], int n2)
{
int lo = 0, hi = n1;
while (lo <= hi)
{
int cut1 = lo + (hi - lo) / 2;
int cut2 = (n1 + n2) / 2;
double l1 = cut1 == 0 ? INT_MIN : arr1[cut1 - 1];
double l2 = cut2 == 0... |
code/unclassified/src/merge_arrays/merge_arrays.cpp | #include <cstdlib>
#include <iostream>
#include <vector>
void merge(std::vector<int> arr, std::vector<int> arr1, std::vector<int> arr2) {
int k = 0;
for (int val : arr1) {
arr[k] = val;
k++;
}
for (int val : arr2) {
arr[k] = val;
k++;
}
std::cout << "Merged arra... |
code/unclassified/src/minimum_subarray_size_with_degree/minsubarraysizewithdegree.cpp | #include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
/* Part of Cosmos by OpenGenus Foundation */
using namespace std;
int minSubArraySizeWithDegree(const vector<int> nums)
{
unordered_map <int, int> m;
priority_queue<int> pq;
int best_degree = 1,
curr_best_degree = num... |
code/unclassified/src/move_zeroes_to_end/move_zeroes_to_end.cpp | #include <cstdlib>
#include <iostream>
#include <vector>
void move_zeroes(std::vector<int> arr, std::vector<int> a, int n) {
int k = 0;
for (int i = 0; i < n; ++i) {
if (a[i] != 0) {
arr.push_back(a[i]);
k++;
}
}
for (int i = k; i < n; ++i) {
arr.push_bac... |
code/unclassified/src/move_zeroes_to_end/move_zeroes_to_end.py | # Moving zeroes to the end of array
ar = list(map(int, input("Enter the elements: ").split()))
lis = [0] * len(ar)
j = 0
for i in range(len(ar)):
if ar[i] != 0:
lis[j] = ar[i]
j += 1
print("Final Array: ", *lis)
# INPUT:
# Enter the elements: 0 2 3 0 5 0
# OUTPUT:
# Final Array: 2 3 5 0 0 0
|
code/unclassified/src/no_operator_addition/addition.c | #include <stdio.h>
int add(int x, int y)
{
return printf("%*c%*c", x, '\r', y, '\r');
}
int main()
{
// test cases
int i, j;
for(i = 1; i <= 3; i++)
{
for(j = 1; j <= 3; j++)
{
printf("%d + %d = %d \n", i, j, add(i, j));
}
}
}
|
code/unclassified/src/optimized_fibonacci/optimized_fibonacci.cpp | /* Fibonacci Series implemented using Memoization */
#include <iostream>
long long fibonacci (int n)
{
static long long fib[100] = {}; // initialises the array with all elements as 0
fib[1] = 0;
fib[2] = 1;
if (n == 1 || n == 2)
return fib[n];
else if (fib[n] != 0)
return fib[n];
... |
code/unclassified/src/paint_fill/paint_fill.cpp | #include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
void print_matrix(char matrix[][100], int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
cout << matrix[i][j];
cout << endl;
}
}
void paint_fill(int i, int j, char dot, ch... |
code/unclassified/src/palindrome/palindrome_check/palindrome.nim | func is_palindrome(str: string): bool =
let length = str.len - 1
for i in 0..(length mod 2):
if str[i] != str[length - i]:
return false
true
from unicode import reversed
func is_palindrome_str_rev(str: string): bool =
str.reversed == str
when isMainModule:
assert("madam".is_pal... |
code/unclassified/src/palindrome/palindrome_check/palindrome.py | def main():
"""
Determine whether or not a string is a palindrome.
:print: 'That's a palindrome.' if the string is a palindrome,
'That isn't a palindrome' otherwise.
"""
input_str = input("Enter a string: ")
if is_palindrome(input_str):
print("That's a palindrome.")
else... |
code/unclassified/src/palindrome/palindrome_check/palindrome_check.c | #include <stdio.h>
#include <string.h>
int isPalindrome(char *arr)
{
int length = strlen(arr);
int i, j;
for(i = 0, j = length - 1; i < length / 2; ++i, --j)
{
if(arr[i] != arr[j])
{
return 0;
}
}
return 1;
}
int main()
{
printf("%d\n", isPalindrome("... |
code/unclassified/src/palindrome/palindrome_check/palindrome_check.cpp | #include <iterator>
#include <type_traits>
#include <functional>
namespace palindrome_check {
template<typename _InputIter,
typename _ValueNotEqualTo
= std::not_equal_to<typename std::iterator_traits<_InputIter>::value_type>,
typename _IterLess = std::less<_InputIter>>
bool
isPalindromeR... |
code/unclassified/src/palindrome/palindrome_check/palindrome_check.cs | using System;
namespace Palindrome
{
class Program
{
public static bool isPalindrome(string str)
{
for (int i = 0, j = str.Length - 1; i < str.Length / 2; ++i, --j)
{
if(str[i] != str[j])
{
return false;
... |
code/unclassified/src/palindrome/palindrome_check/palindrome_check.java | /* checks whether a given string is palindrome or not */
import java.util.Scanner;
public class palindrome_check {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word = scan.nextLine();
if(word.equals(reverse(word)))
System.out.println("yes it's a string");
else
... |
code/unclassified/src/palindrome/palindrome_check/palindrome_check.js | function isPalindrome(str) {
return [...str].reverse().join("") == str;
}
console.log(isPalindrome("lol"));
console.log(isPalindrome("nitin"));
console.log(isPalindrome("terabyte"));
console.log(isPalindrome("tbhaxor"));
// Output
// true
// true
// false
// false
|
code/unclassified/src/palindrome/palindrome_check/palindrome_check.rb | # careful using any variables named word, scoping gets weird
def is_palindrome_recursive(word)
# set both indices for iterating through the word
word_start = 0
word_end = word.length - 1
# check that the word is not one character or empty
if word_end != word_start
# check that the word start index is le... |
code/unclassified/src/range_sum_of_BST/range_sum_of_bst.java | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* ... |
code/unclassified/src/segregate_even_odd/segregate_even_odd.cpp | // Segregate all even numbers to left and odd numbers to right of the array
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <vector>
void even_odd(std::vector<int> a) {
int i = 0;
int j = a.size() - 1;
while (i < j) {
while (a[i] % 2 == 0 && i < j)
i++;
whi... |
code/unclassified/src/segregate_even_odd/segregate_even_odd.py | # Implemented using Bubble Sort
ar = list(map(int, input("Enter the elements: ").split()))
n = len(ar)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if ar[j] > ar[j + 1]:
ar[j], ar[j + 1] = ar[j + 1], ar[j]
swapped = True
if not swapped:
break
prin... |
code/unclassified/src/segregate_positive_negative/segregate_positive_negative.cpp | // Segregate positive and negative numbers in an array
// Here, we try to place all negative numbers to the left
// and all positive elements to the right in O(n) time.
// We can achieve this using Sorting also. But that takes O(nlogn) time.
#include <iostream>
#include <cstdlib>
// Similar to the partition function i... |
code/unclassified/src/smallest_number_to_the_left/smallest.cpp | //Part of Cosmos by OpenGenus Foundation
// C++ implementation of simple algorithm to find
// smaller element on left side
#include <iostream>
#include <stack>
using namespace std;
// Prints smaller elements on left side of every element
void printPrevSmaller(int arr[], int n)
{
// Create an empty stack
stac... |
code/unclassified/src/spiral_print/README.md | # cosmos
> Your personal library of every algorithm and data structure code that you will ever encounter
# Spiral Printing
The aim is to print a given 2D array in spiral form.
We take the dimensions of the array and the array as an input from the user. Dimensions of matrix are taken as mxn where m are the number of ... |
code/unclassified/src/spiral_print/spiral_print.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Part of Cosmos by OpenGenus Foundation
void printSpiral(int N, int M, int[][M]);
void print(int N, int M, int[][M]);
int main()
{
srand(time(NULL));
const int N = 5;
const int M = 5;
int matrix[N][M]; // if you change N & M values, use malloc()
int i, ... |
code/unclassified/src/spiral_print/spiral_print.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <vector>
#include <sstream>
std::string spiralPrint(std::vector<std::vector<int>> vec, int row, int col)
{
int begRow = 0,
endRow = row - 1,
begCol = 0,
endCol = col - 1;
std::ostringstream res;
while (begRow <= endRow && begCol... |
code/unclassified/src/spiral_print/spiral_print.go | package main
import "fmt"
// Part of Cosmos by OpenGenus Foundation
func PrintSpiral(list [][]int, rows, cols int) {
var T, B, L, R, dir int = 0, rows - 1, 0, cols - 1, 0
for {
if T >= B || L >= R {
break
}
// 0 - traverse right (going Left to Right)
if dir == 0 {
for i := 0; i <= R; i++ {
fmt.Pr... |
code/unclassified/src/spiral_print/spiral_print.java | class Main
{
private static void printSpiralOrder(int[][] mat)
{
// base case
if (mat == null || mat.length == 0) {
return;
}
int top = 0, bottom = mat.length - 1;
int left = 0, right = mat[0].length - 1;
while (true)
{
if (left... |
code/unclassified/src/spiral_print/spiral_print.py | from __future__ import print_function
"""
Part of Cosmos by OpenGenus Foundation
"""
matrix = lambda x: list(map(list, zip(*[iter(range(1, x * x + 1))] * x)))
"""
matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]
"""
def main(size):
a = matrix(size)... |
code/unclassified/src/split_list/split_array.js | function splitArray(array, parts) {
let subArray = [];
for (let i = 0; i <= array.length; i += parts) {
subArray.push(array.slice(i, i + parts));
}
if (subArray[subArray.length - 1].length == 0) {
subArray.pop();
}
return subArray;
}
for (let x = 1; x <= 10; ++x) {
console.log(splitArray([1, 2, 3... |
code/unclassified/src/split_list/split_list.py | """
Function script to split a list in n parts
This function can be reused in any project or script.
If you have the following list: [1,2,3,4,5,6,7,8,9,10] and want to break it in
5 parts, you should do:
>>> new_list = [1,2,3,4,5,6,7,8,9,10]
>>> print breaker(new_list, 5)
And you should get:
[[1,2], [3,4]... |
code/unclassified/src/sum_numbers_string/sum_numbers_string.cpp | // Given a string containing alphanumeric characters, calculate sum of all
// numbers present in the string.
#include <cctype>
#include <cstdlib>
#include <iostream>
int sumNumbersString(std::string s) {
int sum = 0;
std::string str = "";
for (int i = 0; i < s.length(); i++) {
if (isdigit(s[i])) {
... |
code/unclassified/src/tokenizer/tokenizer.cpp | #include <iostream>
#include <string>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
string myStrTok(char *input, char delim)
{
static char* ptr;
if (input != nullptr)
ptr = input;
if (ptr == nullptr)
return "";
string output = "";
int i;
for (i = 0; ptr[i] != ... |
code/unclassified/src/unique_number/unique_num_stl.cpp | #include <algorithm>
#include <iostream>
#include <vector>
int main() {
int n, i;
std::cin >> n; // size of array element
std::vector<int> arr(n); // declaration of vector
for (i = 0; i < n; ++i) {
std::cin >> arr[i]; // input
}
std::sort(arr.begin(), arr.end()); // sort the v... |
code/unclassified/src/unique_number/unique_number.cpp | #include <algorithm>
#include <iostream>
#include <cstdlib>
#include <vector>
void display_unique(std::vector<int> arr, int n) {
sort(arr.begin(), arr.end());
for (int i = 0; i < n; ++i) {
while (i < n - 1 && arr[i] == arr[i + 1])
i++;
std::cout << arr[i] << " ";
}
}
int main()... |
code/unclassified/src/unique_number/unique_number.java | import java.util.*;
public class UniqueNumber {
public static void main(String[] args) {
// token array to search
int[] a = new int[10];
System.out.println(uniqueNumber(a));
}
public int uniqueNumber(int[] a) {
Map<Integer, Integer> numbers = new HashMap<Integer, Integer>();
for (int i=0; i<a... |
code/unclassified/src/unique_number/unique_number.py | # Unique numbers in an array
l1 = list(map(int, input("Enter the elements: ").split()))
uniq_list = []
for i in l1:
if i not in uniq_list:
uniq_list.append(i)
print("Unique elements: ", *(uniq_list))
# INPUT:
# Enter the elements: 1 2 2 3 4 5 5
# OUTPUT:
# Unique elements: 1 2 3 4 5
|
code/unclassified/src/unique_numbers/unique_numbers.py | # Unique numbers in an array
l1 = list(map(int, input("Enter the elements: ").split()))
uniq_list = []
for i in l1:
if i not in uniq_list:
uniq_list.append(i)
print("Unique elements: ", *(uniq_list))
# INPUT:
# Enter the elements: 1 2 2 3 4 5 5
# OUTPUT:
# Unique elements: 1 2 3 4 5
|
code/unclassified/src/utilities/convert2mp3.sh | #!/usr/bin/bash
# A program that converts all media into 320kbps mp3 file.
# I use it to organize my media in a common format and common bitrates.
# Author: Adithya Bhat [[email protected]]
# Dependencies:
# Please install ffmpeg on your machine for the program to work
# Usage:
# $ convert2mp3 webm m4a
# Converts ... |
code/unclassified/src/utilities/download_link.sh | #!/usr/bin/bash
# A program that downloads the link in your clipboard.
# I use it to download links that I have copied.
# Author: Adithya Bhat [[email protected]]
# Dependencies:
# Please install xclip and/or one of {axel,aria2c} on your machine to maximize the
# download speeds.
# Usage:
# $ download
# Downloa... |
code/unclassified/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/unclassified/test/palindrome/palindrome_check/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/unclassified/test/palindrome/palindrome_check/test_palindrome_check.cpp | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cassert>
#include "../../../src/palindrome/palindrome_check/palindrome_check.cpp"
using namespace std;
using namespace palindrome_check;
// for test
struct MapValueEqual
{
bool operator()(std::pair<int, int> const &a, std::pair<int, i... |
code/unclassified/test/spiral_printing/test_spiral_print.cpp | #include "../../src/spiral_print/spiral_print.cpp"
#include <cassert>
int main()
{
using namespace std;
vector<vector<int>> vec;
// empty test
assert("" == spiralPrint(vec, 0, 0));
/* row test (even col)
* 1 2 3 4 5 6
* 7 8 9 10 11 12
* 13 14 15 16 17 18
* 19 20 21 22 2... |
generate_dependencies.make | #for Cpp
.PHONY: all generate_dependency append_command
all: generate_dependency append_command;
G++FLAGS = -Wall -std=c++11
# warning: the '^^^^^^^^^^' cannot be used in file-name
COSMOS_ROOT_PATH := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
RECOVER-NAME = $(subst ^^^^^^^^^^,\ ,$(strip $1))
RECOVER-... |
guides/README.md | # Cosmos Guides
> Your personal library of every algorithm and data structure code that you will ever encounter
This folder contains various guidelines in terms of new documentation and coding style that are useful when contributing to this repository.
The folder `coding_style` contains style guides for various progr... |
guides/coding_style/README.md | # Cosmos Guides
> Your personal library of every algorithm and data structure code that you will ever encounter
This folder contains style guides for various programming languages. To find one specific to the language you are looking for, open the file `lang_name/README.md`.
---
<p align="center">
A massive collabo... |
guides/coding_style/c#/README.md | # Cosmos Guides
> Your personal library of every algorithm and data structure code that you will ever encounter
Please follow the official Microsoft [C# coding guidelines](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions).
---
<p align="center">
A massive collabor... |
guides/coding_style/c#/tryCatch.md | ---
Title: Try Catch Statement
---
## Try Catch in CSharp
In the world of programming most of the time for the newbie, they only code in a linear way, assuming that it will be a good practice
and most of the time learning to error exception handling is left behind.
But it's only just a normal for newbie programmers ... |
guides/coding_style/c++/README.md | # Cosmos Guides
> Your personal library of every algorithm and data structure code that you will ever encounter
# C++ Style Guide
> All demonstrates are VALID version
## Index
- [Comments](#comments)
- [Code Width and Alignment](#code-width-and-alignment)
- [Spaces](#spaces)
- [Indentations](#indentations)
- [Newline... |
guides/coding_style/c++/uncrustify_tests/input/space001.cpp | #include <iostream>
#include<vector>
using namespace std;
void bar(int,int,int)
{
// less space
if(true)
{
vector<int> vec{1,2,3};
int i=(1+2)*3;
}
}
void foo( )
{
// more space
if (true)
{
vector<int> vec{1 , 2 , 3};
int i = (1 + 2) * 3; ... |
guides/coding_style/c++/uncrustify_tests/output/space001.cpp | #include <iostream>
#include <vector>
using namespace std;
void bar(int, int, int)
{
// less space
if (true)
{
vector<int> vec{1, 2, 3};
int i = (1 + 2) * 3;
}
}
void foo()
{
// more space
if (true)
{
vector<int> vec{1, 2, 3};
int i = (1 + 2) * 3;
... |
guides/coding_style/c++/uncrustify_tests/test.sh | for full_path_file in `find 'input' -name '*.cpp'`
do
# format file
uncrustify -c ../../../../third_party/uncrustify.cfg $full_path_file
# compare file
input_file=$full_path_file'.uncrustify'
output_file='output/'`basename $full_path_file`
diff $input_file $output_file
done
|
guides/coding_style/c/README.md | # Cosmos Guides
> Your personal library of every algorithm and data structures code that you will ever encounter
## C Code style
C is a general-purpose mid level, procedural computer programming language originally developed between 1969 and 1973 and founded by Dennis Ritchie in AT&T Labs in 1972.
# C Programming St... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.