filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/design_pattern/src/OOP_patterns/observer_pattern/observer_pattern.rs
// Part of Cosmos by OpenGenus Foundation use std::collections::HashMap; #[derive(Debug, Clone, Copy)] enum WeatherType { Clear, Rain, Snow, } #[derive(Debug, Clone, Copy)] enum WeatherObserverMessage { WeatherChanged(WeatherType), } trait WeatherObserver { fn notify(&mut self, msg: WeatherObserverMessage); } struct WeatherObserverExample { name: &'static str, } impl WeatherObserver for WeatherObserverExample { fn notify(&mut self, msg: WeatherObserverMessage) { println!("{} was notified: {:?}", self.name, msg); } } struct Weather { weather: WeatherType, observers: HashMap<usize, Box<WeatherObserver>>, observer_id_counter: usize } impl Weather { pub fn attach_observer(&mut self, observer: Box<WeatherObserver>) -> usize { self.observers.insert(self.observer_id_counter, observer); self.observer_id_counter += 1; self.observer_id_counter - 1 } pub fn detach_observer(&mut self, id: usize) -> Option<Box<WeatherObserver>> { self.observers.remove(&id) } pub fn set_weather(&mut self, weather_type: WeatherType) { self.weather = weather_type; self.notify_observers(WeatherObserverMessage::WeatherChanged(weather_type)); } pub fn notify_observers(&mut self, msg: WeatherObserverMessage) { for obs in self.observers.values_mut() { obs.notify(msg); } } } fn main() { let mut weather = Weather { weather: WeatherType::Clear, observers: HashMap::new(), observer_id_counter: 0 }; let first_obs = weather.attach_observer(Box::new(WeatherObserverExample { name: "First Observer", })); weather.set_weather(WeatherType::Rain); weather.detach_observer(first_obs); weather.attach_observer(Box::new(WeatherObserverExample { name: "Second Observer", })); weather.set_weather(WeatherType::Snow); }
code/design_pattern/src/OOP_patterns/proxy/demo/demo.java
package demo; import protection.proxy.User; import protection.proxy.UserProxy; import virtual.proxy.UltraHDVideo; import virtual.proxy.Video; import virtual.proxy.VideoProxy; public class Demo { public void protectionProxyRun() { User rob = new UserProxy("Robert", "123"); User david = new UserProxy("David", "pass"); User gangplank = new UserProxy("Gangplank", "12312312"); rob.login(); david.login(); gangplank.login(); rob.download(); david.download(); gangplank.login(); rob.upload(); david.upload(); gangplank.upload(); } public void virtualProxyRun() throws InterruptedException { System.out.println("Trying the proxy version first - 3 videos and playing just 1"); long startTime = System.currentTimeMillis(); Video v1 = new VideoProxy("Erik Mongrain - Alone in the mist"); Video v2 = new VideoProxy("Antoine Dufour - Drowning"); Video v3 = new VideoProxy("Jake McGuire - For Scale The Summit"); v3.play(); long endTime = System.currentTimeMillis(); long duration = (endTime - startTime); System.out.println("It took " + (duration / 1000) + " seconds to run"); System.out.println("Now for the not-proxy version"); startTime = System.currentTimeMillis(); Video v4 = new UltraHDVideo("Erik Mongrain - Alone in the mist"); Video v5 = new UltraHDVideo("Antoine Dufour - Drowning"); Video v6 = new UltraHDVideo("Jake McGuire - For Scale The Summit"); v6.play(); endTime = System.currentTimeMillis(); duration = endTime - startTime; System.out.println("It took " + (duration / 1000.0) + " seconds to run"); } }
code/design_pattern/src/OOP_patterns/proxy/main.java
import demo.Demo; public class Main { public static void main(String[] args) throws InterruptedException { new Demo().protectionProxyRun(); } }
code/design_pattern/src/OOP_patterns/proxy/protection/proxy/registeredusers.java
package protection.proxy; import java.util.HashMap; import java.util.Map; public class RegisteredUsers { static Map<String, String> registered = new HashMap<String, String>(){ { put("Robert", "123"); put("David", "pass"); put("Gangplank", "Illaoi"); } }; }
code/design_pattern/src/OOP_patterns/proxy/protection/proxy/user.java
package protection.proxy; public interface User { void login(); void download(); void upload(); }
code/design_pattern/src/OOP_patterns/proxy/protection/proxy/userproxy.java
package protection.proxy; import java.util.Objects; public class UserProxy implements User { private String username; private String password; Boolean isLogged; private User user; public UserProxy(String username, String password) { this.username = username; this.password = password; } @Override public void login() { if (Objects.equals(RegisteredUsers.registered.get(username), password)){ this.user = new ValidUser(username, password); System.out.println("Login successful - welcome back, " + this.username + " !"); } else System.out.println("Invalid credentials for " + this.username + " !"); } @Override public void download() { if (this.user == null) System.out.println("User credentials invalid " + this.username + "!"); else user.download(); } @Override public void upload() { if (this.user == null) System.out.println("User credentials invalid " + this.username + " !"); else user.upload(); } }
code/design_pattern/src/OOP_patterns/proxy/protection/proxy/validuser.java
package protection.proxy; class ValidUser implements User { String username; String password; ValidUser(String username, String password) { this.username = username; this.password = password; } @Override public void login() { System.out.println(">" + this.username + ": Successfully logged, welcome!"); } @Override public void download() { System.out.println(">" + this.username + ": Downloading"); } @Override public void upload() { System.out.println(">" + this.username + ": Uploading"); } }
code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/demo.java
package virtual.proxy; public class Demo { }
code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/ultrahdvideo.java
package virtual.proxy; public class UltraHDVideo implements Video { public String name; public UltraHDVideo(String path) throws InterruptedException { this.name = path; loadVideo(); } @Override public void play() { System.out.println("4k video is being played - " + name); } private void loadVideo() throws InterruptedException { Thread.sleep(5000); System.out.println("Video has been loaded - " + name); } }
code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/video.java
package virtual.proxy; public interface Video { void play(); }
code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/videoproxy.java
package virtual.proxy; public class VideoProxy implements Video { public String name; public Video realVideo; public VideoProxy(String name) { this.name = name; } @Override public void play() { try { this.realVideo = new UltraHDVideo(name); } catch (InterruptedException e) { e.printStackTrace(); } realVideo.play(); } }
code/design_pattern/src/OOP_patterns/singleton_pattern/singleton_pattern.cpp
#include <string> #include <iostream> template<typename T> class Singleton { public: static T* GetInstance(); static void destroy(); private: Singleton(Singleton const&) { }; Singleton& operator=(Singleton const&) { }; protected: static T* m_instance; Singleton() { m_instance = static_cast <T*> (this); }; ~Singleton() { }; }; template<typename T> T * Singleton<T>::m_instance = 0; template<typename T> T* Singleton<T>::GetInstance() { if (!m_instance) Singleton<T>::m_instance = new T(); return m_instance; } template<typename T> void Singleton<T>::destroy() { delete Singleton<T>::m_instance; Singleton<T>::m_instance = 0; } class TheCow : public Singleton<TheCow> { public: void SetSays(std::string &whatToSay) { whatISay = whatToSay; }; void Speak(void) { std::cout << "I say" << whatISay << "!" << std::endl; }; private: std::string whatISay; }; void SomeFunction(void) { std::string say("moo"); TheCow::GetInstance()->SetSays(say); } int main () { std::string say("meow"); TheCow::GetInstance()->SetSays(say); SomeFunction(); TheCow::GetInstance()->Speak(); }
code/design_pattern/src/OOP_patterns/singleton_pattern/singleton_pattern.java
/** * Singleton Design Pattern * * @author Sagar Rathod * @version 1.0 * */ class Singleton { private volatile transient static Singleton singletonInstance; private Singleton() {} public static synchronized Singleton getInstance() { if ( singletonInstance == null ) { singletonInstance = new Singleton(); } return singletonInstance; } } public class SingletonPattern { public static void main(String[] args) { Singleton instance = Singleton.getInstance(); System.out.println(instance == Singleton.getInstance()); } }
code/design_pattern/src/OOP_patterns/singleton_pattern/singleton_pattern.php
<?php /** * Simple singleton class which could only have one instance * Part of Cosmos by OpenGenus Foundation */ class Singleton { } /** * Class which creates instance of Singleton if it does not exists */ class SingletonInstanter { private static $instance; public static function getInstance() { if (empty(self::$instance)) { self::$instance = new Singleton(); } return self::$instance; } }
code/design_pattern/src/OOP_patterns/singleton_pattern/singleton_pattern.py
# Part of Cosmos by OpenGenus Foundation class Singleton: __instance = None @property def x(self): return self.__x @x.setter def x(self, value): self.__x = value @staticmethod def instance(): if not Singleton.__instance: Singleton.__instance = Singleton() return Singleton.__instance
code/design_pattern/src/__init__.py
code/design_pattern/src/builder_pattern/builder.cs
using System; using System.Collections.Generic; namespace SandBox { /// <summary> /// Acts as the "Director" class. /// /// An intermediary between the customer (main) and the manufacturer. /// Unaware of the intracacies of building each product. /// </summary> class Dealer { /// <summary> /// Orders a vehicle from a Manufacturer. /// </summary> /// <param name="manufacturer">The manufacturer to order from</param> public Vehicle Order(Manufacturer manufacturer) { return manufacturer.BuildVehicle(); } } /// <summary> /// Template class for each Manufacturer to follow. /// Allows for easy extensibility, while maintaining consistency. /// </summary> abstract class Manufacturer { public Vehicle Vehicle { get; protected set; } public abstract Vehicle BuildVehicle(); } /// <summary> /// 1 of 3. /// An example of one of the many possible builder classes that extend the /// abstract class Manufacturer. /// </summary> class MotorCycleManufacturer : Manufacturer { public string ManufacturerName = "MotorCycle"; public MotorCycleManufacturer() { } public override Vehicle BuildVehicle() { var vehicle = new Vehicle(ManufacturerName); vehicle.Parts.Add("Body", "Bike"); vehicle.Parts.Add("Handlebars", "Stock"); vehicle.Parts.Add("Wheels", "Two-Wheeled"); return vehicle; } } /// <summary> /// 2 of 3. /// An example of one of the many possible builder classes that extend the /// abstract class Manufacturer. /// </summary> class SUVManufacturer : Manufacturer { private string ManufacturerName = "SUV"; public SUVManufacturer() { } public override Vehicle BuildVehicle() { var vehicle = new Vehicle(ManufacturerName); vehicle.Parts.Add("Body", "Large-Box"); vehicle.Parts.Add("Steering Wheel", "Stock"); vehicle.Parts.Add("Wheels", "Four-Wheeled"); return vehicle; } } /// <summary> /// 3 of 3. /// An example of one of the many possible builder classes that extend the /// abstract class Manufacturer. /// </summary> class ConvertibleManufacturer : Manufacturer { private string ManufacturerName = "Convertible"; public ConvertibleManufacturer() { } public override Vehicle BuildVehicle() { var vehicle = new Vehicle(ManufacturerName); vehicle.Parts.Add("Body", "Small-Sleek"); vehicle.Parts.Add("Steering Wheel", "Stock"); vehicle.Parts.Add("Wheels", "Four-Wheeled"); vehicle.Parts.Add("Roof", "Soft-Top"); return vehicle; } } /// <summary> /// Acts as the item being built. /// /// Each item starts generic, then the manufacturer makes it unique. The /// process is abstracted from the item. /// </summary> class Vehicle { public readonly string Make; public Dictionary<string, string> Parts = new Dictionary<string, string>(); public Vehicle(string manufacturer) { this.Make = manufacturer; } public void Show() { Console.WriteLine("\n---------------------------"); Console.WriteLine("Vehicle Type: {0}", Make); foreach (var part in Parts) Console.WriteLine(" {0} : {1}", part.Key, part.Value); } } class Program { static void Main(string[] args) { var MotorCycleManufacturer = new MotorCycleManufacturer(); var motorCycle = MotorCycleManufacturer.BuildVehicle(); motorCycle.Show(); var SUVManufacturer = new SUVManufacturer(); var suv = SUVManufacturer.BuildVehicle(); suv.Show(); var ConvertibleManufacturer = new ConvertibleManufacturer(); var convertible = ConvertibleManufacturer.BuildVehicle(); convertible.Show(); } } }
code/design_pattern/src/functional_patterns/README.md
# cosmos Your personal library of every design pattern code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/design_pattern/src/functional_patterns/functional_patterns/scala/build.sbt
code/design_pattern/src/functional_patterns/functional_patterns/scala/project/build.properties
sbt.version = 1.1.0
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/arrows/arrow/arrow.scala
package arrows.arrow trait Arrow { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/applicative/functor/applicativefunctor.scala
package functors.applicative.functor import scala.language.higherKinds /** * Applicative is an intermediate between functor and monad. * * Its importance are dominated by: * - ability to apply functions of more parameters * For example: * val f = (x: Int)(y: Int) => x + y * If we apply the above function to a functor Future(10).map(f), * the result will be a Future(x => 10 + x). And you can't map that any further. * A way to extract the result is needed, hence applicative functors, where you can do something like: * val f = (x: Int)(y: Int) => x + y * val r: Future[Int -> Int] = Future(10).map(f) * Future(20).apply(r) => should return 30 * * - can apply functions wrapped into a functor context * * - can combine multiple functors into one single product */ trait ApplicativeFunctor[F[_]] { def apply[A, B](fa: F[A])(f: F[A => B]): F[A] => F[B] }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/bifunctor/bifunctor.scala
package functors.bifunctor import scala.language.higherKinds /** * * Similar to a functor, the BiFunctor must satisfy the functor laws: * 1. bimap f id id = id * first f id = id * second f id = id * * Applying a function over the identity, should return the identity. * * 2. bimap f g = first f . second g * * Asociativity: applying bimap f g should be equal to applying f to first and g to second. * * BiFunctors include: Either, N-Tuples */ trait BiFunctor[F[_, _]] { def biMap[A, B, C, D](fab: F[A, B])(f: A => C)(g: B => D): F[B, D] def first[A, C](fab: F[A, _])(f: A => C): F[C, _] def second[B, D](fab: F[_, B])(f: B => D): F[_, D] }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/contravariant/contravariant.scala
package functors.contravariant trait Contravariant { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/functor/functor.scala
package functors.functor import scala.language.higherKinds /** * ADT which aspires to be a functor must preserve 2 laws: * 1. fmap over the identity functor of the ADT should coincide with the original ADT * fmap(identity, adt) === adt * * 2. The composition of 2 functions and mapping the resulting function over a functor * should be the same as mapping the first function over the functor and then the second one. * fmap(f compose g, adt) === fmap(f, fmap(g, adt)) * * Some functors include: List, Set, Map, Option, etc. */ trait Functor[A, F[_]] { // something might be fishy with the id def id: A def fmap[B](fA: F[A])(f: A => B): F[B] } object FunctorImplicits { implicit def listFunctor[A]: Functor[A, List] = new Functor[A, List] { override def id: A = ??? override def fmap[B](fA: List[A])(f: A => B): List[B] = fA.map(f) } implicit def optionFunctor[A]: Functor[A, Option] = new Functor[A, Option] { override def id: A = ??? override def fmap[B](fA: Option[A])(f: A => B): Option[B] = fA.map(f) } }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/multifunctor/multifunctor.scala
package functors.multifunctor trait Multifunctor { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/profunctor/profunctor.scala
package functors.profunctor trait Profunctor { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/main.scala
object Main extends App{ }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/comonad/comonad.scala
package monads.comonad trait Comonad { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/costate/monad/costatemonad.scala
package monads.costate.monad trait CostateMonad { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/free/monad/freemonad.scala
package monads.free.monad trait FreeMonad { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/gonad/gonad.scala
package monads.gonad trait Gonad { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/io/monad/iomonad.scala
package monads.io.monad trait IOMonad { }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/monad/monad.scala
package monads.monad import scala.language.higherKinds trait Monad[T, M[_]] { def flatMap[S](fA: T => M[S])(f: M[T]): M[S] } object MonadImplicits { implicit def listMonad[T]: Monad[T, List] = new Monad[T, List] { override def flatMap[S](fA: T => List[S])(f: List[T]): List[S] = f.flatMap(fA) } implicit def optionMonad[T]: Monad[T, Option] = new Monad[T, Option] { override def flatMap[S](fA: T => Option[S])(f: Option[T]): Option[S] = f.flatMap(fA) } }
code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/state/monad/statemonad.scala
package monads.state.monad /** * The equivalent of Memento design pattern in OOP on steroids, * state monads deal with maintaining previous states WHILE generating new ones. */ trait StateMonad[S, A] { def apply(f: S => (S, A)): StateMonad[S, A] }
code/design_pattern/src/iterator_pattern/class.java
package iterator; public class Class { private Student[] students = new Student[100]; private int i = 0; private String class_name; public Class(String n) { this.class_name = n; } public String getName() { return this.class_name; } public void add(String name,int age) { Student s = new Student(name, age); students[i] = s; i++; } public ClassIterator iterator() { ClassIterator iterator = new ClassIterator(students); return iterator; } }
code/design_pattern/src/iterator_pattern/classiterator.java
package iterator; public class ClassIterator implements Iterator<Student> { private Student[] student; private int i = 0; public ClassIterator(Student[] s){ this.student = s; } @Override public boolean hasNext() { if( i < student.length && student[i] != null) return true; else return false; } @Override public Student next() { if(this.hasNext()){ Student s = student[i]; i++; return s; }else return null; } }
code/design_pattern/src/iterator_pattern/iterator.java
package iterator; public interface Iterator<T> { public boolean hasNext(); public Student next(); }
code/design_pattern/src/iterator_pattern/main.java
package iterator; public class Main { public static void main(String[] args) { Class class1 = new Class("class1"); class1.add("student1",12); class1.add("student2",15); class1.add("student3",16); ClassIterator it = class1.iterator(); while (it.hasNext()) { Student student = it.next(); student.print(); } } }
code/design_pattern/src/iterator_pattern/student.java
package iterator; public class Student { private String name; private int age; public Student(String n, int a) { this.name = n; this.age = a; } public String getName() { return this.name; } public void print() { System.out.println("Student: " + this.name + " Age: " + this.age); } }
code/design_pattern/src/policy_based_design/policy_design.cpp
/* * policy_design.cpp * * Created: 3/15/2018 1:14:41 AM * Author: n-is * email: [email protected] */ #include <iostream> class Classical { public: Classical(int a) { } void solve() { std::cout << "The differential equation was solved by the classical" << " method." << std::endl; } }; class Laplace { public: void solve() { std::cout << "The differential equation was solved by the Laplace" << " Transform method." << std::endl; } }; template <class Method> class DifferentialEquaton { private: Method m_; public: DifferentialEquaton(const Method & m = Method()) : m_(m) { } void solve() { m_.solve(); } }; int main() { DifferentialEquaton<Laplace> eqn1; DifferentialEquaton<Classical> eqn2(Classical(1)); eqn1.solve(); eqn2.solve(); return 0; }
code/design_pattern/src/policy_based_design/readme.md
# Policy Based Design Policy-based design, also known as policy-based class design or policy-based programming, is a computer programming paradigm based on an idiom for C++ known as policies. ## Explanation Wikipedia(<https://en.wikipedia.org/wiki/Policy-based_design>) says: >Policy-based design has been described as a compile-time variant of the strategy pattern, and has connections with C++ template metaprogramming. It was first popularized by Andrei Alexandrescu with his 2001 book Modern C++ Design and his column Generic`<Programming>` in the C/C++ Users Journal. This design pattern is expecially suitable for writing library for embedded systems, where a single peripheral may have various modes of operation and the user may choose between the modes of operation at compile time. ## Algorithm Well, a design pattern is not an algorithm, but just a solution to certain problems. In the same way, policy based design a one of the best method to implement strategy pattern at compile time(i.e. choose between the implementations at the compile time). ## Complexity Implementing Policy Based Design increases the number of classes in the program, so it may be hard to handle since the program will become larger. But this design pattern does not add runtime overhead while choosing the implementation. So, this design pattern reduces the timing overhead. If a compiler with a very good optimizer is used, the space consumed by the final program is also reduced. --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/design_pattern/src/singleton_pattern/singleton_pattern.cs
// Singleton design pattern using properties class Singleton { private static readonly Singleton _instance = new Singleton(); public static Singleton Instance { get { return _instance; } } private Singleton() { // Initialize object } } class Program { static void Main(string[] args) { var instance = Singleton.Instance; } }
code/design_pattern/src/singleton_pattern/singleton_pattern.js
/* Part of Cosmos by OpenGenus Foundation */ class Singleton { constructor() { console.log('New Singleton'); } static getInstance() { if (!Singleton.instance) { Singleton.instance = new Singleton(); } return Singleton.instance; } foo() { console.log('bar'); } } (function () { const firstInstance = Singleton.getInstance(); // New Singleton const secondInstance = Singleton.getInstance(); // void firstInstance.foo(); // bar secondInstance.foo(); // bar })();
code/design_pattern/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/design_pattern/test/__init__.py
code/design_pattern/test/test_observer.py
from src.OOP_patterns.observer_pattern import Notifier, Observer import unittest from enum import Enum class Event(Enum): Earthquake = 0 Joke = 1 class SomeWhere: def __init__(self): self._member = {} def add_member(self, member): self._member[member] = "is here" def remove_member(self, member): del self._member[member] # override update protocol def update(self, event): global res if event == Event.Earthquake: for member in self._member: res.append("{0} received, need to run away !!!".format(member)) elif event == Event.Joke: for member in self._member: res.append("{0} received, A false alarm ...".format(member)) # decorate class LivingRoom(SomeWhere): pass # decorate class StudyRoom(SomeWhere): pass class School(SomeWhere): pass class EmergencyAlart(Notifier): pass class Kitchen(Notifier): pass res = [] class TestObserver(unittest.TestCase): def test_observer(self): global res study_room = Observer(StudyRoom()) living_room = Observer(LivingRoom()) school = Observer(School()) emergency_alart = EmergencyAlart() kitchen = Kitchen() study_room.attach_notifier(emergency_alart) living_room.attach_notifier(emergency_alart) school.attach_notifier(emergency_alart) study_room.attach_notifier(kitchen) living_room.attach_notifier(kitchen) # My sister is studying in studyroom study_room.add_member("My sister") # and I am watching TV in living room living_room.add_member("I") # Just cooking. res = [] kitchen.notify(Event.Joke) self.assertListEqual( sorted(res), sorted( [ "I received, A false alarm ...", "My sister received, A false alarm ...", ] ), ) # My sister is on her way to school. study_room.remove_member("My sister") school.add_member("My sister") res = [] kitchen.notify(Event.Joke) self.assertListEqual(sorted(res), sorted(["I received, A false alarm ..."])) # Living room alert is no longer needed. living_room.detach_notifier(kitchen) res = [] kitchen.notify(Event.Joke) self.assertListEqual(sorted(res), sorted([])) # I am studying living_room.remove_member("I") study_room.add_member("I") res = [] kitchen.notify(Event.Joke) self.assertListEqual(sorted(res), sorted(["I received, A false alarm ..."])) # emergency alart notify you everywhere res = [] emergency_alart.notify(Event.Earthquake) self.assertListEqual( sorted(res), sorted( [ "I received, need to run away !!!", "My sister received, need to run away !!!", ] ), )
code/divide_conquer/src/README.md
# Divide and conquer Divide and conquer is an algorithm design paradigm based on multi-branched recursion. A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem. This divide and conquer technique is the basis of efficient algorithms for all kinds of problems, such as sorting (e.g., quicksort, merge sort), multiplying large numbers (e.g. the Karatsuba algorithm), finding the closest pair of points, syntactic analysis (e.g., top-down parsers), and computing the discrete Fourier transform (FFTs). # cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/divide_conquer/src/closest_pair_of_points/closest_pair.cpp
// divide conquer | structure to represent a point | C // Part of Cosmos by OpenGenus Foundation #include <vector> #include <cmath> #include <iostream> #include <algorithm> #include <cfloat> #define ll long long using namespace std; struct point { ll x; ll y; }; // comparator function to sort points by X coordinates bool compX(point a, point b) { return a.x < b.x; } // comparator function to sort points by Y coordinates bool compY(point a, point b) { if (a.y < b.y) return true; if (a.y > b.y) return false; return a.x < b.x; } point result1, result2; double minDist = DBL_MAX; double euclideanDistance(point a, point b) { return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2)); } double bruteMin(vector<point> &pointsByX, size_t low, size_t high) { size_t i, j; double dist, bestDistance = DBL_MAX; for (i = low; i <= high; i++) for (j = i + 1; j <= high; j++) { dist = euclideanDistance(pointsByX[i], pointsByX[j]); if (dist < bestDistance) { bestDistance = dist; if (bestDistance < minDist) { minDist = bestDistance; result1 = pointsByX[i]; result2 = pointsByX[j]; } } } return bestDistance; } double closestPair(vector<point> &pointsByX, vector<point> &pointsByY, size_t low, size_t high) { size_t i, j, n = high - low + 1; // if number of points <= 3, use brute to find min distance if (n <= 3) return bruteMin(pointsByX, low, high); size_t mid = low + (high - low) / 2; // find minimum distance among left half of points recursively double distLeft = closestPair(pointsByX, pointsByY, low, mid); // find minimum distance among right half of points recursively double distRight = closestPair(pointsByX, pointsByY, mid + 1, high); double bestDistance = min(distLeft, distRight); // store points in strip of width 2d sorted by Y coordinates vector<point> pointsInStrip; for (i = 0; i < n; i++) if (abs(pointsByY[i].x - pointsByX[mid].x) < bestDistance) pointsInStrip.push_back(pointsByY[i]); // calculate minimum distance within the strip (atmost 6 comparisons) for (i = 0; i < pointsInStrip.size(); i++) for (j = i + 1; j < pointsInStrip.size() && abs(pointsInStrip[i].y - pointsInStrip[j].y) < bestDistance; j++) { double dist = euclideanDistance(pointsInStrip[i], pointsInStrip[j]); if (dist < bestDistance) { bestDistance = dist; minDist = dist; result1 = pointsInStrip[i]; result2 = pointsInStrip[j]; } } return bestDistance; } int main() { ll i, n; cin >> n; // number of points // pointsByX stores points sorted by X coordinates // pointsByY stores points sorted by Y coordinates vector<point> pointsByX(n), pointsByY(n); for (i = 0; i < n; i++) { cin >> pointsByX[i].x >> pointsByX[i].y; pointsByY[i].x = pointsByX[i].x; pointsByY[i].y = pointsByX[i].y; } sort(pointsByX.begin(), pointsByX.end(), compX); sort(pointsByY.begin(), pointsByY.end(), compY); cout << "Shortest distance = " << closestPair(pointsByX, pointsByY, 0, n - 1) << endl; cout << "Points are (" << result1.x << "," << result1.y << ") and (" << result2.x << "," << result2.y << ")\n"; return 0; }
code/divide_conquer/src/closest_pair_of_points/closest_pair.py
# divide conquer | structure to represent a point | Python # Part of Cosmos by OpenGenus Foundation import math def dist(p1, p2): return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def closest_pair(ax, ay): # It's quicker to assign variable ln_ax = len(ax) if ln_ax <= 3: # A call to bruteforce comparison return brute(ax) # Division without remainder, need int mid = ln_ax // 2 # Two-part split Qx = ax[:mid] Rx = ax[mid:] # Determine midpoint on x-axis midpoint = ax[mid][0] Qy = list() Ry = list() # split ay into 2 arrays using midpoint for x in ay: if x[0] <= midpoint: Qy.append(x) else: Ry.append(x) # Call recursively both arrays after split (p1, q1, mi1) = closest_pair(Qx, Qy) (p2, q2, mi2) = closest_pair(Rx, Ry) # Determine smaller distance between points of 2 arrays if mi1 <= mi2: d = mi1 mn = (p1, q1) else: d = mi2 mn = (p2, q2) # Call function to account for points on the boundary (p3, q3, mi3) = closest_split_pair(ax, ay, d, mn) # Determine smallest distance for the array if d <= mi3: return mn[0], mn[1], d else: return p3, q3, mi3 def closest_split_pair(p_x, p_y, delta, best_pair): # store length - quicker ln_x = len(p_x) # select midpoint on x-sorted array mx_x = p_x[ln_x // 2][0] # Create a subarray of points not further than delta from # midpoint on x-sorted array s_y = [x for x in p_y if mx_x - delta <= x[0] <= mx_x + delta] # assign best value to delta best = delta # store length of subarray for quickness ln_y = len(s_y) for i in range(ln_y - 1): for j in range(i + 1, min(i + 7, ln_y)): p, q = s_y[i], s_y[j] dst = dist(p, q) if dst < best: best_pair = p, q best = dst return best_pair[0], best_pair[1], best def solution(a): ax = sorted(a, key=lambda x: x[0]) # Presorting x-wise ay = sorted(a, key=lambda x: x[1]) # Presorting y-wise p1, p2, mi = closest_pair(ax, ay) # Recursive D&C function return (p1, p2, mi) def brute(ax): mi = dist(ax[0], ax[1]) p1 = ax[0] p2 = ax[1] ln_ax = len(ax) if ln_ax == 2: return p1, p2, mi for i in range(ln_ax - 1): for j in range(i + 1, ln_ax): if i != 0 and j != 1: d = dist(ax[i], ax[j]) if d < mi: # Update min_dist and points mi = d p1, p2 = ax[i], ax[j] return p1, p2, mi solution_tuple = solution( [ (0, 0), (7, 6), (2, 20), (12, 5), (16, 16), (5, 8), (19, 7), (14, 22), (8, 19), (7, 29), (10, 11), (1, 13), ] ) print("Point 1 =>", solution_tuple[0]) print("Point 2 =>", solution_tuple[1]) print("Distance =>", solution_tuple[2])
code/divide_conquer/src/factorial/factorial.cpp
#include<iostream> int factorial(int num) { if (num == 0 || num == 1) { return num; } return (num * factorial(num - 1)); } int main() { int num; while (true) { std::cin >> num; std::cout << "> " << factorial(num) << '\n'; } return 0; }
code/divide_conquer/src/factorial/factorial.py
""" divide conquer | factorial | Python part of Cosmos by OpenGenus Foundation """ def factorial(num): """ Returns the factorial of a given integer num. Divide and conquer is used here by organizing the function into a base and recursive case. Parameter: num is the number for which the factorial will be found Precondition: num is a non-negative integer """ assert (type(num)) == int assert num >= 0 # base case if num == 0 or num == 1: return 1 # recursive case recursive = factorial(num - 1) # output return num * recursive
code/divide_conquer/src/inversion_count/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/divide_conquer/src/inversion_count/count_inversions.c
// divide conquer | inversion count | C // Part of Cosmos by OpenGenus Foundation #include <stdlib.h> #include <stdio.h> int _mergeSort(int arr[], int temp[], int left, int right); int merge(int arr[], int temp[], int left, int mid, int right); int mergeSort(int arr[], int array_size) { int *temp = (int *)malloc(sizeof(int)*array_size); return _mergeSort(arr, temp, 0, array_size - 1); } int _mergeSort(int arr[], int temp[], int left, int right) { int mid, inv_count = 0; if (right > left) { mid = (right + left)/2; inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid+1, right); inv_count += merge(arr, temp, left, mid+1, right); } return inv_count; } int merge(int arr[], int temp[], int left, int mid, int right) { int i, j, k; int inv_count = 0; i = left; j = mid; k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } while (i <= mid - 1) temp[k++] = arr[i++]; while (j <= right) temp[k++] = arr[j++]; for (i=left; i <= right; i++) arr[i] = temp[i]; return inv_count; } int main(int argc, char** argv) { printf("Number of elements in array : "); int n; scanf("%d", &n); int arr[n]; printf("elements in array:\n"); for (int x=0; x<n; x++) { scanf("%d", &arr[x]); } printf("Number of inversions are %d \n", mergeSort(arr, n)); getchar(); return 0; }
code/divide_conquer/src/inversion_count/inversion_count.cpp
// divide conquer | inversion count | C++ // Part of Cosmos by OpenGenus Foundation #include <iostream> using namespace std; int mergesort(int arr[], int l, int r); int merge(int arr[], int l, int m, int r); int main() { int n, a[100], i; cout << "Enter nuber of elements : "; cin >> n; cout << "Enter the elements : "; for (i = 0; i < n; i++) cin >> a[i]; cout << "Number of inversion = " << mergesort(a, 0, n - 1); return 0; } //merge int merge(int arr[], int l, int m, int r) { int i, j, k, c[100], count = 0; i = 0; j = l; k = m; while (j <= m - 1 && k <= r) { if (arr[j] <= arr[k]) c[i++] = arr[j++]; else { c[i++] = arr[k++]; count += m - j; } } while (j <= m - 1) c[i++] = arr[j++]; while (k <= r) c[i++] = arr[k++]; i = 0; while (l <= r) arr[l++] = c[i++]; return count; } //mergesort int mergesort(int arr[], int l, int r) { int x = 0, y = 0, z = 0; int m = (l + r) / 2; if (l < r) { x += mergesort(arr, l, m); y += mergesort(arr, m + 1, r); z += merge(arr, l, m + 1, r); } return x + y + z; }
code/divide_conquer/src/inversion_count/inversion_count.java
// divide conquer | inversion count | Java // Part of Cosmos by OpenGenus Foundation import java.util.Scanner; public class InversionCount { public static int merge(int a[], int p, int q,int r){ int i = p ,j = q ,k = 0, count = 0; int temp[] = new int[r-p+1]; while(i<q && j<=r){ if(a[i] < a[j]){ temp[k++] = a[i++]; } else{ temp[k++] = a[j++]; count += (q - i); } } while(i<q){ temp[k++] = a[i++]; } while(j<=r){ temp[k++] = a[j++]; } k = 0; while(p<=r) a[p++] = temp[k++]; return count; } public static int mergeSort(int a[],int i, int j){ int count = 0; if(i>=j) return 0; int mid = (i+j)/2; count += mergeSort(a,i,mid); count += mergeSort(a,mid+1,j); count += merge(a,i,mid+1,j); return count; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter n >> "); int n = sc.nextInt(); int a[] = new int[n]; System.out.print("Enter elements of array >> "); for(int i=0;i<n;i++) a[i] = sc.nextInt(); int count = mergeSort(a,0,a.length-1); System.out.println("Number of inversions : " + count); } }
code/divide_conquer/src/inversion_count/inversion_count.js
// divide conquer | inversion count | Javascript // Part of Cosmos by OpenGenus Foundation function mergeSort(arr, size) { if (array.length === 0 || array.length === 1) return 0; var temp = []; return mergeSortHelper(arr, temp, 0, size - 1); } function mergeSortHelper(arr, temp, left, right) { var inv_count, mid = 0; if (right > left) { mid = (right + left) / 2; /* sum the number of inversions from all parts */ inv_count = mergeSortHelper(arr, temp, left, mid); inv_count += mergeSortHelper(arr, temp, mid + 1, right); inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } function merge(arr, temp, left, mid, right) { var inv_count = 0; var i = left; var j = mid; var k = left; while (i <= mid - 1 && j <= right) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; /* remaining elements in subarray arr[i] to arr[mid] are sorted and grater than arr[j] */ inv_count = inv_count + (mid - i); } } /* Copy remaining elements*/ while (i <= mid - 1) temp[k++] = arr[i++]; while (j <= right) temp[k++] = arr[j++]; /*merge into original array*/ for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } console.log(mergeSort([5, 10, 4, 8, 2], 5));
code/divide_conquer/src/inversion_count/inversion_count.py
""" divide conquer | inversion count | Python part of Cosmos by OpenGenus Foundation """ def merge(left, right): merged_arr = [] i = 0 j = 0 inv_cnt = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: merged_arr.append(left[i]) i += 1 else: merged_arr.append(right[j]) j += 1 inv_cnt += len(left) - i merged_arr += left[i:] merged_arr += right[j:] return merged_arr, inv_cnt def merge_sort( arr ): # this function will return a tuple as (sorted_array, inversion_count) if len(arr) > 1: mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] left, left_inv_cnt = merge_sort(left) right, right_inv_cnt = merge_sort(right) merged, merged_inv_cnt = merge(left, right) return merged, (left_inv_cnt + right_inv_cnt + merged_inv_cnt) else: return arr, 0 arr = [1, 8, 3, 4, 9, 3] sorted_array, inversion_count = merge_sort(arr) print("Sorted array:", sorted_array, " and Inversion count = %s" % inversion_count)
code/divide_conquer/src/karatsuba_multiplication/karatsuba_multiplication.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue May 29 11:21:34 2018 @author: Sahit """ print("enter the first number") n1 = input() print("enter the second number") n2 = input() def Correcting(string): p = len(string) i = 1 while i < p: i = i * 2 return i l = max(Correcting(n1), Correcting(n2)) num1 = "0" * (l - len(n1)) + n1 num2 = "0" * (l - len(n2)) + n2 def Karatsuba(number_1, number_2): l = len(number_1) r1 = int(number_1) r2 = int(number_2) if len(number_1) == 1: return r1 * r2 else: a = number_1[: l // 2] b = number_1[l // 2 :] c = number_2[: l // 2] d = number_2[l // 2 :] e = Karatsuba(a, c) f = Karatsuba(b, d) g = Karatsuba(b, c) h = Karatsuba(a, d) return ((10 ** l) * e) + (g + h) * (10 ** (l / 2)) + f ans = Karatsuba(num1, num2) print(ans)
code/divide_conquer/src/karatsuba_multiplication/karatsubamultiply.cpp
// Author: Tote93 #include <iostream> #include <string> #include <sstream> #include <cstdlib> /* Prototypes */ int getBiggerSize(const std::string &number1, const std::string &number2); void checkNumbers(int size, std::string &number1, std::string &number2); std::string KaratsubaMultiply(std::string &number1, std::string &number2, int limit); std::string AddNumbers(std::string &number1, std::string &number2); void removeNonSignificantZeros(std::string &c); void splitString(std::string original, std::string &sub1, std::string &sub2); int main() { std::string number1, number2; std::cout << "Insert the first number \n"; std::cin >> number1; std::cout << "Insert the second number \n"; std::cin >> number2; int size = getBiggerSize(number1, number2); checkNumbers(size, number1, number2); std::string result = KaratsubaMultiply(number1, number2, number1.length()); //Returns number to original without non-significant zeros removeNonSignificantZeros(number1); removeNonSignificantZeros(number2); std::cout << "Result " << number1 << " * " << number2 << " = " << result << "\n"; } int getBiggerSize(const std::string &number1, const std::string &number2) { int numb1Length = number1.length(); int numb2Length = number2.length(); return (numb1Length > numb2Length) ? numb1Length : numb2Length; } void checkNumbers(int size, std::string &number1, std::string &number2) { int newSize = 0, nZeros = 0; newSize = getBiggerSize(number1, number2); nZeros = newSize - number1.length(); number1.insert(number1.begin(), nZeros, '0'); nZeros = newSize - number2.length(); number2.insert(number2.begin(), nZeros, '0'); if (number1.length() % 2 != 0) number1.insert(number1.begin(), 1, '0'); if (number2.length() % 2 != 0) number2.insert(number2.begin(), 1, '0'); } std::string KaratsubaMultiply(std::string &number1, std::string &number2, int limit) { int n = number1.length(), s; std::string w, x, y, z; std::string final1, final2, final3; std::string total; if (n == 1) { int integer1, integer2, aux; integer1 = atoi (number1.c_str()); integer2 = atoi (number2.c_str()); aux = integer1 * integer2; //We can replace two next lines with -> total = to_string(aux) using c++11 std::ostringstream temp; temp << aux; total = temp.str(); removeNonSignificantZeros (total); return total; } else { s = n / 2; splitString (number1, w, x); splitString (number2, y, z); final1 = KaratsubaMultiply (w, y, n); final1.append(2 * s, '0'); std::string wz = KaratsubaMultiply (w, z, n); std::string xy = KaratsubaMultiply (x, y, n); final2 = AddNumbers (wz, xy); final2.append(s, '0'); final3 = KaratsubaMultiply (x, z, n); total = AddNumbers (final1, final2); return AddNumbers (total, final3); } } void removeNonSignificantZeros(std::string &c) { int acum = 0; for (int i = 0; i < c.length(); ++i) { if (c[i] != '0') break; else acum++; } if (c.length() != acum) c = c.substr(acum, c.length()); else c = c.substr(acum - 1, c.length()); } void splitString(std::string original, std::string &sub1, std::string &sub2) { int n, n1, n2; sub1 = sub2 = ""; n = original.length(); if (n % 2 == 0) { n1 = n / 2; n2 = n1; } else { n1 = (n + 1) / 2; n2 = n1 - 1; } sub1 = original.substr(0, n1); sub2 = original.substr(n1, n); if (sub1.length() % 2 != 0 && sub2.length() > 2) sub1.insert(sub1.begin(), 1, '0'); if (sub2.length() > 2 && sub2.length() % 2 != 0) sub2.insert(sub2.begin(), 1, '0'); } std::string AddNumbers(std::string &number1, std::string &number2) { int x, y, aux = 0, aux2 = 0; int digitos = getBiggerSize(number1, number2); std::string total, total2, cadena; int n1 = number1.length(); int n2 = number2.length(); if (n1 > n2) number2.insert(number2.begin(), n1 - n2, '0'); else number1.insert(number1.begin(), n2 - n1, '0'); for (int i = digitos - 1; i >= 0; i--) { x = number1[i] - '0'; y = number2[i] - '0'; aux = x + y + aux2; if (aux >= 10) { aux2 = 1; aux = aux % 10; } else aux2 = 0; total2 = '0' + aux; total.insert(0, total2); if (i == 0 && aux2 == 1) { total2 = "1"; total.insert(0, total2); removeNonSignificantZeros(total); return total; } } removeNonSignificantZeros(total); return total; }
code/divide_conquer/src/karatsuba_multiplication/multiply.java
// divide conquer | karatsuba multiplication | Java // Part of Cosmos by OpenGenus Foundation import java.lang.*; import java.util.Scanner; public class Multiply { public static String trim(String str,int n) { if(str.length()>n) while(str.charAt(0)=='0' && str.length()>n) str=str.substring(1); else while(str.length()!=n) str="0"+str; return str; } public static String add_str(String a,String b,int n) { a=trim(a,n); b=trim(b,n); String val=""; int i,rem=0; char []c1=a.toCharArray(); char []c2=b.toCharArray(); int ans[]=new int[a.length()+1]; for(i=a.length();i>0;i--) { ans[i]=(c1[i-1]-48+c2[i-1]-48+rem)%10; rem=(c1[i-1]-48+c2[i-1]-48+rem)/10; } ans[0]=rem; for(i=0;i<ans.length;i++) val=val+ans[i]; val=trim(val,a.length()+1); return val; } public static String multiply(String s1,String s2,int n) { String a,b,c,d,ac,bd,ad_bc,ad,bc; int i; if(n==1) return Integer.toString(Integer.parseInt(s1)*Integer.parseInt(s2)); a=s1.substring(0,n/2); b=s1.substring(n/2,n); c=s2.substring(0,n/2); d=s2.substring(n/2,n); ac=multiply(a,c,n/2); bd=multiply(b,d,n/2); ad=multiply(a,d,n/2); bc=multiply(b,c,n/2); ad_bc=add_str(ad,bc,n); for(i=1;i<=n;i++) ac=ac+"0"; for(i=1;i<=n/2;i++) ad_bc=ad_bc+"0"; ac=trim(ac,n*2); ad_bc=trim(ad_bc,n*2); bd=trim(bd,n*2); return add_str(add_str(ac,ad_bc,n*2),bd,n*2); } public static void main(String args[]) { int n; Scanner sc=new Scanner(System.in); System.out.print("Enter first number="); String s1=sc.next(); System.out.print("Enter second number="); String s2=sc.next(); n=s1.length(); String s3=multiply(s1,s2,n); System.out.println(s3); } }
code/divide_conquer/src/maximum_contiguous_subsequence_sum/maximum_contiguous_subsequence_sum.c
#include <stdio.h> int max(int const a, int const b, const int c) { if (a > b) return (a > c ? a : c); return (b > c ? b : c); } int maximumContiguousSubsequenceSum(const int a[], int beg, int end) { if (beg == end) return (a[beg] > 0 ? a[beg] : 0); int mid = (beg + end) / 2; int leftSubProblem = maximumContiguousSubsequenceSum(a, beg, mid); int rightSubProblem = maximumContiguousSubsequenceSum(a, mid + 1, end); int currentSum = 0, leftSum = 0, rightSum = 0; int i; for (i = mid; i >= beg; --i) { currentSum += a[i]; if (leftSum < currentSum) leftSum = currentSum; } currentSum = 0; for (i = mid + 1; i <= end; ++i) { currentSum += a[i]; if (rightSum < currentSum) rightSum = currentSum; } return (max(leftSubProblem, rightSubProblem, leftSum + rightSum)); } int main() { int n; printf("Enter the size of the array: "); scanf("%d", &n); int a[n]; printf("Enter %d Integers \n", n); int i; for (i = 0; i < n; ++i) scanf("%d", &a[i]); printf("Maximum Contiguous Subsequence Sum is %d \n", maximumContiguousSubsequenceSum(a, 0, n - 1)); return (0); }
code/divide_conquer/src/merge_sort_using_divide_and_conquer/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/divide_conquer/src/merge_sort_using_divide_and_conquer/inversions.c
#include <stdio.h> const int maxn = 1e6; typedef long long unsigned llu; llu merge(int v[], int lo, int mid, int hi) { llu inv = 0; int i, j, k; int n1 = mid - lo + 1, n2 = hi - mid; int left[n1], right[n2]; for(i = 0; i < n1; i++) left[i] = v[i+lo]; for(j = 0; j < n2; j++) right[j] = v[j+mid+1]; i = 0, j = 0, k = lo; while(i < n1 && j < n2) { if(left[i] >= right[j]) { v[k] = left[i]; i++; inv += j; } else { v[k] = right[j]; j++; inv++; } ++k; } inv -= j; while(i < n1) { v[k] = left[i]; ++k; ++i; inv += j; } while(j < n2) { v[k] = right[j]; ++k; ++j; } return inv; } llu mergeSort(int v[], int lo, int hi) { llu inv = 0; if(lo < hi) { int mid = (lo+hi)/2; inv += mergeSort(v, lo, mid); inv += mergeSort(v, mid+1, hi); inv += merge(v, lo, mid, hi); } return inv; } llu inversions(int v[], int lo, int hi) { int size = hi-lo+1, u[size]; for(int i = 0; i < size; i++) { u[i] = v[i+lo]; } return mergeSort(u, 0, size-1); } int main() { int n, v[maxn]; scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d", &v[i]); } printf("Inversions: %llu\n", inversions(v, 0, n-1)); return 0; }
code/divide_conquer/src/merge_sort_using_divide_and_conquer/merge_sort_using_divide_and_conquer.cpp
// divide conquer | merge sort using divide and conquer | C++ // Part of Cosmos by OpenGenus Foundation #include <cstdlib> #include <cstdio> int _mergeSort(int arr[], int temp[], int left, int right); int merge(int arr[], int temp[], int left, int mid, int right); /* This function sorts the input array and returns the * number of inversions in the array */ int mergeSort(int arr[], int array_size) { int *temp = (int *)malloc(sizeof(int) * array_size); return _mergeSort(arr, temp, 0, array_size - 1); } /* An auxiliary recursive function that sorts the input array and * returns the number of inversions in the array. */ int _mergeSort(int arr[], int temp[], int left, int right) { int mid, inv_count = 0; if (right > left) { /* Divide the array into two parts and call _mergeSortAndCountInv() * for each of the parts */ mid = (right + left) / 2; /* Inversion count will be sum of inversions in left-part, right-part * and number of inversions in merging */ inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); /*Merge the two parts*/ inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } /* This funt merges two sorted arrays and returns inversion count in * the arrays.*/ int merge(int arr[], int temp[], int left, int mid, int right) { int i, j, k; int inv_count = 0; i = left; /* i is index for left subarray*/ j = mid; /* j is index for right subarray*/ k = left; /* k is index for resultant merged subarray*/ while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) temp[k++] = arr[i++]; else { temp[k++] = arr[j++]; /*this is tricky -- see above explanation/diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray * (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray * (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /*Copy back the merged elements to original array*/ for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } /* Driver program to test above functions */ int main() { int arr[] = {1, 20, 6, 4, 5}; printf(" Number of inversions are %d \n", mergeSort(arr, 5)); getchar(); return 0; }
code/divide_conquer/src/merge_sort_using_divide_and_conquer/merge_sort_using_divide_and_conquer.java
// divide conquer | merge sort using divide and conquer | Java // Part of Cosmos by OpenGenus Foundation package mergesort; /** * * @author Yatharth Shah */ public class MergeSort { int array[]; int size; public MergeSort(int n) { size=n; //create array with size n array=new int[n]; //asign value into the array for (int i=0;i<n;i++){ array[i]=(int) Math.round(Math.random()*89+10); } } public int getSize() { return size; } public void merge(int left, int mid, int right) { int temp [] =new int[right-left+1]; int i = left; int j = mid+1; int k = 0; while (i <= mid && j <= right) { if (array[i] <= array[j]) { temp[k] = array[i]; k++; i++; } else { //array[i]>array[j] temp[k] = array[j]; k++; j++; } } while(j<=right) temp[k++]=array[j++]; while(i<=mid) temp[k++]=array[i++]; for(k=0;k<temp.length;k++) array[left+k]=temp[k]; } public void merge_sort(int left,int right){ // Check if low is smaller then high, if not then the array is sorted if(left<right){ // Get the index of the element which is in the middle int mid=(left+right)/2; // Sort the left side of the array merge_sort(left,mid); // Sort the right side of the array merge_sort(mid+1,right); // Combine them both merge(left,mid,right); } } public void print(){ System.out.println("Contents of the Array"); for(int k=0;k<15;k++) { System.out.print(array[k]+" | "); } System.out.println(); } public static void main(String args[]){ MergeSort m=new MergeSort(15); System.out.println("Before Sort <<<<<<<<<<<<<<<<<<<<<"); m.print(); m.merge_sort(0,m.getSize()-1); System.out.println("After Sort > > > > > > > > > > > >"); m.print(); System.out.println("=======+============+=======+============+========="); MergeSort m2=new MergeSort(25); System.out.println("Before Sort <<<<<<<<<<<<<<<<<<<<<"); m2.print(); m2.merge_sort(0,m2.getSize()-1); System.out.println("After Sort > > > > > > > > > > > >"); m2.print(); System.out.println("=======+============+=======+============+========="); MergeSort m3=new MergeSort(30); System.out.println("Before Sort <<<<<<<<<<<<<<<<<<<<<"); m3.print(); m3.merge_sort(0,m3.getSize()-1); System.out.println("After Sort > > > > > > > > > > > >"); m3.print(); System.out.println("=======+============+=======+============+========="); } }
code/divide_conquer/src/power_of_a_number/power_of_a_number.cpp
/* PROBLEM STATEMENT: Given 2 numbers x and y, you need to find x raise to y. */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define FIO ios::sync_with_stdio(0); ll power(ll a,ll b) { ll res=1; while(b!=0) { if(b%2!=0) { res=(res*a)%1000000007; b--; } else { a=(a*a)%1000000007; b/=2; } } return res; } int main() { FIO; ll number_a,number_b,answer; cin >> number_a >> number_b; answer = power(number_a,number_b); cout << answer; return 0; }
code/divide_conquer/src/power_of_a_number/power_of_a_number.py
# Python3 program to check if # a given number can be expressed # as power import math # Returns true if n can be written as x^y def isPower(n) : if (n==1) : return True # Try all numbers from 2 to sqrt(n) as base for x in range(2,(int)(math.sqrt(n))+1) : y = 2 p = (int)(math.pow(x, y)) # Keep increasing y while power 'p' is smaller # than n. while (p<=n and p>0) : if (p==n) : return True y = y + 1 p = math.pow(x, y) return False # Driver Program for i in range(2,100 ) : if (isPower(i)) : print(i,end=" ")
code/divide_conquer/src/quick_hull/quick_hull.cpp
#include<bits/stdc++.h> using namespace std; #define iPair pair<int, int> set<iPair> hull;// stores the final points to create the convex hull int findSide(iPair p1, iPair p2, iPair p)// returns the side of the hull joined points p1 and p2 { int val = (p.second - p1.second) * (p2.first - p1.first) - (p2.second - p1.second) * (p.first - p1.first); if (val > 0) return 1; if (val < 0) return -1; return 0; } int line_distance(iPair p1, iPair p2, iPair p) { return abs ((p.second - p1.second) * (p2.first - p1.first) - (p2.second - p1.second) * (p.first - p1.first)); } void quickHull(iPair arr[], int size, iPair p1, iPair p2, int side) { int ind = -1; int max_dist = 0; for (int i=0; i<size; i++) { int temp = line_distance(p1, p2, arr[i]); if (findSide(p1, p2, arr[i]) == side && temp > max_dist) { ind = i; max_dist = temp; } } if (ind == -1) { hull.insert(p1); hull.insert(p2); return; } quickHull(arr, size, arr[ind], p1, -findSide(arr[ind], p1, p2)); quickHull(arr, size, arr[ind], p2, -findSide(arr[ind], p2, p1)); } void print(iPair arr[], int size) { if (size < 3) { cout << "Convex hull not possible\n"; return; } int min_x = 0, max_x = 0; for (int i=1; i<size; i++) { if (arr[i].first < arr[min_x].first) min_x = i; if (arr[i].first > arr[max_x].first) max_x = i; } quickHull(arr, size, arr[min_x], arr[max_x], 1); quickHull(arr, size, arr[min_x], arr[max_x], -1); cout << "The Convex Hull points are:\n"; while (!hull.empty()) { cout << "(" <<( *hull.begin()).first << ", " << (*hull.begin()).second << ") "; hull.erase(hull.begin()); } } int main() { iPair arr[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}}; int size = sizeof(arr)/sizeof(arr[0]); print(arr, size); return 0; } // OUTPUT // The Convex Hull points are: // (0, 0) (0, 3) (3, 1) (4, 4) // Code curated by Subhadeep Das(username:- Raven1233)
code/divide_conquer/src/quick_sort/Quick_Sort.cs
// Part of Cosmos (OpenGenus) using System; public class Quick_Sort { // Conquer public static int Parition(int[] array, int left, int right) { int pivot = array[left]; int index = right; int temp; for(int j = right; j > left; j--) { if(array[j] > pivot) { temp = array[j]; array[j] = array[index]; array[index] = temp; index--; } } array[left] = array[index]; array[index] = pivot; return index; } // Divide array into halves public static void Quick(int[] array, int left, int right) { if(left < right) { int pivot = Parition(array, left, right); Quick(array, left, pivot - 1); Quick(array, pivot + 1, right); } } public static void QuickSort(int[] array, int size) { Quick(array, 0, size - 1); } // function ro print array public static void Print_Array(int[] array, int size) { for(int i = 0; i < size; i++) Console.Write(array[i] + " "); Console.Write(""); } public static void Main() { int[] array = {2, 4, 3, 1, 6, 8, 4}; QuickSort(array, 7); Print_Array(array, 7); } } // Output // 1 2 3 4 4 6 8
code/divide_conquer/src/quick_sort/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/divide_conquer/src/quick_sort/quick_sort.c
// divide conquer | quick sort | C // Part of Cosmos by OpenGenus Foundation #include<stdio.h> // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ int partition (int arr[], int low, int high) { int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ void quickSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("n"); } // Driver program to test above functions int main() { int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr)/sizeof(arr[0]); quickSort(arr, 0, n - 1); printf("Sorted array: n"); printArray(arr, n); return (0); }
code/divide_conquer/src/quick_sort/quick_sort.cpp
// divide conquer | quick sort | C++ // Part of Cosmos by OpenGenus Foundation #include <cstdio> using namespace std; void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function takes last element as pivot, places * the pivot element at its correct position in sorted * array, and places all smaller (smaller than pivot) * to left of pivot and all greater elements to right * of pivot */ int partition (int arr[], int low, int high) { int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element swap(&arr[i], &arr[j]); } swap(&arr[i + 1], &arr[high]); return i + 1; } void quickSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now * at right place */ int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf("Sorted array: \n"); printArray(arr, n); return 0; }
code/divide_conquer/src/quick_sort/quick_sort.hs
quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = smaller ++ [x] ++ larger where smaller = quicksort $ filter (<=x) xs larger = quicksort $ filter (>x) xs
code/divide_conquer/src/quick_sort/quick_sort.py
def partition(arr, low, high): i = low - 1 pivot = arr[high] for j in range(low, high): if arr[j] <= pivot: i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 def quickSort(arr, low, high): if low < high: pi = partition(arr, low, high) quickSort(arr, low, pi - 1) quickSort(arr, pi + 1, high) arr = [10, 7, 8, 9, 1, 5] n = len(arr) quickSort(arr, 0, n - 1) print("Sorted array is:") for i in range(n): print("%d" % arr[i]),
code/divide_conquer/src/quick_sort/quick_sort.rs
// divide conquer | quick sort | Rust // Part of Cosmos by OpenGenus Foundation fn quick_sort(mut arr :Vec<i32>,low :usize, high :usize) -> Vec<i32> { if low < high { let mid = partition(&mut arr, low, high); let arr = quick_sort(arr.clone(),low,mid); let arr = quick_sort(arr,mid+1,high); return arr } arr } fn partition(arr : &mut Vec<i32>, low :usize, high :usize) -> usize { let pivot = arr[low]; let mut i = low ; let mut j = high; loop { while arr[i] < pivot && arr[i] != pivot { i += 1; } while arr[j] > pivot && arr[j] != pivot { j -= 1; } if i < j { arr.swap(i,j); }else{ return j } } } fn main() { let arr = vec![10, 7, 8, 9, 1, 5]; let len = arr.len(); let sorted = quick_sort(arr,0,len-1); println!("Sorted array is {:?}", sorted); }
code/divide_conquer/src/quick_sort/quick_sort.swift
// divide conquer | quick sort | Swift // Part of Cosmos by OpenGenus Foundation import Foundation; func partition(_ arr: inout [UInt32], _ begin: Int, _ end: Int) -> Int { var i = begin; var j = end; let pivot = arr[(i + j) / 2]; while i <= j { while arr[i] < pivot { i += 1; } while arr[j] > pivot { j -= 1; } if i <= j { arr.swapAt(i, j); i += 1; j -= 1; } } arr.swapAt(i, end); return i; } func quick_sort(_ arr: inout [UInt32], begin: Int, end: Int) { if begin < end { let index = partition(&arr, begin, end); quick_sort(&arr, begin: begin, end: index - 1); quick_sort(&arr, begin: index, end: end); } } func test() { print("Size of array: ", terminator: ""); let size = Int(readLine()!)!; var arr = [UInt32](); for _ in 1 ... size { arr.append(arc4random_uniform(100)); } print("Original: "); print(arr); quick_sort(&arr, begin: 0, end: size - 1); print("Sorted: "); print(arr); } test();
code/divide_conquer/src/quick_sort/quick_sort2.cpp
#include <iostream> using namespace std; void swapit(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } int Mpartition(int arr[], int low, int high) { int i = low - 1; int j = low; for (; j < high; j++) if (arr[high] < arr[j]) { i++; swapit(&arr[j], &arr[i]); } swapit(&arr[high], &arr[i + 1]); return i + 1; } void quicksort(int arr[], int low, int high) { if (low < high) { int pi = Mpartition(arr, low, high); quicksort(arr, low, pi - 1); quicksort(arr, pi + 1, high); } } int main() { int arr[] = {14, 15, 13, 44, 56, 23, 8, 78, 36, 72}; int arrsize = sizeof(arr) / sizeof(arr[0]) - 1; quicksort(arr, 0, arrsize); for (int i = 0; i < 9; i++) cout << arr[i] << endl; }
code/divide_conquer/src/quick_sort/quicksort.java
// divide conquer | quick sort | Java // Part of Cosmos by OpenGenus Foundation public class QuickSort { private int []v; private int n; public String toString() { String result = ""; for(int i = 0; i < n; i++) { result += v[i] + " "; } return result; } public void quickSort(QuickSort v, int left, int right) { int i = left, j = right; int aux; int pivot = (left + right) / 2; while(i <= j) { while(v.v[i] < v.v[pivot]) { i++; } while(v.v[j] > v.v[pivot]) { j--; } if(i <= j) { aux = v.v[i]; v.v[i] = v.v[j]; v.v[j] = aux; i++; j--; } } if(left < j) { quickSort(v, left, j); } if(i < right) { quickSort(v, i, right); } } public static void main(String []args) { QuickSort obj = new QuickSort(); obj.n = 10; obj.v = new int[10]; for(int i = 0; i < 10; i++) { obj.v[i] = 10 - i; } System.out.println(obj); obj.quickSort(obj, 0, obj.n - 1); System.out.println(obj); } }
code/divide_conquer/src/search_in_a_rotated_array/search_in_a_rotated_array.cpp
/* Problem statement: Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element K. The task is to find the index of the given element K in the array A. */ #include <iostream> #include <vector> #define ll long long int ll findPivot(std::vector<ll> &v, ll low, ll high) { while (low < high) { // find mid element ll mid = low + (high - low) / 2; if (v[mid] < v[0]) { high = mid; } else { low = mid + 1; } } if (v[low] < arr[0]) { return low; } else { // pivot element does not exist return -1; } } ll findAns(std::vector<ll> &v, ll k, ll low, ll high) { while (low < high) { // find mid element ll mid = low + (high - low) / 2; if (v[mid] == k) { return mid; } if (v[mid] >= k) { high = mid; } else { low = mid + 1; } } if (v[low] == k) { return low; } else { // element does not exist in array return -1; } } int main() { ll test, n, k, pivot; std::cin >> test; // no. of test cases std::vector<ll> v; while (test--) { std::cin >> n; // size of array for (ll i = 0; i < n; i++) { ll num; std::cin >> num; v.push_back(num); } std::cin >> k; // element to be searched pivot = findPivot(v, 0, n - 1); // find pivot element if (pivot == -1) { // if pivot element does not exist, elements are // whole array is in ascending order std::cout << findAns(v, k, 0, n - 1) << "\n"; } else { if (k >= v[0]) { std::cout << findAns(v, k, 0, pivot - 1) << "\n"; } else { std::cout << findAns(v, k, pivot, n - 1) << "\n"; } } v.clear(); } return 0; } /* Input: 3 9 5 6 7 8 9 10 1 2 3 10 3 3 1 2 1 4 3 5 1 2 6 Output: 5 1 -1 */
code/divide_conquer/src/strassen_matrix_multiplication/main.cpp
//The following program contains the strassen algorithm along with the Currently Fastest Matrix Multiplication Algorithm for sparse matrices // Developed by Raphael Yuster and Uri Zwick // I have also included a time calculator in case anyone wanted to check time taken by each algorithms // Although mathematcially the fast multiplication algorithm should take less time, since it is of lesser order O(n^t) // however it has a large preceeding constant thus the effect of the algorthm can only be seen in larger matrices #include <algorithm> #include <chrono> #include <iostream> #include <random> #include <vector> std::vector<std::vector<int>> generator(int m, int n) { std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<std::mt19937::result_type> dist6(0, 1); std::vector<std::vector<int>> ans; for (int i = 0; i < m; i++) { std::vector<int> row; for (int j = 0; j < n; j++) { if ((i + j) % 5 != 5) row.push_back(dist6(rng)); else row.push_back(0); } ans.push_back(row); } return ans; } int f(const std::vector<std::vector<int>>& a) { return a[0][0]; } std::vector<std::vector<int>> retriever(const std::vector<std::vector<int>>& matrix, int x, int y) { std::vector<std::vector<int>> ans; for (int i = 0; i < x; i++) { std::vector<int> row; for (int j = 0; j < y; j++) row.push_back(matrix[i][j]); ans.push_back(row); } return ans; } std::vector<std::vector<int>> converter(const std::vector<std::vector<int>>& matrix) { auto noOfRows = matrix.size(); auto noOfCols = matrix[0].size(); std::vector<std::vector<int>>::size_type t = 1; std::vector<std::vector<int>>::size_type p; if (x > y) p = noOfRows; else p = noOfCols; while (t < p) t *= 2; p = t; int flag = 0; std::vector<std::vector<int>> ans; for (vector<vector<int>>::size_type i = 0; i < p; i++) { if (i >= noOfRows) flag = 1; std::vector<int> row; for (std::vector<int>::size_type j = 0; j < p; j++) { if (flag == 1) row.push_back(0); else { if (j >= noOfCols) row.push_back(0); else row.push_back(matrix[i][j]); } } ans.push_back(row); } return ans; } void print(const std::vector<std::vector<int>>& grid) { for (std::vector<std::vector<int>>::size_type i = 0; i < grid.size(); i++) { for (std::vector<int>::size_type j = 0; j < grid[i].size(); j++) std::cout << grid[i][j] << ' '; std::cout << std::endl; } } std::vector<std::vector<int>> add(const std::vector<std::vector<int>>& a, const std::vector<std::vector<int>>& b) { std::vector<std::vector<int>> ans; for (std::vector<std::vector<int>>::size_type i = 0; i < a.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < a[i].size(); j++) { int temp = a[i][j] + b[i][j]; row.push_back(temp); } ans.push_back(row); } return ans; } std::vector<std::vector<int>> subtract(const std::vector<std::vector<int>>& a, const std::vector<std::vector<int>>& b) { std::vector<std::vector<int>> ans; for (std::vector<std::vector<int>>::size_type i = 0; i < a.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < a[i].size(); j++) { int temp = a[i][j] - b[i][j]; row.push_back(temp); } ans.push_back(row); } return ans; } std::vector<std::vector<int>> naive_multi(const std::vector<std::vector<int>>& a, const std::vector<std::vector<int>>& b) { int s = 0; std::vector<std::vector<int>> ans; for (std::vector<std::vector<int>>::size_type i = 0; i < a.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < b[i].size(); j++) { s = 0; for (std::vector<int>::size_type k = 0; k < a[i].size(); k++) s += a[i][k] * b[k][j]; row.push_back(s); } ans.push_back(row); } return ans; } std::vector<std::vector<int>> strassen(const std::vector<std::vector<int>>& m1, const std::vector<std::vector<int>>& m2) { std::vector<std::vector<int>>::size_type s1 = m1.size(); std::vector<std::vector<int>>::size_type s2 = m2.size(); if (s1 > 2 && s2 > 2) { std::vector<std::vector<int>> a, b, c, d, e, f, g, h, ans; for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size() / 2; i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < m1[i].size() / 2; j++) row.push_back(m1[i][j]); a.push_back(row); } for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size() / 2; i++) { vector<int> row; for (std::vector<int>::size_type j = m1[i].size() / 2; j < m1[i].size(); j++) row.push_back(m1[i][j]); b.push_back(row); } for (std::vector<std::vector<int>>::size_type i = m1.size() / 2; i < m1.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < m1[i].size() / 2; j++) row.push_back(m1[i][j]); c.push_back(row); } for (std::vector<std::vector<int>>::size_type i = m1.size() / 2; i < m1.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = m1[i].size() / 2; j < m1[i].size(); j++) row.push_back(m1[i][j]); d.push_back(row); } for (std::vector<std::vector<int>>::size_type i = 0; i < m2.size() / 2; i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < m2[i].size() / 2; j++) row.push_back(m2[i][j]); e.push_back(row); } for (std::vector<std::vector<int>>::size_type i = 0; i < m2.size() / 2; i++) { vector<int> row; for (std::vector<int>::size_type j = m2[i].size() / 2; j < m2[i].size(); j++) row.push_back(m2[i][j]); f.push_back(row); } for (std::vector<std::vector<int>>::size_type i = m2.size() / 2; i < m2.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = 0; j < m2[i].size() / 2; j++) row.push_back(m2[i][j]); g.push_back(row); } for (std::vector<std::vector<int>>::size_type i = m2.size() / 2; i < m2.size(); i++) { vector<int> row; for (std::vector<int>::size_type j = m2[i].size() / 2; j < m2[i].size(); j++) row.push_back(m2[i][j]); h.push_back(row); } std::vector<std::vector<int>> p1, p2, p3, p4, p5, p6, p7; p1 = strassen(a, subtract(f, h)); p2 = strassen(add(a, b), h); p3 = strassen(add(c, d), e); p4 = strassen(d, subtract(g, e)); p5 = strassen(add(a, d), add(e, h)); p6 = strassen(subtract(b, d), add(g, h)); p7 = strassen(subtract(a, c), add(e, f)); std::vector<std::vector<int>> c1, c2, c3, c4; c1 = subtract(add(add(p5, p4), p6), p2); c2 = add(p1, p2); c3 = add(p3, p4); c4 = subtract(add(p1, p5), add(p3, p7)); int flag1, flag2; for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size(); i++) { std::vector<int> row; if (i < m1.size() / 2) flag1 = 0; else flag1 = 1; for (std::vector<int>::size_type j = 0; j < m2[i].size(); j++) { if (j < m2[i].size() / 2) { if (flag1 == 0) row.push_back(c1[i][j]); else row.push_back(c3[i - m1.size() / 2][j]); } else { if (flag1 == 0) row.push_back(c2[i][j - m2[i].size() / 2]); else row.push_back(c4[i - m1.size() / 2][j - m2[i].size() / 2]); } } ans.push_back(row); } return ans; } else { std::vector<std::vector<int>> v; v = naive_multi(m1, m2); return v; } } std::vector<std::vector<int>> fast_multi(const std::vector<std::vector<int>>& m1, const std::vector<std::vector<int>>& m2) { std::vector<int> ranges, ranges_c, ind; std::vector<std::vector<int>> ans; for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size(); i++) { int a = 0; int b = 0; for (std::vector<std::vector<int>>::size_type j = 0; j < m1[i].size(); j++) { if (m1[j][i] != 0) a += 1; if (m2[i][j] != 0) b += 1; } ranges.push_back(a * b); ranges_c.push_back(a * b); } sort(ranges.begin(), ranges.end()); int comp, index; for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size(); i++) { int s = 0; for (std::vector<std::vector<int>>::size_type j = 0; j <= i; j++) s += ranges[j]; s += (m1.size() - i - 1) * m1.size() * m1.size(); if (i == 0) { comp = s; index = 1; } else if (s < comp) { comp = s; index = i + 1; } } for (int g = 0; g < index; g++) { for (std::vector<std::vector<int>>::size_type i = 0; i < m1.size(); i++) if (ranges_c[i] == ranges[g]) { ind.push_back(i); break; } } for (std::vector<vector<int>>::size_type i = 0; i < m1.size(); i++) { int flag; int flag_search = 0; for (std::vector<int>::size_type j = 0; j < ind.size(); j++) if (i == ind[j]) { flag_search = 1; break; } std::vector<std::vector<int>> row, col; for (std::vector<int>::size_type j = 0; j < ind.size(); j++) { std::vector<int> temp1, temp2; temp1.push_back(m1[j][i]); temp2.push_back(m2[i][j]); col.push_back(temp1); row.push_back(temp2); } if (i == 0) { if (flag_search == 1) ans = naive_multi(col, row); else { std::vector<std::vector<int>> row_c, col_c; row_c = converter(row); col_c = converter(col); ans = retriever(strassen(col_c, row_c), m1.size(), m1.size()); } } else { std::vector<std::vector<int>> v1, v2; if (flag_search == 1) v1 = naive_multi(col, row); else { std::vector<std::vector<int>> row_c, col_c; row_c = converter(row); col_c = converter(col); v1 = retriever(strassen(col_c, row_c), m1.size(), m1.size()); } ans = add(v1, ans); } } return ans; } int main() { std::vector<vector<int>> matrix1, matrix2, v1, v2, v3; int i1, j1; int i2, j2; std::cout << "enter the dimensions of matrix1\n"; std::cin >> i1 >> j1; std::cout << '\n'; std::cout << "enter the dimensions of matrix2\n"; std::cin >> i2 >> j2; std::cout << '\n'; int x, y; for (x = 0; x < i1; x++) { std::vector<int> row; for (y = 0; y < j1; y++) { int temp; std::cout << "enter the " << x + 1 << " , " << y + 1 << " element for matrix1 - "; std::cin >> temp; row.push_back(temp); } matrix1.push_back(row); } for (x = 0; x < i2; x++) { std::vector<int> row; for (y = 0; y < j2; y++) { int temp; std::cout << "enter the " << x + 1 << " , " << y + 1 << " element for matrix2 - "; std::cin >> temp; row.push_back(temp); } matrix2.push_back(row); } //print(matrix1); std::vector<std::vector<int>> m1, m2, m3, m4; m1 = converter(matrix1); m2 = converter(matrix2); //print(m1); //cout << "a\n"; //print(m2); //cout <<"a\n"; /* * m3 = generator(1024, 1024); * m4 = generator(1024, 1024); */ auto start = std::chrono::high_resolution_clock::now(); v1 = retriever(naive_multi(m1, m2), i1, j2); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(start - stop); std::cout << "tiime taken by function" << duration.count() << endl; //print(v1); auto start2 = std::chrono::high_resolution_clock::now(); v2 = retriever(strassen(m1, m2), i1, j2); auto stop2 = std::chrono::high_resolution_clock::now(); auto duration2 = std::chrono::duration_cast<microseconds>(start2 - stop2); std::cout << "tiime taken by function" << duration2.count() << endl; /* * auto start_3 = std::chrono::high_resolution_clock::now(); * v3 = retriever(fast_multi(m1, m2), i_1, j_2); * auto stop_3 = std::chrono::high_resolution_clock::now(); * auto duration_3 = std::chrono::duration_cast<microseconds>(start_3 - stop_3); * * * cout << "tiime taken by function" << duration_3.count() << endl; */ //print(v2); print(v1); return 0; }
code/divide_conquer/src/strassen_matrix_multiplication/strassen.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue May 29 13:36:32 2018 @author: Sahit """ import numpy as np def Correction(matrix_1, matrix_2): r = max(matrix_1.shape[0], matrix_1.shape[1], matrix_2.shape[0], matrix_2.shape[1]) i = 1 while i < r: i = i * 2 return i """ result = np.zeros((i,i)) for i in xrange(matrix.shape[0]): for j in xrange(matrix.shape[1]): result[i][j] = matrix[i][j] return result """ def Modification(matrix, p): result = np.zeros((p, p)) for i in range(matrix.shape[0]): for j in range(matrix.shape[1]): result[i][j] = matrix[i][j] return result def Extraction(matrix, x, y): result = np.zeros((x, y)) for i in range(x): for j in range(y): result[i][j] = matrix[i][j] return result def Strassen(matrix_1, matrix_2): r = matrix_1.shape[0] // 2 if r == 0: return matrix_1.dot(matrix_2) else: a = matrix_1[:r, :r] b = matrix_1[:r, r:] c = matrix_1[r:, :r] d = matrix_1[r:, r:] e = matrix_2[:r, :r] f = matrix_2[:r, r:] g = matrix_2[r:, :r] h = matrix_2[r:, r:] p1 = Strassen(a, f - h) p2 = Strassen(a + b, h) p3 = Strassen(c + d, e) p4 = Strassen(d, g - e) p5 = Strassen(a + d, e + h) p6 = Strassen(b - d, g + h) p7 = Strassen(a - c, e + f) s1 = p5 + p4 + p6 - p2 s2 = p1 + p2 s3 = p3 + p4 s4 = p1 + p5 - p3 - p7 result = np.zeros((r * 2, r * 2)) for i in range(r): for j in range(r): result[i][j] = s1[i][j] for i in range(r): for j in range(r): result[i][r + j] = s2[i][j] for i in range(r): for j in range(r): result[r + i][j] = s3[i][j] for i in range(r): for j in range(r): result[r + i][r + j] = s4[i][j] return result print("enter the dimensions of the first matrix") r1 = list(map(int, input().split())) x1, y1 = r1[0], r1[1] print("enter the dimensions of the second matrix") r2 = list(map(int, input().split())) x2, y2 = r2[0], r2[1] m1 = [] for i in range(x1): row = [] for j in range(y1): print("enter the ", i + 1, j + 1, " element of the first matrix") row.append(input()) m1.append(row) m2 = [] for i in range(x2): row = [] for j in range(y2): print("enter the ", i + 1, j + 1, " element of the second matrix") row.append(input()) m2.append(row) matrix1 = np.array(m1) matrix2 = np.array(m2) f = Correction(matrix1, matrix2) answer = Extraction( Strassen(Modification(matrix1, f), Modification(matrix2, f)), x1, y2 ) print(answer)
code/divide_conquer/src/tournament_method_to_find_min_max/tournament_method_to_find_min_max.c
#include<stdio.h> struct pair { int min; int max; }; struct pair getMinMax(int arr[], int low, int high) { struct pair minmax, mml, mmr; int mid; if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return (minmax); } if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return (minmax); } mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return (minmax); } int main() { int arr_size; printf("Enter size of the Array: \n"); scanf("%d", &arr_size); int arr[arr_size]; printf("Enter %d Integers:- \n", arr_size); int i; for (i = 0; i < arr_size; ++i) scanf("%d", &arr[i]); struct pair minmax = getMinMax(arr, 0, arr_size - 1); printf("Minimum element is %d \n", minmax.min); printf("Maximum element is %d \n", minmax.max); return (0); }
code/divide_conquer/src/warnock_algorithm/warnock_algorithm.pde
/* divide conquer | warnock's Algorithm | Processing Part of Cosmos by OpenGenus Foundation National University from Colombia Author:Andres Vargas, Jaime Gitub: https://github.com/jaavargasar webpage: https://jaavargasar.github.io/ Language: Processing Description: This is a implementation of warnock's Algorithm in 2D plane. This algorithm is an implementation of divide and conquer */ import java.util.*; void setup() { size(600, 600); background(250); createPicture1(); createPicture2(); //another picture that you can try the warnock's algorithm loadPixels(); warnockAlgorithm(0,height,width,0); } //Creating picture one void createPicture1(){ pushStyle(); noStroke(); fill(#FFFF00);//yellow color rect(104,82,100,100); rect(400,422,100,100); fill(#FF0000); //red color rect(350,82,100,100); rect(104+60,82+45,100,100); popStyle(); } //creating picture 2 void createPicture2(){ pushStyle(); strokeWeight(4); fill(#008000); //green color triangle(142,82,142+200,82+60,142-20,82+100); noStroke(); fill(#008080);//teal color rect(150+62,82+150,200,100); fill(#FF00FF); ellipse(150+62+150,82+150+50,100,100); fill(#FFFF00); rect(300,450,50,110); popStyle(); pushStyle(); fill(#FFFF00); strokeWeight(4); rect(300-100,450,50,110); popStyle(); } //warnock's Algorithm void warnockAlgorithm(int x1,int y1,int y2, int x2){ HashSet<Object> colors = new HashSet<Object>(); int counter=0; int iniPixel= x2 + x1*width; if( iniPixel>=360000) iniPixel=359999; Object pix=pixels[iniPixel]; colors.add(pix); for ( int y = y1-1; y >=x1; y--) { //height for ( int x = y2-1; x >= x2; x--) { //width int loc = x + y*width; //check if I've already added a color if( check(pixels[loc], colors) ){ colors.add(pixels[loc]); } } } counter= colors.size(); if( counter>2){ //strokeWeight(2); line( x2+(y2-x2)/2, x1, x2+(y2-x2)/2, y1); line(x2, x1+(y1-x1)/2, y2, x1+(y1-x1)/2 ); //divide and conquer implementation warnockAlgorithm( x1+(y1-x1)/2,y1,y2,x2+(y2-x2)/2); warnockAlgorithm( x1,x1+(y1-x1)/2,y2,x2+(y2-x2)/2); warnockAlgorithm(x1,x1+(y1-x1)/2,x2+(y2-x2)/2,x2); warnockAlgorithm(x1+(y1-x1)/2,y1,x2+(y2-x2)/2,x2); } return; } //check if I've already have added a new color boolean check(Object pix,HashSet colors){ if( colors.contains(pix) ) return false; //si ya lo contiene return true; //si no lo contiene }
code/divide_conquer/src/x_power_y/x_power_y.c
#include <stdio.h> float power(float x, int y) { if (y == 0) return (1); float temp = power(x, y / 2); if (y % 2 == 0) return (temp * temp); else { if (y > 0) return (x * temp * temp); else return (temp * temp / x); } } int main() { float x; printf("Enter x (float): "); scanf("%f", &x); int y; printf("Enter y (int): "); scanf("%d", &y); printf("%f^%d == %f\n", x, y, power(x, y)); return (0); }
code/divide_conquer/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/dynamic_programming/src/Climbing Stairs/solution.cpp
// recursion // TC - O(2^n) , SC - O(1) class Solution { public: int func(int n){ if(n <= 1){ return n; } return func(n-1) + func(n-2); } int climbStairs(int n) { return func(n+1); } }; // memoisation // TC - O(n), SC - O(n) + O(n) class Solution { public: int func(int n, vector<int> &dp){ if(n <= 1){ return n; } if(dp[n] !=-1){ return dp[n]; } return dp[n] = func(n-1, dp) + func(n-2, dp); } int climbStairs(int n) { vector<int>dp(n+2, -1); return func(n+1, dp); } }; // tabulation // TC - O(n), SC - O(n) class Solution { public: int climbStairs(int n) { vector<int> dp(n+2, -1); dp[0] = 0, dp[1] = 1; for(int i = 2; i <= n+1 ;i++){ dp[i] = dp[i-1] + dp[i-2]; } return dp[n+1]; } }; // space optimised // TC - O(n) , SC - O(1) class Solution { public: int climbStairs(int n) { int prev1 = 1, prev2 = 0; for(int i = 1;i<=n;i++){ int ans = prev1 + prev2; prev2 = prev1; prev1 = ans; } return prev1; } };
code/dynamic_programming/src/Count_Subsequence_Having_Product_Less_Than_K/Solution.cpp
#include<iostream> #include<cstring> using namespace std; int dp[10005][10005]; int helper(int a[], int n, int k , int product) { // base case if(n==0) { return 0; } if(product > k) { return 0; } if(dp[n][product] !=-1) { return dp[n][product]; } int include = product * a[n-1]; int exclude =product; int count =0; if( include < k) { count++; } count += helper(a,n-1,k,include) + helper(a,n-1,k,exclude); dp[n][product] =count; return dp[n][product]; } int solve(int a[], int n, int k) { dp[k+1][n+1]; memset(dp,-1,sizeof(dp)); int product =1; return helper(a,n,k,product); } int main() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } int k; cout<<"Enter the value of k"<<endl; cin>>k; cout<<solve(a,n,k)<<endl; return 0; }
code/dynamic_programming/src/README.md
# Dynamic Programming Dynamic programming approach is similar to divide and conquer in breaking down the problem into smaller and yet smaller possible sub-problems. But unlike, divide and conquer, these sub-problems are not solved independently. Rather, results of these smaller sub-problems are remembered and used for similar or overlapping sub-problems. Dynamic programming is used where we have problems, which can be divided into similar sub-problems, so that their results can be re-used. Mostly, these algorithms are used for optimization. Before solving the in-hand sub-problem, dynamic algorithm will try to examine the results of the previously solved sub-problems. The solutions of sub-problems are combined in order to achieve the best solution. Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/dynamic_programming/src/array_median/array_median.c
#include <stdio.h> void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j <= high- 1; j++) { if (arr[j] <= pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } float median(int n, int arr[n]) { if (n % 2 != 0) return (float)arr[n / 2]; return ((float)(arr[(n - 1) / 2] + arr[n / 2]) / 2.0); } int main() { int n; printf("Enter size of the Array\n"); scanf("%d",&n); int arr[n]; printf("Enter %d integers\n",n); for (int i = 0; i < n; i++) scanf("%d",&arr[i]); quickSort(arr,0,n - 1); printf("Median = %f\n",median(n,arr)); return (0); }
code/dynamic_programming/src/array_median/array_median.cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; float median(vector<int> arr) { int n = arr.size(); if (n % 2 != 0) return (float)arr[n / 2]; return (float)(arr[(n - 1) / 2] + arr[n / 2]) / 2; } int main() { int n; cout << "Enter size of the Array"; cin >> n; vector<int> arr(n); cout << "Enter " << n << " integers"; for (int i = 0; i < n; i++) cin >> arr[i]; sort(arr.begin(), arr.end()); cout << "Median= " << median(arr); return 0; }
code/dynamic_programming/src/array_median/array_median.exs
defmodule ArrayMedian do def get_median(array) when is_list(array) do list_nums = Enum.sort(array) half = length(list_nums) |> div(2) if length(list_nums) |> rem(2) != 0 do # odd length -> middle number mid = half + 1 Enum.reduce_while(list_nums, 1, fn el, ^mid -> {:halt, el} _el, acc -> {:cont, acc + 1} end) else # even length -> mean of the 2 middle numbers {n1, n2} = Enum.reduce_while(list_nums, 1, fn el, {n1} -> {:halt, {n1, el}} el, ^half -> {:cont, {el}} _el, acc -> {:cont, acc + 1} end) (n1 + n2) / 2 end end end # Test data from array_median.php test_data = [ [[-1], -1], [[0], 0], [[1], 1], [[-1, 0, 1], 0], [[1, 2, 3], 2], [[-1, -2, -3], -2], [[1, 2.5, 3], 2.5], [[-1, -2.5, -3], -2.5], [[1, 2, 2, 4], 2], [[1, 2, 3, 4], 2.5], [[2, 2, 1, 4], 2], [[3, 2, 1, 4], 2.5], [[-1, -2, -2, -4], -2], [[-1, -2, -3, -4], -2.5] ] Enum.each( test_data, fn data = [arr, expected] -> result = ArrayMedian.get_median(arr) if result == expected do IO.puts("Success!!") else IO.puts("Failure") IO.inspect(data, label: "Problem here") IO.inspect(result, label: "wrong") end end )
code/dynamic_programming/src/array_median/array_median.java
import java.util.*; // Part of Cosmos by OpenGenus Foundation public class Median{ public static void main(String[] args) { int length; int median; System.out.print("Enter Length of array "); Scanner scanner = new Scanner(System.in); length = scanner.nextInt(); int array[] = new int[length]; System.out.printf("Enter %d values: \n", length); for (int i=0 ; i<length ; i++){ array[i] = scanner.nextInt(); } Arrays.sort(array); if (array.length % 2 == 0){ median = (((array[array.length /2]) + (array[array.length/2 - 1])) / 2); } else { median = array[array.length / 2]; } System.out.printf("The median is %d\n", median); } }
code/dynamic_programming/src/array_median/array_median.php
<?php /** * Part of Cosmos by OpenGenus Foundation */ /** * Finds median in array of numbers * * @param array $arr array of numbers * @return int median */ function median(array $arr) { sort($arr); $cnt = count($arr); if ($cnt % 2) { return $arr[floor(($cnt - 1) / 2)]; } return ($arr[floor($cnt / 2)] + $arr[floor($cnt / 2) - 1]) / 2; } echo "median\n"; $test_data = [ [[-1], -1], [[0], 0], [[1], 1], [[-1, 0, 1], 0], [[1, 2, 3], 2], [[-1, -2, -3], -2], [[1, 2.5, 3], 2.5], [[-1, -2.5, -3], -2.5], [[1, 2, 2, 4], 2], [[1, 2, 3, 4], 2.5], [[2, 2, 1, 4], 2], [[3, 2, 1, 4], 2.5], [[-1, -2, -2, -4], -2], [[-1, -2, -3, -4], -2.5], ]; foreach ($test_data as $test_case) { $input = $test_case[0]; $expected = $test_case[1]; $result = median($input); printf( " input %s, expected %s, got %s: %s\n", str_replace(["\n", ' '], ['', ' '], var_export($input, true)), var_export($expected, true), var_export($result, true), ($expected === $result) ? 'OK' : 'FAIL' ); }
code/dynamic_programming/src/array_median/array_median.py
import sys # Part of Cosmos by OpenGenus Foundation def median(nums): """ Calculates the median of a list of numbers. import median from statistics in python 3.4 and above. """ sorted_nums = sorted(nums) len_nums = len(nums) odd = len_nums % 2 # If the length is odd, the median is the middle value of the sorted list. if odd: return sorted_nums[(len_nums - 1) // 2] # Otherwise it's the average of the middle two. return (nums[len_nums // 2] + nums[(len_nums // 2) - 1]) / 2 def main(): """Calculates median of numbers in stdin.""" # Read stdin until EOF nums_string = sys.stdin.read() # Split on whitespace num_strings = nums_string.split() # Make a new list of floats of all the non-whitespace values. nums = [float(i) for i in num_strings if i] # Print median if not nums: print("You didn't enter any numbers.") else: print(median(nums)) def test_median(): """Test the median function for correctness.""" assert median([1, 2, 3]) == 2 assert median([1, 2.9, 3]) == 2.9 assert median([1, 2, 3, 4]) == 2.5 assert median([2, 1, 4, 3]) == 2.5 assert median([1, 3, 3, 4, 5, 6, 8, 9]) == 4.5 def test_main(): """Test the main function for correctness.""" # Backup stdin.read _stdin_read = sys.stdin.read # patch main's print def print_patch(arg): assert arg == 5.5 main.__globals__["print"] = print_patch # patch main's stdin class stdin_patch: def read(self): return "1 2 3 4 5.5 6 7 8 9\n" main.__globals__["sys"].stdin = stdin_patch() # invoke main with mocks main() # undo patches main.__globals__["sys"].stdin.read = _stdin_read del main.__globals__["print"] if __name__ == "__main__": test_median() # test_main() main()
code/dynamic_programming/src/array_median/array_median.rb
# Part of Cosmos by OpenGenus Foundation def median(*nums) nums.sort! if nums.size.odd? nums[(nums.size + 1) / 2 - 1] else (nums[nums.size / 2 - 1] + nums[nums.size / 2]).fdiv(2) end end
code/dynamic_programming/src/array_median/array_median.rs
// Part of Cosmos by OpenGenus Foundation fn median(arr: &[i32]) -> f64 { let len = arr.len(); if len % 2 == 0 { (arr[len / 2] + arr[len / 2 - 1]) as f64 / 2.0 } else { arr[(len - 1) / 2] as f64 } } fn main() { let arr = vec![1, 3, 3, 4, 5, 6, 8, 9]; let median = median(&arr); //Assuming input is sorted array println!("{}", median); }
code/dynamic_programming/src/assembly_line_scheduling/assembly_line_scheduling.cpp
// Part of OpenGenus Cosmos // A C++ program to find minimum possible // time by the car chassis to complete #include <bits/stdc++.h> using namespace std; #define NUM_LINE 2 #define NUM_STATION 4 // Utility function to find a minimum of two numbers int min(int a, int b) { return a < b ? a : b; } int carAssembly(int a[][NUM_STATION], int t[][NUM_STATION], int *e, int *x) { int T1[NUM_STATION], T2[NUM_STATION], i; // time taken to leave first station in line 1 T1[0] = e[0] + a[0][0]; // time taken to leave first station in line 2 T2[0] = e[1] + a[1][0]; // Fill tables T1[] and T2[] using the // above given recursive relations for (i = 1; i < NUM_STATION; ++i) { T1[i] = min(T1[i - 1] + a[0][i], T2[i - 1] + t[1][i] + a[0][i]); T2[i] = min(T2[i - 1] + a[1][i], T1[i - 1] + t[0][i] + a[1][i]); } // Consider exit times and retutn minimum return min(T1[NUM_STATION - 1] + x[0], T2[NUM_STATION - 1] + x[1]); } // Driver Code int main() { int a[][NUM_STATION] = {{4, 5, 3, 2}, {2, 10, 1, 4}}; int t[][NUM_STATION] = {{0, 7, 4, 5}, {0, 9, 2, 8}}; int e[] = {10, 12}, x[] = {18, 7}; cout << carAssembly(a, t, e, x); return 0; } // This is code is contributed by rathbhupendra
code/dynamic_programming/src/best_time_to_sell_stock_II/best_time_to_sell_stock_II.cpp
// You are given an integer array prices where prices[i] is the price of a given stock on the ith day. // On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. // Find and return the maximum profit you can achieve. // Example 1: // Input: prices = [7,1,5,3,6,4] // Output: 7 // Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. // Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. // Total profit is 4 + 3 = 7. #include<bits/stdc++.h> class Solution { public: int maxProfit(vector<int>& arr) { int pr = 0; for(int i=1; i<arr.size(); i++){ if(arr[i]>arr[i-1]){ pr+= arr[i]-arr[i-1]; } } return pr; } };
code/dynamic_programming/src/binomial_coefficient/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)