filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/greedy_algorithms/src/egyptian_fraction/egyptian_fraction.py
# Part of Cosmos by OpenGenus Foundation import math import fractions def fibonacciEgyptian(numerator, denominator, current_fraction=[]): # Fibonacci's algorithm implementation inverse = denominator / numerator first_part = fractions.Fraction(1, math.ceil(inverse)) second_part = fractions.Fraction( int(-denominator % numerator), denominator * math.ceil(inverse) ) current_fraction.append(first_part) if second_part.numerator != 1: return fibonacciEgyptian( second_part.numerator, second_part.denominator, current_fraction ) else: current_fraction.append(second_part) print(current_fraction) return current_fraction
code/greedy_algorithms/src/fractional_knapsack/README.md
# Fractional Knapsack ---- ## what is Fractional Knapsack? >see [Wikipedia](https://en.wikipedia.org/wiki/Continuous_knapsack_problem) In theoretical computer science, Fractional Knapsack problem is an algorithmic problem in combinatorial optimization in which the goal is to fill a container (the "knapsack") with fractional amounts of different materials chosen to maximize the value of the selected materials. It is also referred to as Continuous Knapsack. ## Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/greedy_algorithms/src/fractional_knapsack/fractional_knapsack.c
/* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> int n = 5; /* The number of objects */ int c[10] = {12, 1, 2, 1, 4}; /* c[i] is the *COST* of the ith object; i.e. what YOU PAY to take the object */ int v[10] = {4, 2, 2, 1, 10}; /* v[i] is the *VALUE* of the ith object; i.e. what YOU GET for taking the object */ int W = 15; /* The maximum weight you can take */ void simple_fill() { int cur_w; float tot_v; int i, maxi; int used[10]; for (i = 0; i < n; ++i) used[i] = 0; /* I have not used the ith object yet */ cur_w = W; while (cur_w > 0) { /* while there's still room*/ /* Find the best object */ maxi = -1; for (i = 0; i < n; ++i) if ((used[i] == 0) && ((maxi == -1) || ((float)v[i]/c[i] > (float)v[maxi]/c[maxi]))) maxi = i; used[maxi] = 1; /* mark the maxi-th object as used */ cur_w -= c[maxi]; /* with the object in the bag, I can carry less */ tot_v += v[maxi]; if (cur_w >= 0) printf("Added object %d (%d$, %dKg) completely in the bag. Space left: %d.\n", maxi + 1, v[maxi], c[maxi], cur_w); else { printf("Added %d%% (%d$, %dKg) of object %d in the bag.\n", (int)((1 + (float)cur_w/c[maxi]) * 100), v[maxi], c[maxi], maxi + 1); tot_v -= v[maxi]; tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi]; } } printf("Filled the bag with objects worth %.2f$.\n", tot_v); } int main(int argc, char *argv[]) { simple_fill(); return 0; }
code/greedy_algorithms/src/fractional_knapsack/fractional_knapsack.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <algorithm> using namespace std; // Custom structure for Item to store its weight and value struct Item { int value, weight; // Constructor to initialize weight and value Item(int value, int weight) : value(value), weight(weight) { } }; // Custom comparison function to sort Items according to val/weight ratio bool cmp(struct Item a, struct Item b) { double r1 = (double)a.value / a.weight; double r2 = (double)b.value / b.weight; return r1 > r2; } // Main greedy function to solve problem double fractionalKnapsack(int W, struct Item arr[], int n) { // sorting Item on basis of ratio value/weight sort(arr, arr + n, cmp); int curWeight = 0; // Current weight in knapsack double finalvalue = 0.0; // Result (value in Knapsack) // Looping through all Items for (int i = 0; i < n; i++) { // If adding Item won't overflow, add it completely if (curWeight + arr[i].weight <= W) { curWeight += arr[i].weight; finalvalue += arr[i].value; } // If we can't add current Item, add a fraction of it else { int remain = W - curWeight; finalvalue += arr[i].value * ((double) remain / arr[i].weight); break; } } // Returning final value return finalvalue; } int main() { int W = 50; // Weight of knapsack Item arr[] = {{60, 10}, {100, 20}, {120, 30}}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum value we can obtain = " << fractionalKnapsack(W, arr, n) << endl; return 0; }
code/greedy_algorithms/src/fractional_knapsack/fractional_knapsack.cs
/* *Part of Cosmos by OpenGenus Foundation */ using System; namespace FractionalKnapsack { // Custom object for Item to store its weight and value public class Item { public int Value { get; set; } public int Weight { get; set; } public Item(int value,int weight) { this.Value = value; this.Weight = weight; } } public class FractionalKnapsack { // Custom comparison function to sort Items according to val/weight ratio private static int CompareItems(Item a, Item b) { double r1 = (double)a.Value / a.Weight; double r2 = (double)b.Value / b.Weight; //items are the same object or equal r if(a == b || r1 == r2) { return 0; } //a < b else if (r1 < r2) { return 1; } //b < a else { return -1; } } private static double FractionalKnapsack(int W, Item[] arr) { //sorting Item on basis of ratio value/weight Array.Sort(arr, CompareItems); int curWeight = 0; // Current weight in knapsack double finalvalue = 0.0; // Result (value in Knapsack) // Looping through all Items for (int i = 0; i < arr.Length; i++) { // If adding Item won't overflow, add it completely if (curWeight + arr[i].Weight <= W) { curWeight += arr[i].Weight; finalvalue += arr[i].Value; } // If we can't add current Item, add a fraction of it else { int remain = W - curWeight; finalvalue += arr[i].Value * ((double)remain / arr[i].Weight); break; } } // Returning final value return finalvalue; } public static void Main(string[] args) { int W = 50; // Weight of knapsack Item[] arr = { new Item(60,10), new Item(100,20), new Item(120,30) }; Console.WriteLine("Maximum value we can obtain = " + FractionalKnapsack(W, arr)); } } }
code/greedy_algorithms/src/fractional_knapsack/fractional_knapsack.go
//Part of Cosmos Project by OpenGenus Foundation //Implementation of the factional knapsack on golang //written by Guilherme Lucas (guilhermeslucas) package main import ( "fmt" "sort" ) type Item struct { value float32 weight float32 } func fractional_knapsack(items []Item, maxWeight float32) float32 { var totalPrice float32 sort.Sort(ByPrice(items)) for i := 0; i < len(items); i++ { if maxWeight == 0 { break } if (items[i].weight <= maxWeight) { totalPrice = totalPrice + items[i].value maxWeight = maxWeight - items[i].weight } else { totalPrice = totalPrice + items[i].price()*maxWeight maxWeight = 0 } } return totalPrice } func (i Item) price() float32 { return i.value/i.weight } type ByPrice []Item func (c ByPrice) Len() int { return len(c) } func (c ByPrice) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c ByPrice) Less(i, j int) bool { return c[i].price() > c[j].price() } func main() { items := []Item{} i1 := Item{ value: 32, weight: 2, } i2 := Item{ value: 16, weight: 4, } i3 := Item{ value: 8, weight: 8, } items = append(items,i1) items = append(items,i2) items = append(items,i3) fmt.Println("The maximum price is: ",fractional_knapsack(items, 10)) }
code/greedy_algorithms/src/fractional_knapsack/fractional_knapsack.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Scanner; /** * Added by Vishesh Dembla on October 07, 2017 */ public class fractional_knapsack { private double finalValue; private int remainingWeight; private Item [] itemList; public fractional_knapsack( int totalWeight, Item [] itemList) { this.finalValue = 0; this.remainingWeight = totalWeight; this.itemList = itemList; //Sorting the array in descending order based upon the preference order Arrays.sort(itemList); } public double getFinalValue() { return finalValue; } public int getRemainingWeight() { return remainingWeight; } public Item [] getFractions(){ int i = 0; //Setting fraction of preffered items as 1.0, if their weight is less than the total remaining weight while(i < itemList.length && remainingWeight > itemList[i].getWeight()){ remainingWeight -= itemList[i].getWeight(); finalValue += itemList[i].getValue(); itemList[i].setFraction(1.0); i++; } if( i < itemList.length) { //Calculating the fraction of the item whoes weight is greater than the current remaining weight finalValue = finalValue + (remainingWeight) * itemList[i].getValue() / itemList[i].getWeight(); itemList[i].setFraction(remainingWeight / itemList[i].getWeight()); remainingWeight = 0 ; } return itemList; } public static void main(String args[]){ int totalWeight = 90; Item [] items = {new Item(10,60) , new Item(20,100) , new Item(30, 120)}; fractional_knapsack fractionalKnapsack = new fractional_knapsack(totalWeight , items); items = fractionalKnapsack.getFractions(); System.out.println("TOTAL VALUE = "+fractionalKnapsack.getFinalValue()+" REMAINING WEIGHT = "+fractionalKnapsack.getRemainingWeight()); for(int i = 0 ; i < items.length ; i++)System.out.print("ITEM "+(i+1) +" "+items[i]); } } class Item implements Comparable<Item>{ private int weight; private int value; private double preference; private double fraction; public Item(int weight, int value) { this.weight = weight; this.value = value; this.fraction = 0.0; //Attribute preference helps to decide the order of preference of the items for selection this.preference = (double) value / (double) weight; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public double getFraction() { return fraction; } public void setFraction(double fraction) { this.fraction = fraction; } //Enabling sort in descending order @Override public int compareTo(Item item) { double difference = this.preference - item.preference; if(difference > 0) return -1; else if(difference < 0) return 1; else return 0; } @Override public String toString(){ return "VALUE = "+this.value+" WEIGHT = "+this.weight+" FRACTION = "+this.fraction+"\n"; } }
code/greedy_algorithms/src/fractional_knapsack/fractional_knapsack.py
""" Part of Cosmos by OpenGenus Foundation """ # Item class with weight and values class Item: # intialize weight and values def __init__(self, weight=0, value=0): self.weight = weight self.value = value return def fractional_knapsack(items, W): # Sorting items by value /weight sorted(items, key=lambda item: float(item.value) / float(item.weight)) finalValue = 0.0 currentWeight = 0 for item in items: if currentWeight + item.weight <= W: # If adding Item won't overflow, add it completely finalValue += item.value currentWeight += item.weight else: # If we can't add current Item, add a fraction of it remaining = W - currentWeight finalValue += item.value * (float(remaining) / float(item.weight)) break return finalValue def main(): W = 50 items = [Item(10, 60), Item(20, 100), Item(30, 120)] print("Maximum value we can obtain -{}".format(fractional_knapsack(items, W))) return if __name__ == "__main__": main()
code/greedy_algorithms/src/hillclimber/hillclimber.java
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Hillclimber { private double[][] distances; private int[] shortestRoute; private static final int NUMBER_OF_CITIES = 100; public Hillclimber() { distances = new double[NUMBER_OF_CITIES][NUMBER_OF_CITIES]; } public static void main(String[] args) { Hillclimber hillclimber = new Hillclimber(); hillclimber.fillList(); hillclimber.shortestRoute = hillclimber.getShortestRouteStart(); hillclimber.calculateShortestDistance(); } /** * calculate the current fitness when getting the route as an array of integers, which city to visit first * * @param route array of integers, current route * @return distance of the route, lower is better */ private float fitness(int[] route) { float currentFitness = 0; for (int i = 0; i < route.length - 1; i++) { currentFitness += distanceFromAtoB(route[i],route[i+1]); } return currentFitness; } /** * returns a random route that passes every city * @return */ private int[] getShortestRouteStart(){ List<Integer> numbers = new ArrayList<>(); for(int i = 0;i<100; i++){ numbers.add(i); } Collections.shuffle(numbers); int[] shortestRoute = numbers.stream().mapToInt(i->i).toArray(); return shortestRoute; } public double distanceFromAtoB(int positionA, int positionB){ return distances[positionA][positionB]; } @Override public String toString() { String order = ""; double distance = 0; for(int i =0;i<shortestRoute.length-1;i++){ order += shortestRoute[i] + ", "; distance += distanceFromAtoB(shortestRoute[i],shortestRoute[i+1]); } return order + "\n total distance = "+ distance; } /** * swap the position of 2 cities on the route * * @param currentRoute * @return */ private int[] moveOneStepAtRandom(int[] currentRoute) { int[] currentRouteCopy = Arrays.copyOf(currentRoute, currentRoute.length); int position1 = (int) (Math.random()*100); int position2 = (int) (Math.random()*100); currentRouteCopy[position1] = currentRoute[position2]; currentRouteCopy[position2] = currentRoute[position1]; return currentRouteCopy; } /** * find the shortest distance */ private void calculateShortestDistance() { float lastFitness = fitness(shortestRoute); double threshold = lastFitness/9; int i = 0; do { i++; int[] lastRoute= Arrays.copyOf(shortestRoute, shortestRoute.length); shortestRoute = moveOneStepAtRandom(shortestRoute); if (fitness(shortestRoute) < lastFitness) { lastFitness = fitness(shortestRoute); } else { shortestRoute = lastRoute; } } while (lastFitness > threshold && i<50000); //TODO: find the Threshold } /** Initializes the list with random distances between each of the cities * */ private void fillList() { for (int i = 0; i < NUMBER_OF_CITIES; i++) { for (int j = i; j < NUMBER_OF_CITIES; j++) { if (i == j) { distances[i][j] = 0; } else { distances[i][j] = Math.random()*100; distances[j][i] = distances[i][j]; } } } } }
code/greedy_algorithms/src/huffman_coding/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/greedy_algorithms/src/huffman_coding/huffman_GreedyAlgo.java
import java.util.PriorityQueue; import java.util.Scanner; import java.util.Comparator; class HuffmanNode { int data; char c; HuffmanNode left; HuffmanNode right; } class MyComparator implements Comparator<HuffmanNode> { public int compare(HuffmanNode x, HuffmanNode y) { return x.data - y.data; } } public class Huffman { public static void printCode(HuffmanNode root, String s) { if (root.left == null && root.right == null && Character.isLetter(root.c)) { System.out.println(root.c + ":" + s); return; } printCode(root.left, s + "0"); printCode(root.right, s + "1"); } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = 6; char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; int[] charfreq = { 5, 9, 12, 13, 16, 45 }; PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator()); for (int i = 0; i < n; i++) { HuffmanNode hn = new HuffmanNode(); hn.c = charArray[i]; hn.data = charfreq[i]; hn.left = null; hn.right = null; q.add(hn); } HuffmanNode root = null; while (q.size() > 1) { HuffmanNode x = q.peek(); q.poll(); HuffmanNode y = q.peek(); q.poll(); HuffmanNode f = new HuffmanNode(); f.data = x.data + y.data; f.c = '-'; f.left = x; f.right = y; root = f; q.add(f); } printCode(root, ""); } }
code/greedy_algorithms/src/huffman_coding/huffman_coding.c
#include <stdio.h> #include <stdlib.h> #define MAX_TREE_HT 100 struct MinHeapNode { char data; int freq; struct MinHeapNode *left, *right; }; struct MinHeap { int size; int capacity; struct MinHeapNode** array; }; struct MinHeapNode* newNode(char data, int freq) { struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return (temp); } struct MinHeap* createMinHeap(int capacity) { struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap)); minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*)); return (minHeap); } void swapMinHeapNode(struct MinHeapNode** a,struct MinHeapNode** b) { struct MinHeapNode* t = *a; *a = *b; *b = t; } void minHeapify(struct MinHeap* minHeap, int index) { int smallest = index; int left = (2 * index) + 1; int right = (2 * index) + 2; if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest = right; if (smallest != index) { swapMinHeapNode(&minHeap->array[smallest],&minHeap->array[index]); minHeapify(minHeap, smallest); } } int isSizeOne(struct MinHeap* minHeap) { return (minHeap->size == 1); } struct MinHeapNode* extractMin(struct MinHeap* minHeap) { struct MinHeapNode* temp = minHeap->array[0]; minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return (temp); } void insertMinHeap(struct MinHeap* minHeap,struct MinHeapNode* minHeapNode) { ++minHeap->size; int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap->array[i] = minHeapNode; } void buildMinHeap(struct MinHeap* minHeap) { int i; for (i = (minHeap->size - 2) / 2; i >= 0; --i) minHeapify(minHeap, i); } void printArr(int arr[], int n) { int i; for (i = 0; i < n; ++i) printf("%d", arr[i]); printf("\n"); } int isLeaf(struct MinHeapNode* root) { return !(root->left) && !(root->right); } struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) { struct MinHeap* minHeap = createMinHeap(size); int i; for (i = 0; i < size; ++i) minHeap->array[i] = newNode(data[i], freq[i]); minHeap->size = size; buildMinHeap(minHeap); return (minHeap); } struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); while (!isSizeOne(minHeap)) { left = extractMin(minHeap); right = extractMin(minHeap); top = newNode('@', left->freq + right->freq); top->left = left; top->right = right; insertMinHeap(minHeap, top); } return (extractMin(minHeap)); } void printCodes(struct MinHeapNode* root, int arr[], int top) { if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } if (isLeaf(root)) { printf("%c: ", root->data); printArr(arr, top); } } void HuffmanCodes(char data[], int freq[], int size) { struct MinHeapNode* root= buildHuffmanTree(data, freq, size); int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top); } int main() { int size; printf("Enter number of characters: "); scanf("%d", &size); char arr[size]; int freq[size]; int i; for (i = 0; i <size; ++i) { printf("Enter character %d: ", i + 1); scanf(" %c", &arr[i]); printf("Enter frequency character %d: ", i + 1); scanf("%d", &freq[i]); } HuffmanCodes(arr, freq, size); return (0); }
code/greedy_algorithms/src/huffman_coding/huffman_coding.cpp
/* * Huffman Codes */ // Part of Cosmos by OpenGenus Foundation #include <iostream> // std::cout, std::endl #include <map> // std::map #include <string> // std::string #include <queue> // std::priority_queue struct huff_node { float weight; huff_node *left, *right; huff_node(float w, huff_node *l, huff_node *r) : weight(w), left(l), right(r) { } virtual ~huff_node() { delete left; delete right; } virtual void print(std::string) { } }; struct huff_leaf : public huff_node { char letter; huff_leaf(char c, float w) : huff_node(w, nullptr, nullptr), letter(c) { } void print(std::string prefix = "") { std::cout << letter << " (" << weight << ") -> " << prefix << std::endl; } }; struct Compare { bool operator()(huff_node *a, huff_node *b) { return a->weight > b->weight; } }; huff_node * merge_nodes(huff_node *a, huff_node *b) { return new huff_node(a->weight + b->weight, a, b); } typedef std::priority_queue<huff_node*, std::vector<huff_node*>, Compare> huff_priority_queue; huff_node * encode(std::map<char, float> &m) { huff_priority_queue pq; huff_node *a, *b; // create a huff_leaf for each letter in the map // weighted by its associated weight, and put each leaf into // priority queue std::map<char, float>::iterator it; for (it = m.begin(); it != m.end(); it++) pq.push(new huff_leaf(it->first, it->second)); // create the tree while (pq.size() > 1) { a = pq.top(); pq.pop(); b = pq.top(); pq.pop(); pq.push(merge_nodes(a, b)); } // only single node left in the pq, root of the tree return pq.top(); } void print_tree(huff_node *node, std::string prefix = "") { node->print(prefix); if (node->left) print_tree(node->left, prefix + "0"); if (node->right) print_tree(node->right, prefix + "1"); } int main() { // dictionary of letters w/ frequency in English std::map<char, float> freq = { {'a', 8.1}, {'b', 1.5}, {'c', 2.8}, {'d', 4.2}, {'e', 12.7}, {'f', 2.2}, {'g', 2.0}, {'h', 6.0}, {'i', 7.0}, {'j', 0.2}, {'k', 0.8}, {'l', 4.0}, {'m', 2.4}, {'n', 6.7}, {'o', 7.5}, {'p', 1.9}, {'q', 0.1}, {'r', 6.0}, {'s', 6.3}, {'t', 9.1}, {'u', 2.8}, {'v', 1.0}, {'w', 2.4}, {'x', 0.2}, {'y', 2.0}, {'z', 0.1} }; huff_node *root = encode(freq); print_tree(root); return 0; }
code/greedy_algorithms/src/huffman_coding/huffman_coding.py
import heapq import os from functools import total_ordering """ Code for Huffman Coding, compression and decompression. Explanation at http://bhrigu.me/blog/2017/01/17/huffman-coding-python-implementation/ """ @total_ordering class HeapNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None # defining comparators less_than and equals def __lt__(self, other): return self.freq < other.freq def __eq__(self, other): if other == None: return False if not isinstance(other, HeapNode): return False return self.freq == other.freq class HuffmanCoding: def __init__(self, path): self.path = path self.heap = [] self.codes = {} self.reverse_mapping = {} # functions for compression: def make_frequency_dict(self, text): frequency = {} for character in text: if not character in frequency: frequency[character] = 0 frequency[character] += 1 return frequency def make_heap(self, frequency): for key in frequency: node = HeapNode(key, frequency[key]) heapq.heappush(self.heap, node) def merge_nodes(self): while len(self.heap) > 1: node1 = heapq.heappop(self.heap) node2 = heapq.heappop(self.heap) merged = HeapNode(None, node1.freq + node2.freq) merged.left = node1 merged.right = node2 heapq.heappush(self.heap, merged) def make_codes_helper(self, root, current_code): if root == None: return if root.char != None: self.codes[root.char] = current_code self.reverse_mapping[current_code] = root.char return self.make_codes_helper(root.left, current_code + "0") self.make_codes_helper(root.right, current_code + "1") def make_codes(self): root = heapq.heappop(self.heap) current_code = "" self.make_codes_helper(root, current_code) def get_encoded_text(self, text): encoded_text = "" for character in text: encoded_text += self.codes[character] return encoded_text def pad_encoded_text(self, encoded_text): extra_padding = 8 - len(encoded_text) % 8 for i in range(extra_padding): encoded_text += "0" padded_info = "{0:08b}".format(extra_padding) encoded_text = padded_info + encoded_text return encoded_text def get_byte_array(self, padded_encoded_text): if len(padded_encoded_text) % 8 != 0: print("Encoded text not padded properly") exit(0) b = bytearray() for i in range(0, len(padded_encoded_text), 8): byte = padded_encoded_text[i : i + 8] b.append(int(byte, 2)) return b def compress(self): filename, file_extension = os.path.splitext(self.path) output_path = filename + ".bin" with open(self.path, "r+") as file, open(output_path, "wb") as output: text = file.read() text = text.rstrip() frequency = self.make_frequency_dict(text) self.make_heap(frequency) self.merge_nodes() self.make_codes() encoded_text = self.get_encoded_text(text) padded_encoded_text = self.pad_encoded_text(encoded_text) b = self.get_byte_array(padded_encoded_text) output.write(bytes(b)) print("Compressed") return output_path """ functions for decompression: """ def remove_padding(self, padded_encoded_text): padded_info = padded_encoded_text[:8] extra_padding = int(padded_info, 2) padded_encoded_text = padded_encoded_text[8:] encoded_text = padded_encoded_text[: -1 * extra_padding] return encoded_text def decode_text(self, encoded_text): current_code = "" decoded_text = "" for bit in encoded_text: current_code += bit if current_code in self.reverse_mapping: character = self.reverse_mapping[current_code] decoded_text += character current_code = "" return decoded_text def decompress(self, input_path): filename, file_extension = os.path.splitext(self.path) output_path = filename + "_decompressed" + ".txt" with open(input_path, "rb") as file, open(output_path, "w") as output: bit_string = "" byte = file.read(1) while len(byte) > 0: byte = ord(byte) bits = bin(byte)[2:].rjust(8, "0") bit_string += bits byte = file.read(1) encoded_text = self.remove_padding(bit_string) decompressed_text = self.decode_text(encoded_text) output.write(decompressed_text) print("Decompressed") return output_path
code/greedy_algorithms/src/job_sequencing/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/greedy_algorithms/src/job_sequencing/job_sequencing.cpp
#include <iostream> #include <algorithm> using namespace std; // Part of Cosmos by OpenGenus Foundation // A structure to represent a job struct Job { char id; // Job Id int dead; // Deadline of job int profit; // Profit if job is over before or on deadline }; // This function is used for sorting all jobs according to profit bool comparison(Job a, Job b) { return a.profit > b.profit; } // Returns minimum number of platforms reqquired void printJobScheduling(Job arr[], int n) { // Sort all jobs according to decreasing order of prfit sort(arr, arr + n, comparison); int result[n]; // To store result (Sequence of jobs) bool slot[n]; // To keep track of free time slots // Initialize all slots to be free for (int i = 0; i < n; i++) slot[i] = false; // Iterate through all given jobs for (int i = 0; i < n; i++) { // Find a free slot for this job (Note that we start // from the last possible slot) for (int j = min(n, arr[i].dead) - 1; j >= 0; j--) // Free slot found if (slot[j] == false) { result[j] = i; // Add this job to result slot[j] = true; // Make this slot occupied break; } } // Print the result for (int i = 0; i < n; i++) if (slot[i]) cout << arr[result[i]].id << " "; } int main() { Job arr[] = { {'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27}, {'d', 1, 25}, {'e', 3, 15}}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Following is maximum profit sequence of jobsn"; printJobScheduling(arr, n); return 0; }
code/greedy_algorithms/src/job_sequencing/job_sequencing.java
import java.util.Arrays; import java.util.Comparator; class Job { char id; int deadline, profit; public Job(char id, int deadline, int profit) { this.id = id; this.deadline = deadline; this.profit = profit; } } public class job_sequencing { public static void printJobSequence(Job[] jobs) { // Sort jobs based on decreasing order of profit Arrays.sort(jobs, Comparator.comparingInt(j -> -j.profit)); int n = jobs.length; int[] result = new int[n]; boolean[] slot = new boolean[n]; // Time slots // Iterate through all given jobs and select the maximum profit job for (int i = 0; i < n; i++) { // Find a free slot for this job for (int j = Math.min(n, jobs[i].deadline) - 1; j >= 0; j--) { if (!slot[j]) { result[j] = i; // Add this job to result slot[j] = true; // Mark this slot as occupied break; } } } // Print the result System.out.println("Job Sequence:"); for (int i = 0; i < n; i++) { if (slot[i]) { System.out.println(jobs[result[i]].id + " "); } } } public static void main(String[] args) { Job[] jobs = { new Job('a', 2, 100), new Job('b', 1, 19), new Job('c', 2, 27), new Job('d', 1, 25), new Job('e', 3, 15) }; System.out.println("Original Jobs:"); for (Job job : jobs) { System.out.println("Job ID: " + job.id + ", Deadline: " + job.deadline + ", Profit: " + job.profit); } printJobSequence(jobs); } }
code/greedy_algorithms/src/job_sequencing/job_sequencing.py
# Part of Cosmos by OpenGenus Foundation class Job: def __init__(self, name, profit, deadline): self.name = name self.profit = profit self.deadline = deadline def job_scheduling(jobs): jobs = sorted(jobs, key=lambda job: job.profit) max_deadline = max([job.deadline for job in jobs]) scheduling = [jobs.pop()] while len(jobs) != 0 and len(scheduling) < max_deadline: new_job = jobs.pop() if new_job.deadline - len(scheduling) > 0: scheduling.append(new_job) return scheduling
code/greedy_algorithms/src/k_centers/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/greedy_algorithms/src/k_centers/k_centers.py
# Part of Cosmos by OpenGenus Foundation import random import math # Euclidean Distance def euclidean(x, y): return math.sqrt(sum([(a - b) ** 2 for a, b in zip(x, y)])) # K-Centers Algorithm def k_centers(vertices, k, distance=euclidean): centers = set() centers.add(random.choice(vertices)) for i in range(k - 1): min_distance = dict() for vertex in vertices: if vertex not in centers: min_distance[vertex] = min( [distance(vertex, center) for center in centers] ) next_center = max(min_distance, key=min_distance.get) centers.add(next_center) return centers
code/greedy_algorithms/src/kruskal_minimum_spanning_tree/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) Below are the steps for finding MST using Kruskal’s algorithm ``` 1. Sort all the edges in non-decreasing order of their weight. 2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. 3. Repeat step#2 until there are (V-1) edges in the spanning tree. ```
code/greedy_algorithms/src/kruskal_minimum_spanning_tree/kruskal.c
// C++ program for Kruskal's algorithm to find Minimum Spanning Tree // of a given connected, undirected and weighted graph #include <stdio.h> #include <stdlib.h> #include <string.h> // a structure to represent a weighted edge in graph struct Edge { int src, dest, weight; }; // a structure to represent a connected, undirected and weighted graph struct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. Since the graph is // undirected, the edge from src to dest is also edge from dest // to src. Both are counted as 1 edge here. struct Edge* edge; }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) ); graph->V = V; graph->E = E; graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); return graph; } // A structure to represent a subset for union-find struct subset { int parent; int rank; }; // A utility function to find set of an element i // (uses path compression technique) int find(struct subset subsets[], int i) { // find root and make root as parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; } // A function that does union of two sets of x and y // (uses union by rank) void Union(struct subset subsets[], int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root of high rank tree // (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root and increment // its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } // Compare two edges according to their weights. // Used in qsort() for sorting an array of edges int myComp(const void* a, const void* b) { struct Edge* a1 = (struct Edge*)a; struct Edge* b1 = (struct Edge*)b; return a1->weight > b1->weight; } // The main function to construct MST using Kruskal's algorithm void KruskalMST(struct Graph* graph) { int V = graph->V; struct Edge result[V]; // Tnis will store the resultant MST int e = 0; // An index variable, used for result[] int i = 0; // An index variable, used for sorted edges // Step 1: Sort all the edges in non-decreasing order of their weight // If we are not allowed to change the given graph, we can create a copy of // array of edges qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp); // Allocate memory for creating V ssubsets struct subset *subsets = (struct subset*) malloc( V * sizeof(struct subset) ); // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } // Number of edges to be taken is equal to V-1 while (e < V - 1) { // Step 2: Pick the smallest edge. And increment the index // for next iteration struct Edge next_edge = graph->edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // If including this edge does't cause cycle, include it // in result and increment the index of result for next edge if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } // Else discard the next_edge } // print the contents of result[] to display the built MST printf("Following are the edges in the constructed MST\n"); for (i = 0; i < e; ++i) printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight); return; } // Driver program to test above functions int main() { /* Let us create following weighted graph 10 0--------1 | \ | 6| 5\ |15 | \ | 2--------3 4 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = 10; // add edge 0-2 graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 6; // add edge 0-3 graph->edge[2].src = 0; graph->edge[2].dest = 3; graph->edge[2].weight = 5; // add edge 1-3 graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 15; // add edge 2-3 graph->edge[4].src = 2; graph->edge[4].dest = 3; graph->edge[4].weight = 4; KruskalMST(graph); return 0; }
code/greedy_algorithms/src/kruskal_minimum_spanning_tree/kruskal.cpp
#include <algorithm> #include <vector> namespace kruskal_impl { using namespace std; template<typename _ForwardIter, typename _ValueType> pair<_ValueType, _ValueType> edgeFuncPolicy(_ForwardIter it); template<typename _ValueType> struct UnionFindPolicy { void merge(_ValueType a, _ValueType b); bool connected(_ValueType a, _ValueType b); }; } // kruskal_impl template<typename _HeapedContainer, typename _HeapCompare, typename _EdgeFunc, typename _UnionFind> std::vector<typename _HeapedContainer::value_type> kruskal(const size_t minimum_edge_count, _HeapedContainer edges, _HeapCompare compare, _EdgeFunc ef, _UnionFind union_sets) { using namespace std; using value_type = typename _HeapedContainer::value_type; auto min_spanning_tree = vector<value_type>{}; while (min_spanning_tree.size() < minimum_edge_count && !edges.empty()) { // the pick elem is on the back pop_heap(edges.begin(), edges.end(), compare); auto edge = ef(edges.back()); // cycle detection if (!union_sets.connected(edge.first, edge.second)) { union_sets.merge(edge.first, edge.second); min_spanning_tree.push_back(edges.back()); } edges.pop_back(); } return min_spanning_tree; }
code/greedy_algorithms/src/kruskal_minimum_spanning_tree/kruskal.py
# Part of Cosmos by OpenGenus Foundation parent = dict() rank = dict() def make_set(vertice): parent[vertice] = vertice rank[vertice] = 0 def find(vertice): if parent[vertice] != vertice: parent[vertice] = find(parent[vertice]) return parent[vertice] def union(vertice1, vertice2): root1 = find(vertice1) root2 = find(vertice2) if root1 != root2: if rank[root1] > rank[root2]: parent[root2] = root1 else: parent[root1] = root2 if rank[root1] == rank[root2]: rank[root2] += 1 def kruskal(graph): for vertice in graph["vertices"]: make_set(vertice) minimum_spanning_tree = set() edges = list(graph["edges"]) edges.sort() for edge in edges: weight, vertice1, vertice2 = edge if find(vertice1) != find(vertice2): union(vertice1, vertice2) minimum_spanning_tree.add(edge) return minimum_spanning_tree
code/greedy_algorithms/src/kruskal_minimum_spanning_tree/kruskal_using_adjacency_matrix.c
#include <stdio.h> #include <limits.h> int delete_min_edge(int *u, int *v, int c[][1024], int n, int *e) { int min = INT_MAX; int i, j; for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) if (c[i][j] < min && c[i][j] != -1) { min = c[i][j]; *u = i; *v = j; } c[*u][*v] = -1; *e = *e - 1; return (min); } int find(int n, int parent[], int i) { while (parent[i] >= 0) i = parent[i]; return (i); } void Union(int n, int parent[], int p, int q) { int temp = parent[p] + parent[q]; if (parent[p] > parent[q]) { parent[p] = q; parent[q] = temp; } else { parent[q] = p; parent[p] = temp; } } int main() { int n; int e = 0; printf("Enter number of nodes in graph: "); scanf("%d", &n); int c[n][1024]; printf("Enter cost matrix: \n"); int i, j; for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) { scanf("%d", &c[i][j]); if (c[i][j] != -1) ++e; } e = e / 2; int t[n - 1][2]; int parent[n]; for (i = 0; i < n; i++) parent[i] = -1; int mincost = 0; int u, v, p, q; i = 0; while (i < n - 1 && e > 0) { int min = delete_min_edge(&u, &v, c, n, &e); p = find(n, parent, u); q = find(n, parent, v); if (p != q) { t[i][0] = u; t[i][1] = v; ++i; mincost += min; Union(n, parent, p, q); } } if(i != n - 1) printf("There is no spanning tree\n"); else { printf("Minimum Spanning Tree:- \n"); for (i = 0; i < n - 1; ++i) printf("%d----%d \n", t[i][0], t[i][1]); printf("Mincost: %d \n", mincost); } }
code/greedy_algorithms/src/min_lateness/README.md
# Scheduling tasks to minimize maximum lateness Given *n* tasks with their respective starting and finishing time, we would like to schedule the jobs in an order such that the maximum lateness for any task is minimized. Taking in consideration various possible greedy strategies, we at last decide that choosing jobs with nearest deadline gives best results. The algorithm for same can be devised as: 1. Sort the requests by their deadline 2. min_lateness = 0 3. start_time = 0 4. for i = 0 -> n 5. min_lateness = max(min_lateness, (t[i] + start_time) - d[i]) 6. start_time += t[i] 7. return min_lateness; **Complexity** * Time Complexity: O(nlogn) * Space Complexity: O(1) <p align="center"> For more insights, refer to <a href="https://iq.opengenus.org/scheduling-to-minimize-lateness/">Scheduling to minimize lateness</a> </p> --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/greedy_algorithms/src/min_lateness/min_lateness.cpp
#include <bits/stdc++.h> using namespace std; class Request { public: int deadline, p_time; bool operator < (const Request & x) const { return deadline < x.deadline; } }; int main() { int n, i, finish_time, start_time, min_lateness, temp; cout << "Enter the number of requests: "; cin >> n; // no. of requests Request r[n]; cout << "Enter the deadline and processing time of each request: "; for (i = 0; i < n; i++) // deadline and processing time of each job cin >> r[i].deadline >> r[i].p_time; sort(r, r + n); // sort jobs in increasing order of deadline start_time = 0; min_lateness = 0; for (i = 0; i < n; i++) { min_lateness = max((r[i].p_time + start_time) - r[i].deadline, min_lateness); start_time += r[i].p_time; } cout << "Maximum lateness of schedule: " << min_lateness; return 0; }
code/greedy_algorithms/src/min_operation_to_make_gcd_k/README.md
# Minimum Number of Operations to Change GCD of given numbers to *k* GCD refers to the *greatest common factor* of two or more numbers. For ex: GCD of 10, 25 is 5. We are interested in finding minimum number of operations to change the GCD of given numbers to *k* where an operation could be either an increment or decrement of array element by 1. The problem could be solved by shifting the array elements to nearest multiple of *k* and changing the minimum value in array to *k*. The Pseudocode for same will be: 1. Sort the array 2. For i = 1 to n - 1 3. No_of_operations += min(arr[i] % k, k - arr[i] % k) 4. If arr[0] > k, 5. No_of_operations += arr[0] - k else 6. No_of_operations += k - arr[0] ## Complexity * Time Comlexity: O(nlogn) * Space Complexity: O(1) For more explanations, refer to <a href = "https://iq.opengenus.org/minimum-operations-to-make-gcd-k/">Minimum Number of Operations to Change GCD of given numbers to *k*</a>
code/greedy_algorithms/src/min_operation_to_make_gcd_k/min_operation.cpp
#include <bits/stdc++.h> using namespace std; int main() { int n; // no. of elements in array int k; // new GCD cout << "Enter number of elements in array: "; cin >> n; cout << "\nEnter the array: "; int arr[n]; // array for(int i = 0 ; i < n ; i++) cin >> arr[i]; cout << "\nEnter value of k: "; cin >> k; if(k == 0) { cout << "\nInvalid value for gcd"; return 0; } sort(arr, arr + n); int min_operation = 0; for(int i = 1 ; i < n ; i++) min_operation += min(arr[i] % k, k - (arr[i] % k)); //shift towards closest multiple if(arr[0] > k) min_operation += arr[0] - k; else min_operation += k - arr[0]; cout << "\nMinimum Number of Operations: " << min_operation; return 0; }
code/greedy_algorithms/src/minimum_coins/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) ## Minimum Coins The **Minimum Coins** tackles the [Change-making problem](https://en.wikipedia.org/wiki/Change-making_problem). It takes a value V and a set of coin's denomination D. Supposing we have infinite supply of each denomination, the algorithm returns the minimum set of coins C that makes the value V. ### The algorithm in plain english: Assuming the set D is sorted in descending order Foreach denomination in D While value V is greater than or equal to the current denomination value Add the current denomination value to the set of coins C Subtract the current denomination value from the value V ### Practical example Given V = 98; D = {50, 25, 10, 5, 1} and C = {} Loop 0-0: V = 48 and C = {50} Loop 1-0: V = 23 and C = {50, 25} Loop 2-0: V = 13 and C = {50, 25, 10} Loop 2-1: V = 3 and C = {50, 25, 10, 10} Loop 3-0: V = 3 and C = {50, 25, 10, 10} Loop 4-0: V = 2 and C = {50, 25, 10, 10, 1} Loop 4-1: V = 1 and C = {50, 25, 10, 10, 1, 1} Loop 4-2: V = 0 and C = {50, 25, 10, 10, 1, 1, 1} END.
code/greedy_algorithms/src/minimum_coins/minimum_coins.c
#include <stdio.h> int main() { printf("Enter Number of Denominations \n"); int n, i; scanf("%d", &n); int denominations[n], frequency[n]; for(i = 0; i < n; i++) frequency[i] = 0; printf("Enter Denominations in descending order \n"); for(i = 0; i < n; i++) scanf("%d", &denominations[i]); printf("Enter Bill \n"); int bill; scanf("%d", &bill); i = 0; while (bill > 0 && i < n) { frequency[i] = bill / denominations[i]; bill = bill - (frequency[i] * denominations[i]); i++; } if (bill == 0 ) for(i = 0; i < n; i++) printf("%d * %d \n", denominations[i], frequency[i]); else printf("Bill cannot be paid \n"); return (0); }
code/greedy_algorithms/src/minimum_coins/minimum_coins.cpp
/* Part of Cosmos by OpenGenus Foundation */ /* This file uses features only available on C++11. * Compile using -std=c++11 or -std=gnu++11 flag. */ #include <iostream> #include <vector> std::vector<unsigned int> minimum_coins(int value, std::vector<unsigned int> denominations) { std::vector<unsigned int> result; // Assuming denominations is sorted in descendig order for (int cur_denom : denominations) while (cur_denom <= value) { result.push_back(cur_denom); value -= cur_denom; } return result; } // Testing int main() { std::vector<unsigned int> result = minimum_coins(191, {100, 50, 25, 10, 5, 1}); for (auto i = result.begin(); i != result.end(); ++i) std::cout << *i << " "; std::cout << std::endl; return 0; }
code/greedy_algorithms/src/minimum_coins/minimum_coins.go
package main import ( "fmt" ) type Scenario struct { Value int Denoms []int Result []int } func main() { scenarios := []Scenario{ Scenario{Value: 100, Denoms: []int{50, 25, 10, 5, 1}, Result: []int{50, 50}}, Scenario{Value: 101, Denoms: []int{50, 25, 10, 5, 1}, Result: []int{50, 50, 1}}, Scenario{Value: 77, Denoms: []int{50, 25, 10, 5, 1}, Result: []int{50, 25, 1, 1}}, Scenario{Value: 38, Denoms: []int{50, 25, 10, 5, 1}, Result: []int{25, 10, 1, 1, 1}}, Scenario{Value: 17, Denoms: []int{50, 25, 10, 5, 1}, Result: []int{10, 5, 1, 1}}, Scenario{Value: 3, Denoms: []int{50, 25, 10, 5, 1}, Result: []int{1, 1, 1}}, Scenario{Value: 191, Denoms: []int{100, 50, 25, 10, 5, 1}, Result: []int{100, 50, 25, 10, 5, 1}}, } for _, s := range scenarios { result := getMinimumCoins(s.Value, s.Denoms) if fmt.Sprint(result) != fmt.Sprint(s.Result) { fmt.Println("Test Failed: Value: ", s.Value, ", Denominations: ", s.Denoms, ", Expected Result: ", s.Result, ", Actual Result: ", result) } } } func getMinimumCoins(value int, denoms []int) []int { var result []int for _, d := range denoms { for { if value < d { break } result = append(result, d) value -= d } } return result }
code/greedy_algorithms/src/minimum_coins/minimum_coins.js
/* Part of Cosmos by OpenGenus Foundation */ function minimumCoins(value, denominations) { var result = []; // Assuming denominations is sorted in descendig order for (var i = 0; i < denominations.length; i++) { var cur_denom = denominations[i]; while (cur_denom <= value) { result.push(cur_denom); value -= cur_denom; } } return result; } Array.prototype.equals = function(other) { if (!other || !(other instanceof Array)) { return false; } if (this.length != other.length) { return false; } for (var i = 0; i < this.length; i++) { if (this[i] != other[i]) { return false; } } return true; }; function test() { var scenarios = [ { value: 100, denoms: [50, 25, 10, 5, 1], result: [50, 50] }, { value: 101, denoms: [50, 25, 10, 5, 1], result: [50, 50, 1] }, { value: 77, denoms: [50, 25, 10, 5, 1], result: [50, 25, 1, 1] }, { value: 38, denoms: [50, 25, 10, 5, 1], result: [25, 10, 1, 1, 1] }, { value: 17, denoms: [50, 25, 10, 5, 1], result: [10, 5, 1, 1] }, { value: 3, denoms: [50, 25, 10, 5, 1], result: [1, 1, 1] }, { value: 191, denoms: [100, 50, 25, 10, 5, 1], result: [100, 50, 25, 10, 5, 1] } ]; scenarios.forEach(function(scenario) { var actual = minimumCoins(scenario.value, scenario.denoms); if (!scenario.result.equals(actual)) { console.error( "Test Failed: Value: " + scenario.value + ", Denominations: " + scenario.denoms + ", Expected Result: " + scenario.result + ", Actual Result: " + actual ); } }, this); } test();
code/greedy_algorithms/src/minimum_coins/minimum_coins.py
# Part of Cosmos by OpenGenus Foundation def minimum_coins(value, denominations): result = [] # Assuming denominations is sorted in descendig order for cur_denom in denominations: while cur_denom <= value: result.append(cur_denom) value = value - cur_denom return result # Testing def test(): scenarios = [ [100, [50, 25, 10, 5, 1], [50, 50]], [101, [50, 25, 10, 5, 1], [50, 50, 1]], [77, [50, 25, 10, 5, 1], [50, 25, 1, 1]], [38, [50, 25, 10, 5, 1], [25, 10, 1, 1, 1]], [17, [50, 25, 10, 5, 1], [10, 5, 1, 1]], [3, [50, 25, 10, 5, 1], [1, 1, 1]], [191, [100, 50, 25, 10, 5, 1], [100, 50, 25, 10, 5, 1]], ] for scenario in scenarios: actual = minimum_coins(scenario[0], scenario[1]) if actual != scenario[2]: message = "Test Failed: Value: {}, Denominations: {}, Expected Result: {}, Actual Result: {}".format( scenario[0], scenario[1], scenario[2], actual ) print(message) test()
code/greedy_algorithms/src/minimum_coins/minimumcoins.hs
module MinimumCoins where -- Part of Cosmos by OpenGenus safeHead [] = Nothing safeHead (x:xs) = Just x -- takes denominations in decreasing order -- returns valid solution if such exists minCoins :: Int -> [Int] -> Maybe [Int] minCoins 0 _ = Just [] minCoins n denominations = let next = safeHead $ filter (<= n) denominations in next >>= \x -> (x:) <$> minCoins (n - x) denominations usDenom = [50, 25, 10, 5, 1] -- simple test main = print $ minCoins 77 usDenom == Just [50, 25, 1, 1]
code/greedy_algorithms/src/minimum_coins/minimumcoins.java
// Part of Cosmos by OpenGenus Foundation import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class MinimumCoins { private static List<Integer> minimumCoins(Integer value, List<Integer> denominations) { List<Integer> result = new ArrayList<>(); // Assuming list of denominations is sorted in descending order for(Integer curDenom : denominations) { while (curDenom <= value){ result.add(curDenom); value -= curDenom; } } return result; } public static void main(String[] args) { List<TestScenario> scenarios = Arrays.asList( new TestScenario(100, Arrays.asList(50, 25, 10, 5, 1), Arrays.asList(50, 50)), new TestScenario(101, Arrays.asList(50, 25, 10, 5, 1), Arrays.asList(50, 50, 1)), new TestScenario(77, Arrays.asList(50, 25, 10, 5, 1), Arrays.asList(50, 25, 1, 1)), new TestScenario(38, Arrays.asList(50, 25, 10, 5, 1), Arrays.asList(25, 10, 1, 1, 1)), new TestScenario(17, Arrays.asList(50, 25, 10, 5, 1), Arrays.asList(10, 5, 1, 1)), new TestScenario(3, Arrays.asList(50, 25, 10, 5, 1), Arrays.asList(1, 1, 1)), new TestScenario(191, Arrays.asList(100, 50, 25, 10, 5, 1), Arrays.asList(100, 50, 25, 10, 5, 1)) ); for (TestScenario scenario : scenarios) { List<Integer> actual = minimumCoins(scenario.value, scenario.denoms); if (!actual.equals(scenario.result)) { System.out.println("Test Failed: Value: " + scenario.value + ", Denominations: " + scenario.denoms + ", Expected Result: " + scenario.result + ", Actual Result: " + actual); } } } private static class TestScenario { public int value; public List<Integer> denoms; public List<Integer> result; public TestScenario(int value, List<Integer> denoms, List<Integer> result) { this.value = value; this.denoms = denoms; this.result = result; } } }
code/greedy_algorithms/src/prim_minimum_spanning_tree/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/greedy_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.c
#include <stdio.h> #include <limits.h> int find_min_edge(int *k, int *l, int n, int c[][1024], int *e) { int min = INT_MAX; int i, j; for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) if (c[i][j] < min) { min = c[i][j]; *k = i; *l = j; } *e = *e - 1; return (min); } int find_new_index(int c[][1024], int near[], int n, int *e) { int min=INT_MAX, index; int i; for (i = 0; i < n; ++i) if (near[i] != 0 && c[i][near[i]] < min) { min = c[i][near[i]]; index = i; } *e = *e - 1; return (index); } int main() { int n; printf("Enter number of nodes in graph: "); scanf("%d", &n); int e = n * (n - 1); int c[n][1024]; printf("Enter cost matrix: \n"); int i, j; for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) { scanf("%d", &c[i][j]); if (c[i][j] == -1) { c[i][j] = INT_MAX; --e; } } e = e / 2; int t[n - 1][2]; //output edges int near[n]; int k, l; int mincost = 0; mincost += find_min_edge(&k, &l, n, c, &e); t[0][0] = k; t[0][1] = l; for (i = 0; i < n; ++i) { if (c[i][l] < c[i][k]) near[i] = l; else near[i] = k; } near[k] = near[l] = 0; for (i = 1; i < n - 1, e > 0; ++i) { int index = find_new_index(c, near, n, &e); t[i][0] = index; t[i][1] = near[index]; mincost += c[index][near[index]]; near[index] = 0; int k; for (k = 0; k < n; ++k) if (near[k] != 0 && c[k][near[k]] > c[k][index]) near[k] = index; } if(i != n - 1) printf("There is no spanning tree\n"); else { printf("Minimum Spanning Tree:- \n"); for (i = 0; i < n - 1; ++i) printf("%d----%d \n", t[i][0], t[i][1]); printf("Mincost: %d \n", mincost); } }
code/greedy_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.cpp
#include <iostream> #include <vector> #include <queue> #include <functional> #include <utility> // Part of Cosmos by OpenGenus Foundation using namespace std; const int MAX = 1e4 + 5; typedef pair<long long, int> PII; bool marked[MAX]; vector <PII> adj[MAX]; long long prim(int x) { priority_queue<PII, vector<PII>, greater<PII>> Q; int y; long long minimumCost = 0; PII p; Q.push(make_pair(0, x)); while (!Q.empty()) { // Select the edge with minimum weight p = Q.top(); Q.pop(); x = p.second; // Checking for cycle if (marked[x] == true) continue; minimumCost += p.first; marked[x] = true; for (size_t i = 0; i < adj[x].size(); ++i) { y = adj[x][i].second; if (marked[y] == false) Q.push(adj[x][i]); } } return minimumCost; } int main() { int nodes, edges, x, y; long long weight, minimumCost; cin >> nodes >> edges; for (int i = 0; i < edges; ++i) { cin >> x >> y >> weight; adj[x].push_back(make_pair(weight, y)); adj[y].push_back(make_pair(weight, x)); } // Selecting 1 as the starting node minimumCost = prim(1); cout << minimumCost << endl; return 0; }
code/greedy_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.hs
-- Author: Matthew McAlister -- Title: Prim's Minimum Spanning Tree Algorithm in Haskell import qualified Data.List as List type Edge = (Char, Char, Int) type Graph = [Edge] -- This is a sample graph that can be used. -- graph :: Graph -- graph = [('a','b',4),('a','h',10),('b','a',4),('b','c',8),('b','h',11),('c','b',8),('c','d',7),('c','f',4),('c','i',2),('d','c',7),('d','e',9),('d','f',14),('e','d',9),('e','f',10),('f','c',4),('f','d',14),('f','e',10),('f','g',2),('g','f',2),('g','h',1),('g','i',6),('h','a',10),('h','b',11),('h','g',1),('h', 'i',7),('i','c',2),('i','g',6),('i','h',7)] prim :: Graph -> Graph prim g = List.delete ('a','z', 0) (treeBuilder g "" (getGraphNodes g)) weight :: Graph -> Int weight g = weight' g weight':: Graph -> Int -- ^ Returns the weight of the MST weight' [] = 0; weight' (g:gs) = third g + weight' gs first :: Edge -> Char -- ^ Returns the first value from the tuple first (x,_,_) = x second :: Edge -> Char -- ^ Returns the second value from the tuple second (_,x,_) = x third :: Edge -> Int -- ^ Returns the third value from the tuple third (_,_,x) = x lowestWeight :: [Edge] -> Edge -- ^ Returns the Edge with the lowest weight from a list of Edges lowestWeight [] = ('a','z',0) lowestWeight (v:vs) = determineLowerWeight v (if null vs then v else lowestWeight vs) determineLowerWeight :: Edge -> Edge -> Edge -- ^ Returns the Edge with the lower weight determineLowerWeight m n | third m < third n = m | third n < third m = n | third n == third m = m reverseEdges :: [Edge] -> [Edge] -- ^ Returns a [Edge] with the first and second reversed reverseEdges [] = [] reverseEdges (e:es) = [reverseEdge e] ++ reverseEdges es ++ [] reverseEdge :: Edge -> Edge -- ^ Returns an Edge with the first and second reversed reverseEdge e = (second e, first e, third e) getGraphNodes :: Graph -> [Char] -- ^ Builds a list of unique Nodes getGraphNodes [] = [] getGraphNodes (g:gs) = List.nub (first g:second g:[] ++ getGraphNodes gs ++ []) getConnectedEdges :: [Char] -> Graph -> [Edge] -- ^ Returns a list of Edges connected to the supplied Node from the supplied Graph getConnectedEdges c g = [x | x <- g, first x `elem` c || second x `elem` c] reduceGraph :: Graph -> Graph -- ^ Returns a Graph with unique Edges by comparing the current edge to the reverse of all other Edges reduceGraph [] = [] reduceGraph g = reduceGraph' g ++ reduceGraph (tail g) ++ [] reduceGraph' :: [Edge] -> [Edge] -- ^ Compares this Edge to the reverse of the other Edges and returns the appropriate unique output reduceGraph' (g:gs) = if notElem g (reverseEdges gs) then [g] else [] removeUsedNodeFromList :: Char -> [Char] -> [Char] removeUsedNodeFromList c l = List.delete c l treeBuilder :: Graph -> [Char] -> [Char] -> [Edge] -- ^ Take a Graph, a list of Chars that are USED, and a list of Chars that are UNUSED and returns a tree treeBuilder g cus cun = if null cun then [] else [lowestWeightEdge g cus cun] ++ treeBuilder g (treeBuilder'addList g cus cun) (treeBuilder'delList g cus cun) ++ [] treeBuilder'addList :: Graph -> [Char] -> [Char] -> [Char] -- ^ Adds the Nodes from the lowestWeightEdge to the USED list treeBuilder'addList g cus cun = addEdgeNodesToList (lowestWeightEdge g cus cun) cus treeBuilder'delList :: Graph -> [Char] -> [Char] -> [Char] -- ^ Deletes the Nodes from the lowestWeightEdge to the UNUSED list treeBuilder'delList g cus cun = delEdgeNodesFromList (lowestWeightEdge g cus cun) cun addEdgeNodesToList :: Edge -> [Char] -> [Char] -- ^ Adds the Nodes from an Edge to a List of Chars addEdgeNodesToList n l = first n: second n : l delEdgeNodesFromList :: Edge -> [Char] -> [Char] -- ^ Deletes the Nodes from an Edge from a List of Chars delEdgeNodesFromList n l = delFirst n (delSecond n l) delFirst :: Edge -> [Char] -> [Char] -- ^ Deletes the first Edge node from the list delFirst n l = List.delete (first n) l delSecond :: Edge -> [Char] -> [Char] -- ^ Deletes the second Edge node from the list delSecond n l = List.delete (second n) l lowestWeightEdge :: Graph -> [Char] -> [Char] -> Edge -- ^ From a Graph, a list of USED nodes, and a list of UNUSED nodes, the lowest edge weight is determined lowestWeightEdge g cus cun = lowestWeight (getEdges g cus cun) getEdges :: Graph -> [Char] -> [Char] -> [Edge] -- ^ From a Graph, a list of USED nodes, and a list of UNUSED nodes, the connected Edges are determined getEdges g cus cun = [x | x <- getConnectedEdges cus g, first x `elem` cun || second x `elem` cun]
code/greedy_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.py
import sys from heap import Heap def primsMSTAlgorithm(adjList): """ Prim's Minimum Spanning Tree (MST) Algorithm It finds a MST of an undirected graph Args: adjList: a dictionary, as a realization of an adjacency list, in the form adjList[vertex1] = [(vertex21,weight1,edgeId1), (vertex22,weight2,edgeId2), ...] Note: Every vertex should have an entry in the adjList Returns: mst: a set of all the edges (ids) that constitute the minimum spanning tree """ def updateHeap(v): """ Updates the heap with entries of all the vertices incident to vertex v that was recently explored Args: v: a vertex that was recently explored """ for vertex, weight, edgeID in adjList[v]: if vertex not in explored: # Updates (!) the weight and reinserts the element into the heap element = unexplored.delete(vertex) if element and element[0] < weight: unexplored.insert(element) else: unexplored.insert((weight, vertex, edgeID)) source = list(adjList.keys())[ 0 ] # Chooses an arbitrary vertex as the starting point of the algorithm # unexplored: a heap with elements of the following format (minWeight, destinationVertex, edgeID) unexplored, explored, mst = Heap(), set([source]), set() updateHeap(source) while unexplored.length(): weight, vertex, edgeID = unexplored.extractMin() explored.add(vertex) mst.add(edgeID) updateHeap(vertex) return mst def graph(filename): """ Builds an adjacency list and an incidence list Args: filename: the name of the file with a representation of the graph. The first line of the file specifies the number of the vertices and the number of the edges. The file is assumed to specify the edges of the graph in the following format: v w e, where v is one vertex of the associated edge, w is the other vertex, and e is the edge's weight Returns: adjList: a dictionary, as a realization of an adjacency list, in the form adjList[vertex1] = [(vertex21,weight1,edgeId1), (vertex22,weight2,edgeId2), ...] edgeList: a dictionary, as a realization of an incidence list, in the form edgeList[edgeId] = (vertex1,vertex2,weight) """ adjList, edgeList = {}, {} with open(filename, "r") as f: numbers = f.readline().split() numVertices, numEdges = int(numbers[0]), int(numbers[1]) edgeID = 1 for line in f: edge = line.split() vertex1, vertex2, weight = int(edge[0]), int(edge[1]), int(edge[2]) if vertex1 in adjList: adjList[vertex1].append((vertex2, weight, edgeID)) else: adjList[vertex1] = [(vertex2, weight, edgeID)] if vertex2 in adjList: adjList[vertex2].append((vertex1, weight, edgeID)) else: adjList[vertex2] = [(vertex1, weight, edgeID)] edgeList[edgeID] = (vertex1, vertex2, weight) edgeID += 1 return adjList, edgeList if __name__ == "__main__": if len(sys.argv) < 2: sys.exit("Error: No filename") filename = sys.argv[1] adjList, edgeList = graph(filename) mst = primsMSTAlgorithm(adjList) cost = 0 # Computes the sum of the weights of all edges in the MST for edgeID in mst: cost += edgeList[edgeID][2] print(cost)
code/greedy_algorithms/src/warshall/warshalls.c
/* * Compute the transitive closure of a given directed graph * using Warshall's algorithm. */ #include <stdio.h> #include <math.h> #define max(a, b) (a > b ? a : b) void warshal(int p[10][10], int n) { int i, j, k; for(k = 1; k <= n; k++) for(i = 1; i <= n; i++) for(j = 1; j <= n; j++) p[i][j] = max(p[i][j], p[i][k] && p[k][j]); } int main() { int p[10][10] = {0}, n, i, j; printf("Enter the size of matrix\n"); scanf("%d", &n); printf ("Enter the Adjacency matrix\n"); for(i = 1; i <= n; i++) for(j = 1; j <= n; j++) scanf("%d", p[i][j]); warshal(p, n); printf("\n Transitive closure: \n"); for(i = 1; i <= n; i++) { for(j = 1; j <= n; j++) printf("%d\t", p[i][j]); printf("\n"); } return (0); }
code/greedy_algorithms/src/water_connection/water_connection_algorithm.cpp
//Part of OpenGenus Cosmos #include <iostream> #include <vector> #include<cstring> using namespace std; int houses, pipes; // this array stores the // ending vertex of pipe int rd[1100]; // this array stores the value // of diameters between two pipes int wt[1100]; // this array stores the // starting end of pipe int cd[1100]; // these vectors are used // to store the resulting output vector<int> a(10); vector<int> b(10); vector<int> c(10); int ans; int dfs(int w) { if (cd[w] == 0) return w; if (wt[w] < ans) ans = wt[w]; return dfs(cd[w]); } // this function performs calculations void solve(int arr[][3]) { int i = 0; while (i < pipes) { int q = arr[i][0], h = arr[i][1], t = arr[i][2]; cd[q] = h; wt[q] = t; rd[h] = q; i++; } a.clear(); b.clear(); c.clear(); for (int j = 1; j <= houses; ++j) /* If a pipe has no ending vertex but has starting vertex i.e is an outgoing pipe then we need to start DFS with that vertex */ if (rd[j] == 0 && cd[j]) { ans = 1000000000; int w = dfs(j); // now,we fill the details of component // in final resulting array a.push_back(j); b.push_back(w); c.push_back(ans); } cout << a.size() << endl; for (int j = 0; j < a.size(); ++j) cout << a[j] << " " << b[j] << " " << c[j] << endl; } int main() { houses = 9, pipes = 6; memset(rd, 0, sizeof(rd)); memset(cd, 0, sizeof(cd)); memset(wt, 0, sizeof(wt)); int arr[][3] = { { 7, 4, 98 }, { 5, 9, 72 }, { 4, 6, 10 }, { 2, 8, 22 }, { 9, 7, 17 }, { 3, 1, 66 } }; solve(arr); return 0; }
code/greedy_algorithms/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/greedy_algorithms/test/kruskal_minimum_spanning_tree/test_kruskal.cpp
#include "../../src/kruskal_minimum_spanning_tree/kruskal.cpp" #include "../../../data_structures/src/tree/multiway_tree/union_find/union_find_dynamic.cpp" #include <iostream> using namespace std; pair<int, int> edgeFunc(pair<pair<int, int>, int> edge) { return edge.first; } class HeapCompare { public: bool operator()(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) { return a.second > b.second; } }; int main() { using namespace std; vector<int> vec{1, 2, 3, 4, 5, 6, 7}; /* * 1---(12)----2 * / / \ * / / \ * (35) (25) (24) * / / \ * / / \ * 6 7 3 \ /\ / \ / \ / \ (15) (18) (22) (32) \ / \ / \/ \ / \ 5---(10)----4 */ vector<pair<pair<int, int>, int>> edge_weight{{{1, 2}, 12}, {{2, 3}, 24}, {{3, 4}, 32}, {{4, 5}, 10}, {{5, 6}, 15}, {{6, 1}, 35}, {{2, 7}, 25}, {{4, 7}, 22}, {{5, 7}, 18}}; make_heap(edge_weight.begin(), edge_weight.end(), HeapCompare()); auto res = kruskal(vec.size() - 1, edge_weight, HeapCompare(), edgeFunc, UnionFind<int>()); // print auto it = res.begin(); while (it != res.end()) { cout << it->first.first << "\t" << it->first.second << endl; ++it; } /* * 1---(12)----2 * / \ * / \ * (25) (24) * / \ * / \ * 6 7 3 \ / \ / \ (15) (18) \ / \/ \ 5---(10)----4 */ return 0; }
code/html/README.md
# HTML (Hyper Text Markup Language) HTML is the standard markup language for creating web pages. Current HTML version is HTML5. Standard Syntax of HTML5 is following: ```html <!DOCTYPE html> <html> <head> <title> Title for top of address bar </title> </head> <body> <!--HTML Tags and content to display on webpage--> </body> </html> ``` ## Table of contents [CSS](css/)
code/html/bootstrap/Readme.MD
Tables are a fundamental part of HTML and CSS is used to format tables nicely. Bootstrap being a CSS framework provides several classes to design HTML tables easily. Many different types of Bootstrap tables are there. In the 'tables.html' file, few examples are shown. Learn more about Bootstrap tables in this article: [Bootstrap-table](https://iq.opengenus.org/bootstrap-tables)
code/html/bootstrap/tables.html
<!DOCTYPE html> <html lang="en"> <head> <title>bootstrap table</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Default Table</h2> <table class="table"> <thead> <tr> <th>First name</th> <th>Last name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Jon</td> <td>Doe</td> <td>21</td> </tr> <tr> <td>Jon</td> <td>Smith</td> <td>22</td> </tr> </tbody> </table> </div> <div class="container"> <h2>Bordered Table</h2> <table class="table-bordered" style="width:100%"> <thead> <tr> <th>First name</th> <th>Last name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Jon</td> <td>Doe</td> <td>21</td> </tr> <tr> <td>Jon</td> <td>Smith</td> <td>22</td> </tr> </tbody> </table> </div> <div class="container"> <h2>Bordered Table</h2> <table class="table-striped" style="width:100%"> <thead> <tr> <th>First name</th> <th>Last name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Jon</td> <td>Doe</td> <td>21</td> </tr> <tr> <td>Jon</td> <td>Smith</td> <td>22</td> </tr> </tbody> </table> </div> <div class="container"> <h2>Contextual Classes</h2> <table class="table"> <thead> <tr> <th>Indication</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Default</td> <td>Jon Doe</td> <td>22</td> </tr> <tr class="success"> <td>Success</td> <td>Jon Doe</td> <td>24</td> </tr> <tr class="danger"> <td>Danger</td> <td>Jon Smith</td> <td>20</td> </tr> <tr class="info"> <td>Info</td> <td>Jon Edwards</td> <td>29</td> </tr> <tr class="warning"> <td>Warning</td> <td>Jon Doe</td> <td>25</td> </tr> <tr class="active"> <td>Active</td> <td>Jon Doe</td> <td>27</td> </tr> </tbody> </table> </div> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">Firstname</th> <th scope="col">Lastname</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <td>Jon</td> <td>Doe</td> <td>21</td> </tr> <tr> <td>Jon</td> <td>Smith</td> <td>22</td> </tr> </tbody> </table> <body> <div class="container"> <h2>Bordered Table</h2> <table class="table-bordered" style="width:100%"> <thead> <tr> <th>First name</th> <th>Last name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Jon</td> <td>Doe</td> <td>21</td> </tr> <tr> <td>Jon</td> <td>Smith</td> <td>22</td> </tr> </tbody> </table> </div> </body> </body> </html>
code/html/css/Hover/src/Hover_effect.html
/* Part of Cosmos by OpenGenus Foundation */ <!DOCTYPE html> <html> <head> <title>HOVER EFFECT</title> <style> h1:hover{ color:red; font-size:50px; } </style> </head> <body> <h1>Move the cursor over this text to see the effects of Hover property</h1> </body> </html>
code/html/css/Layout/normalflow.html
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Normal Flow</title> <script> body { width: 500px; margin:15px; padding:10px; } p { background: green; border: 2px solid black; padding: 10px; margin: 10px; } .block{ display: block; } .inline{ display: inline; } </script> </head> <body> <h1>Normal Flow</h1> <div > <p>Block</p> <p>The elements that appear one below the other are described as block elements</p> <p class="block">Element 1</p> <p class="block">Element 2</p> <p class="block">Element 3</p> </div> <div class="inline"> <p>Inline Elements</p> <p>Appear one beside the other, like the individual words in a paragraph.</p> <p class="inline">Element 1</p> <p class="inline">Element 2</p> <p class="inline">Element 3</p> </div> </body> </html>
code/html/css/Margin/README.md
# CSS Basics: Margins ## Table of contents: [1. Setting individual side margin](src/Individual.html) [2. Shorthand property for CSS Margins](src/Shorthand_4.html) [3. Auto-Keyword](src/Auto_keyword.html) [4. Margin Inherit](src/Inherit_keyword.html) [5. Margin Collapse](src/Margin_collapse.html) CSS Margin property is used to create space between webpage border and HTML Element's border (if defined using CSS Border property). **Syntax:** ```html <style> #idvalue { border: {width} {style} {color}; margin: {value} } </style> <{html_element} id="idvalue"> {content} </{html_element}> ``` **Example:** ```html <style> #margin1 { border: 2px solid black; text-align:center; margin: 100px; } </style> <h1 id="margin1"> Generic Heading with defined margin</h1> <h1> Normal heading </h1> ``` The Margin property can be defined in following ways: 1. Length 2. Percentage 3. Auto 4. Inherit
code/html/css/Margin/src/Auto_keyword.html
<style> #el { width: 250px; border: 8px double black; margin: auto; } </style> <h1 id="el"> Generic Heading </h1>
code/html/css/Margin/src/Individual.html
<style> #el { border: 8px double black; margin-top: 2%; margin-right: 300px; margin-bottom: 0px; margin-left: 250px; } </style> <h1 id="el"> Generic Heading</h1>
code/html/css/Margin/src/Inherit_keyword.html
<style> div { border: 8px double black; margin: 40px; } h1 { border: 4px dotted black; margin: inherit; } </style> <div> <h1> Generic Heading </h1> </div>
code/html/css/Margin/src/Margin.html
<style> #margin1 { border: 2px solid black; text-align:center; margin: 100px; } </style> <h1 id="margin1"> Generic Heading with defined margin</h1> <h1> Normal heading </h1>
code/html/css/Margin/src/Margin_collapse.html
<style> #upper { border: 8px dashed black; margin-bottom: 80px; } #lower { border: 12px double yellow; margin-top: 40px; } </style> <h1 id="upper"> Heading on top element </h1> <h1 id="lower"> Heading on bottom element </h1>
code/html/css/Margin/src/Margin_length.html
<style> #el { border: 2px solid black; margin: 40px 100px 0px 80px; } </style> <h1 id="el"> Generic Heading with margin</h1>
code/html/css/Margin/src/Margin_value_percentage.html
<style> #el { border: 8px double black; margin: 2%; } </style> <h1 id="el"> Heading </h1>
code/html/css/Margin/src/Shorthand_1.html
<style> #el { border: 10px double black; margin: 200px; } </style> <h1 id="el"> Generic Heading </h1>
code/html/css/Margin/src/Shorthand_2.html
<style> #el { border: 10px double black; margin: 10px 100px; } </style> <h1 id="el"> Generic Heading </h1>
code/html/css/Margin/src/Shorthand_3.html
<style> #el { border: 10px double black; margin: 10px 400px 0px; } </style> <h1 id="el"> Generic Heading </h1>
code/html/css/Margin/src/Shorthand_4.html
<style> #el { border: 10px double black; margin: 10px 100px 0px 400px; } </style> <h1 id="el"> Generic Heading </h1>
code/html/css/Padding/README.md
# CSS Basics: Padding ## Table of contents [1. CSS Padding for Individual Sides](src/Individual_sides.html) [2. Shorthand Property](src/Shorthand_1.html) [3. Inherit Keyword](src/Inherit.html) [4. CSS Box Model with Padding](src/BoxModel.html) CSS Padding property is used to create spacing between content of HTML Element and the border(if specified) around it. **Syntax:** ```html <style> HTML_element { border: {width} {style} {color}; padding: {value(s)}; } </style> <HTML_element> Content </HTML_element> ``` **Example:** ```html <style> #el { border: 2px solid black; padding: 40px; } </style> <h1 id="el"> Heading with Padding specified </h1> <h1 style="border:2px solid black;"> Heading without padding </h1> ``` CSS Padding property takes following input as its value: * Length: Number followed by a unit (px,cm etc.) * Percentage: Number followed by % sign. * Inherit Keyword: Inherit padding value from parent HTML element.
code/html/css/Padding/src/BoxModel.html
<style> #box1 { width: 400px; padding: 40px; border: 8px double black; box-sizing: border-box; } #box2 { width: 400px; border: 8px double black; padding: 40px; } </style> <h1 id="box1"> Box with box-sizing defined</h1> <h1 id="box2"> Generic Box</h1>
code/html/css/Padding/src/Individual_sides.html
<style> h1 { border: 8px double black; padding-top: 20px; padding-right: 50px; padding-bottom: 30px; padding-left: 100px; } </style> <h1> This is a Heading for checking Padding on Individual sides where top, right, bottom and left padding are 20px, 50px, 30px and 100px respectively.</h1>
code/html/css/Padding/src/Inherit.html
<style> div { border: 8px double black; padding: 60px; } h1 { border: 2px solid black; padding: inherit; } </style> <div> <h1> Generic Heading </h1> </div>
code/html/css/Padding/src/Length.html
<style> h1 { border: 2px solid black; padding: 40px; } </style> <h1> Generic Heading with padding of 40px from border. </h1>
code/html/css/Padding/src/Padding.html
<style> #el { border: 2px solid black; padding: 40px; } </style> <h1 id="el"> Heading with Padding specified </h1> <h1 style="border:2px solid black;"> Heading without padding </h1>
code/html/css/Padding/src/Percentage.html
<style> h1 { border: 2px solid black; padding: 5%; } </style> <h1> Generic Heading </h1>
code/html/css/Padding/src/Shorthand_1.html
<style> h1 { border: 2px solid black; padding: 40px; } </style> <h1> Generic Heading </h1>
code/html/css/Padding/src/Shorthand_2.html
<style> h1 { border: 2px solid black; padding: 40px 200px; } </style> <h1> Generic Heading </h1>
code/html/css/Padding/src/Shorthand_3.html
<style> h1 { border: 2px solid black; padding: 40px 200px 100px; } </style> <h1> Generic Heading </h1>
code/html/css/Padding/src/Shorthand_4.html
<style> h1 { border: 2px solid black; padding: 40px 200px 100px 500px; } </style> <h1> Generic Heading </h1>
code/html/css/Padding/src/code.html
<style> .paragraph{ border:dotted 3px red; padding: 5%; } </style> <p>Welcome to the code: Without padding</p> <p class="paragraph">Welcome to the code: With padding</p>
code/html/css/Position/README.md
# CSS Position The CSS **position** property is used to specify the position of HTML element in the webpage. Once the position property is set to a given value/keyword. The HTML element has a defined location from which it can be shift relatively using the following keywords: * **top** * **bottom** * **left** * **right** The CSS position property can take following values: 1. Static 2. Fixed 3. Relative 4. Absolute 5. Sticky **Syntax: CSS Position** ```html <style> HTML_element { position: {keyword}; top: {value}; bottom: {value}; right: {value}; left: {value}; } </style> ``` **Example:** ```html <style> h1 { position: absolute; top: 40px; left: 100px; } </style> <h1> Generic Heading </h1> ``` **Output:** ![Position](img/Position.png)
code/html/css/Position/src/Absolute_no_ancestor.html
<style> h1 { position: absolute; top: 100px; left: 100px; } </style> <h2> Generic Heading </h2> <h1> Heading with Absolute positioning </h1>
code/html/css/Position/src/Absoulte_ancestor.html
<style> div { position: relative; top: 40px; left: 100px; } h1 { position: absolute; top: 40px; left: 50px; } </style> <div> <h2> Div Generic Element </h2> <h1> Generic Heading </h1> </div>
code/html/css/Position/src/Fixed.html
<style> img { position: fixed; top: 100px; left: 100px; } </style> <h1> Generic Heading </h1> <img src="OpenGenus.jpg" alt="OpenGenus Foundation Logo"> <pre> ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... </pre>
code/html/css/Position/src/Position.html
<style> h1 { position: absolute; top: 40px; left: 100px; } </style> <h1> Generic Heading </h1>
code/html/css/Position/src/Relative.html
<style> #head1 { position: relative; top: 40px; bottom: 100px; right: 30px; left: 100px; } </style> <h1> Generic Heading </h1> <h1 id="head1"> Heading with relative positioning </h1>
code/html/css/Position/src/Static.html
<style> h1 { position: static; top: 100px; left: 200px; } </style> <h1> Generic Heading </h1>
code/html/css/README.md
# Cascasding StyleSheets (CSS) CSS is used to add styling options to webpages written in normal HTML files. CSS style options are pairs of **property:value**. There are three ways to add CSS style options in HTML files. ## 1. Inline CSS Writing CSS style options within HTML tag. ```html <{HTML_element} style="property:value;property:value,..."> ``` ## 2. Internal CSS Writing entire CSS code in `<style>` HTML element at the `<head>` of HTML file. This method uses Id and Class attributes of HTML to define the style for those HTML elements. ```html <head> <style> HTML-element {property:value;property:value,...} #idvalue {property:value;property:value,...} .classname {property:value;property:value,...} </style> <head> ``` ## 3. External CSS Writing CSS code in an external .css file and linking it in the HTML file. The link is provided in the HTML `head` tag. ```html <head> <link rel="stylesheet" href="{path to external css file}"> </head> ``` <hr> ## Table of contents [* CSS Borders](border/) [* CSS Margins](Margin/) [* CSS Padding](Padding/) [* CSS Position](Position/) [* CSS Position: Z-index](Z_index/) [* CSS Layout](Layout/)
code/html/css/Z_index/README.md
# CSS Position: Z-index property When HTML elements are positioned explicitly, they may overlap with each other. The Z-index property is used to specify the **Stack order** of HTML elements. The higher the value of the HTML element in the stack, the more forward is its position. HTML elements can have either a positive stack or a negative stack. **Syntax** ```css z-index: auto|number|initial|inherit; ``` **Rule: An element with greater stack order is always in front of element with lower stack order.** **Note: If two elements overlap with each other and z-index is not specified explicitly, then the element defined later in the HTML source code has higher stack order.** **Note: Z-index only works on elements whose CSS position property has been defined.** ![Example](img/z_index.png)
code/html/css/Z_index/src/inherit.html
<style> div { z-index:-1; } img { position: absolute; left: 0px; top: 0px; z-index:inherit; } h1 { z-index: 1; position: absolute; top: 220px; } </style> <div> <img src="OpenGenus.jpg" alt="OpenGenus Logo"> </div> <h1> Inherit Keyword Example for CSS Z-index property </h1>
code/html/css/Z_index/src/initial.html
<style> img { position: absolute; left: 0px; top: 0px; z-index: -1; } h1 { z-index: 1; position: absolute; top: 220px; } #b1 { position:absolute; top:400px; } </style> <img src="OpenGenus.jpg" alt="OpenGenus Logo" id="img1"> <h1> Generic Heading </h1> <button onclick="function1()"> Click here to Modify Z-index of Image </button> <button onclick="function2()" id="b1"> Click here to Restore Defaults </button> <script> function function1() { document.getElementById("img1").style.zIndex=2; } function function2() { document.getElementById("img1").style.zIndex=initial; } </script>
code/html/css/Z_index/src/z_index.html
<style> img { position: absolute; left: 0px; top: 0px; z-index: -1; } h1 { z-index: 1; position: absolute; top: 220px; } </style> <img src="OpenGenus.jpg" alt="OpenGenus Logo"> <h1> This is overlap Heading over OpenGenus Logo </h1>
code/html/css/border/README.md
# CSS Basics: Borders CSS Borders are used to create border around any HTML Tag. Borders include following feature: * **Style:** The type of border you want as in solid, dashed etc. It is a compulsory attribute for border. * **width:** It defines the thickness of the border. It is an optional attribute and has inbuilt default value. * **Color:** It defines the color of the border. Default color is black. * **Radius:** A new feature supported by latest web browsers is adding a rounded edge to borders. ## Table of contents: [1. Border-style](src/Border_style.html) ![Style](img/border-style.png) [2. Border-width](src/Border_width.html) ![Width](img/Border_width2.png) [3. Border-Color](src/Border_color.html) ![Color](img/Border_color.png) [4. Individual Border](src/Individual_border.html) ![Individual](img/IndividualBorder.png) [5. Shorthand property](src/Shorthand_property.html) ![Shorthand](img/Shorthand.png) [Rounded Borders](src/Rounded_Border.html) ![Rounded](img/Rounded_border.png)
code/html/css/border/src/Border_color.html
<h1>Defining border color </h1> <h2>1) Border color with keyword </h2> <h3 style="border-style:solid;border-color:red;"> Red colored border </h3> <br><br> <h2>2) Border color with RGB value </h2> <h3 style="border-style:solid;border-color:rgb(255,0,0)"> Border with RGB value (255,0,0) ==> Red color </h3> <br><br> <h2>3) Border color with HEX Value </h2> <h3 style="border-style:solid;border-color:#ff0000"> Border with Hex value #ff0000 ==> Red color </h3>
code/html/css/border/src/Border_style.html
<h1 style="border-style:dotted;text-align:center;"> Dotted Border </h1> <h1 style="border-style:dashed;text-align:center;"> Dashed Border </h1> <h1 style="border-style:solid;text-align:center;"> Solid Border </h1> <h1 style="border-style:double;text-align:center;"> Double Border </h1> <h1 style="border-style:groove;text-align:center;"> Groove Border </h1> <h1 style="border-style:ridge;text-align:center;"> Ridge Border </h1> <h1 style="border-style:inset;text-align:center;"> Inset Border </h1> <h1 style="border-style:outset;text-align:center;"> Outset Border </h1> <h1 style="border-style:none;text-align:center;"> None Border </h1> <h1 style="border-style:hidden;text-align:center;"> Hidden Border </h1>
code/html/css/border/src/Border_width.html
<h1> Border width with keywords </h1> <h2 style="border-style:solid;border-width:thin"> Thin Border </h2> <h2 style="border-style:solid;border-width:thick"> Thick Border </h2> <h2 style="border-style:solid;border-width:medium"> Medium Border </h2> <br> <br> <h1> Border width with numerics and units </h1> <h2 style="border-style:solid;border-width: 2px;"> Border with width = 2 px </h2> <h2 style="border-style:solid;border-width: 5px;"> Border with width = 5 px </h2> <h2 style="border-style:solid;border-width: 10px;"> Border with width = 10 px </h2>
code/html/css/border/src/Individual_border.html
<style> #id1 { border-top-style: solid; border-top-width: 2px; border-top-color: black; border-bottom-style: inset; border-bottom-width: 8px; border-bottom-color: red; border-left-style: outset; border-left-width: 15px; border-left-color: green; border-right-style: dotted; border-right-width: 5px; border-right-color: blue; } </style> <h1 id="id1"> Custom Heading </h1>
code/html/css/border/src/Rounded_Border.html
<style> #generic { border: 8px solid black; text-align:center; } #round1 { border: 8px solid black; text-align:center; border-radius: 4px; } #round2 { border: 8px solid black; text-align:center; border-radius: 8px; } </style> <h1 id="generic"> Generic Border </h1> <h1 id="round1"> Round border </h1> <h1 id="round2"> More rounded edge border </h1>
code/html/css/border/src/Shorthand_property.html
<style> #border { border: 2px solid black; } </style> <h1 id="border"> Heading </h1>
code/languages/Java/2d-array-list-java.java
import java.util.ArrayList; public class TwoDimensionalArrayLists{ public static void main(String args[]) { // Creating 2D ArrayList ArrayList<ArrayList<Integer> > arrLL = new ArrayList<ArrayList<Integer> >(); // Allocating space to 0th row with the help of 'new' keyword // At 0th row, 0 gets stored in memory by default arrLL.add(new ArrayList<Integer>()); // At 0th row, modifing the default value to 13 arrLL.get(0).add(0, 13); System.out.println("2D ArrayList :"); // Printing 2D ArrayList System.out.println(arrLL); // Determining the index of element - 13 int ans = arrLL.get(0).indexOf(13); System.out.println(" Index of element 13 is "+ ans); // Determining the last index of element - 13 int ans = arrLL.get(0).lastIndexOf(13); System.out.println(" Last Index of element 13 is "+ ans); // 0th row gets deleted from the arrayList created arrLL.remove(0); // Modified arrayList is System.out.println(arrLL); // To check whether 13 present at a particular row in our ArrayList System.out.println(x.get(0).contains(13)); System.out.println(x.get(0).contains(1)); } }
code/languages/Java/2d-array.java
import java.util.Scanner; public class TwoDimensionalArray{ // Creating a user defined 2-D Array public static int[][] createarray(){ Scanner s = new Scanner(System.in); // Taking number of rows and columns in input from user System.out.println("Enter number of rows"); int rows = s.nextInt(); System.out.println("Enter number of columns"); int columns = s.nextInt(); // Declaring an 2-D Array int[][] arr = new int[rows][columns]; System.out.println("Enter element of desired matrix"); for (int i = 0; i <arr.length; i++){ for (int j = 0 ; j < arr[0].length; j++){ arr[i][j] = s.nextInt(); } } return arr; } // Printing a 2-D array public static void printarray (){ int[][] arr = createarray(); for (int i = 0; i <arr.length; i++){ for (int j = 0 ; j < arr[0].length; j++){ System.out.print(arr[i][j] + " "); } System.out.println(); } } public static void main(String args[]) { printarray(); } }
code/languages/Java/Handlingexceptions/Handlingexp.java
import java.io.*; public class example { public static void main(String[] args) { try { int n=6; System.out.print("a"); int val = n / 0; throw new IOException(); } catch(EOFException e) { System.out.printf("b"); } catch(ArithmeticException e) { System.out.printf("c"); } catch(IOException e) { System.out.printf("d"); } catch(Exception e) { System.out.printf("e"); } } }
code/languages/Java/Kadane_algo.java
import java.util.Scanner; class Kadane_Algo{ public static void main (String[] args) { int[] array = {-2, -3, 4, -1, -2, 1, 5, -3}; int size = array.length; int maximum_overall = Integer.MIN_VALUE, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + array[i]; if (maximum_overall < max_ending_here) maximum_overall = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } System.out.println("Maximum continuous sum of subarray is " + maximum_overall); } } OUTPUT Maximum continuous sum of subarray is 7
code/languages/Java/README_Kadane_Algo.md
Kadane's Algorithm is commonly known for **Finding the largest sum of a subarray** in linear time O(N). A **Subarray** of an n-element array is an array composed from a contiguous block of the original array's elements. For example, if array = [1,2,3] then the subarrays are [1], [2], [3], [1,2], [2,3] and [1,2,3] . Something like [1,3] would not be a subarray as it's not a contiguous subsection of the original array. So, We need to look for all positive contiguous segments of the array (maximum_ending_here is used for this). And then, keep track of maximum sum contiguous segment among all positive segments (maximum_overall is used for this). Each time we get maximum_ending_here greater than maximum_overall, update maximum_overall. So, this is covered in a greater detail in this article. Link to the article: https://iq.opengenus.org/kadane-algorithm/
code/languages/Java/README_bubble-sort.md
Bubble sort is an algorithm used to sort an array or a list in a more optimized fashion. At worst, bubble sort is seen as a 0(n^2) runtime sort algorithm. Algorithm used: 1) Check and see if the positions next to each other in the array/list are out of order. 2) If they are, swap them. If not, move on. 3) Do this through the entire list, if no swaps are made, end the algorithm. 4) If changes have been made, repeat.