diff --git a/README.md b/README.md index c3b9afae..7ac363a4 100644 --- a/README.md +++ b/README.md @@ -1,68 +1,75 @@ -# :abacus: Algorithms and Data Structures +

+

🧮Algorithms and Data Structures

+

This repository provides several classic algorithms and data structures in **Computer Science**, as well as some extra problems that are frequently encountered in programming challenges. -In order to achieve greater coverage and encourage more people to contribute to the project, the algorithms are available in the following languages: **C**, **C++**, **Java**, **Python**, **Go**, **Ruby**, **Javascript**, **Swift**, **Rust**, **Scala** and **Kotlin**. +In order to achieve greater coverage and encourage more people to contribute to the project, the algorithms are available in the following languages: **C**, **C++**, **Java**, **Python**, **Go**, **Ruby**, **Javascript**, **Swift**, **Rust**, **Scala**, **Kotlin** and **Elixir**. You can quickly access an [online compiler](https://onecompiler.com/) by clicking on the symbols corresponding to the desired programming languages in the top rows of each table. - + + @@ -121,6 +128,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -179,6 +191,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -237,6 +254,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -295,6 +317,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -353,6 +380,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -411,6 +443,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -469,6 +506,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -527,6 +569,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -585,6 +632,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -643,6 +695,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -701,6 +758,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -759,6 +821,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -817,6 +884,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -875,6 +947,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -933,6 +1010,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -991,6 +1073,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1049,6 +1136,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1107,6 +1199,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1165,9 +1262,14 @@ In order to achieve greater coverage and encourage more people to contribute to + - + + @@ -1281,9 +1388,14 @@ In order to achieve greater coverage and encourage more people to contribute to + - + + @@ -1397,6 +1514,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1455,6 +1577,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1513,6 +1640,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1571,6 +1703,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1629,66 +1766,76 @@ In order to achieve greater coverage and encourage more people to contribute to +
AlgorithmsAlgorithms - + - + - + - + - + - + - + - + - + - + - + + + + +
Dijkstra's Algorithm + + + +
Floyd–Warshall Algorithm + + + +
Binary Search + + + +
Graph Search + + + +
Linear Search (Iterative) + + + +
Linear Search (Recursive) + + + +
Linear Search (Sentinel) + + + +
Interpolation Search + + + +
Travelling Salesman + + + +
Hamiltonian Cycle + + + +
Connected Components + + + +
Exponentiation (Iterative) + + + +
Exponentiation (Recursive) + + + +
Factorial (Iterative) + + + +
Factorial (Recursive) + + + +
Fibonacci (Iterative) + + + +
Fibonacci (Recursive) + + + +
Fibonacci (Memoization) + + + +
Max (Recursive) + + + +
Min and Max (Iterative)Min and Max (Iterative) @@ -1223,6 +1325,11 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
Min and Max (Recursive) + + + +
Min and Max (D&C)Min and Max (D&C) @@ -1339,6 +1451,11 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
Knight's Tour + + + +
Tower of Hanoi + + + +
Genetic Algorithm + + + +
Huffman's Algorithm + + + +
LZ77 Algorithm + + + +
- + + @@ -1747,6 +1894,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1805,6 +1957,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1863,6 +2020,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1921,6 +2083,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -1979,6 +2146,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2037,6 +2209,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2095,6 +2272,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2153,6 +2335,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2211,6 +2398,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2269,9 +2461,14 @@ In order to achieve greater coverage and encourage more people to contribute to + - + + @@ -2385,6 +2587,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2443,9 +2650,14 @@ In order to achieve greater coverage and encourage more people to contribute to + - + + @@ -2559,6 +2776,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2617,66 +2839,76 @@ In order to achieve greater coverage and encourage more people to contribute to +
Data StructuresData Structures - + - + - + - + - + - + - + - + - + - + - + + + + +
Binary Tree + + + +
Binary Search Tree + + + +
Double-ended Queue + + + +
Queue + + + +
Dynamic Queue + + + +
Graph + + + +
Circular Linked List + + + +
Singly Linked List + + + +
Doubly Linked List + + + +
Unordered Linked List + + + +
Sorted Linked ListSorted Linked List @@ -2327,6 +2524,11 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
Skip List + + + +
Stack + + + +
Dynamic StackDynamic Stack @@ -2501,6 +2713,11 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
Ring Buffer + + + +
Hash Table + + + +
- + - + @@ -2735,6 +2967,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2793,6 +3030,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2851,6 +3093,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2909,6 +3156,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -2967,6 +3219,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3025,6 +3282,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3083,6 +3345,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3141,6 +3408,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3199,6 +3471,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3257,6 +3534,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3315,6 +3597,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3373,6 +3660,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3431,6 +3723,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3489,6 +3786,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3547,69 +3849,79 @@ In order to achieve greater coverage and encourage more people to contribute to +
Sorting AlgorithmsSorting Algorithms - + - + - + - + - + - + - + - + - + - + - + + + + + +
Bogosort + + + +
Bubble Sort + + + +
Bucket Sort + + + +
Cocktail Sort + + + +
Comb Sort + + + +
Counting Sort + + + +
Gnome Sort + + + +
Heapsort + + + +
Insertion Sort + + + +
Merge Sort + + + +
Quicksort + + + +
Radix Sort + + + +
Selection Sort + + + +
Shell Sort + + + +
Timsort + + + +
- + - + - + + - + + @@ -3781,9 +4103,14 @@ In order to achieve greater coverage and encourage more people to contribute to + - + + @@ -3897,6 +4229,11 @@ In order to achieve greater coverage and encourage more people to contribute to + @@ -3955,9 +4292,14 @@ In order to achieve greater coverage and encourage more people to contribute to + - + + - + +
ExtraExtra - + - + - + - + - + - + - + - + - + - + - + + + + + +
Queue using StacksQueue using Stacks @@ -3665,9 +3977,14 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
Two-Sum ProblemTwo-Sum Problem @@ -3723,6 +4040,11 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
Palindrome + + + +
IsogramIsogram @@ -3839,6 +4166,11 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
Leibniz Formula for Pi + + + +
Maze-Solving Algorithm + + + +
Rotten OrangesRotten Oranges @@ -4013,9 +4355,14 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
Find Distinct SubsetsFind Distinct Subsets @@ -4071,6 +4418,11 @@ In order to achieve greater coverage and encourage more people to contribute to + + + +
@@ -4080,3 +4432,7 @@ In order to achieve greater coverage and encourage more people to contribute to Feel free to contribute to the project, all contributions are welcome. :grin: If you have questions about how to contribute, take a look at the [CONTRIBUTING](CONTRIBUTING.md) file. + +

+[🔼 Back to top](https://github.com/kelvins/algorithms-and-data-structures?tab=readme-ov-file#abacus-algorithms-and-data-structures) + diff --git a/logos/elixir.svg b/logos/elixir.svg new file mode 100644 index 00000000..44d8f7d7 --- /dev/null +++ b/logos/elixir.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + file_type_elixir + + + + + + + + \ No newline at end of file diff --git a/src/c/README.md b/src/c/README.md new file mode 100644 index 00000000..35866cda --- /dev/null +++ b/src/c/README.md @@ -0,0 +1,118 @@ +## C Language Basic Syntax Review +C language is one of the most popular general-purpose programming language developed by Dennis Ritchie at Bell laboratories for UNIX operating system. The initial release of C Language was in the year 1972. Most of the desktop operating systems are written in C Language. + +Key features: +- Structured Programming +- Popular system programming language +- UNIX, MySQL and Oracle are completely written in C. +- Supports variety of platforms +- Efficient and also handle low-level activities. +- As fast as assembly language and hence used as system development language. + + +#### 1. Read inputs +````c +#include +int main() +{ + char name[50]; + printf("Enter name:"); + scanf("%s", &name); + printf("Hello %s" , name ); + return 0; + +} +```` +#### Loops and Conditionals + +##### 2. If-Else: + +When ever you want to perform a set of operations based on a condition if-else is used. +```c +if(conditional-expression) { + // code +} else { + // code +} +``` +You can also use if-else for nested Ifs and if-else-if ladder when multiple conditions are to be performed on a single variable. + +##### 3. Switch: + +Switch is an alternative to if-else-if ladder. + +````c +switch(conditional-expression) { +case value1: + // code + break; // optional +case value2: + // code + break; // optional +... + +default: + // code to be executed when all the above cases are not matched; +} +```` + +##### 4. For: + +For loop is used to iterate a set of statements based on a condition. + +````c +for(Initialization; Condition; Increment/decrement){ + // code +} +```` + +##### 5. While: + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance. + +````c +while(condition) { + // code +} +```` + +##### 6. Do-While: + +Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once. + +````c +do { + // code +} while (condition); + +```` +#### 7. Arrays +Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index. Index starts from 0 to size-1. + +1. One dimentional Array: ` data-type array-name[size];` +2. Two dimensional array: `data-type array-name[size][size];` + +#### 8. Functions +Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. + +Two types of functions are present in C + +1. Library Functions: Library functions are the in-built functions which are declared in header files like `printf()`, `scanf()`, `puts()`, `gets()` etc., +2. User defined functions: User defined functions are the ones which are written by the programmer based on the requirement. + + +##### 9. How to declare a Function +```c +return_type function_name(parameters);` +``` +##### How to call a Function +```c +function_name (parameters) +``` + +##### How to define a FunctionHow to define a Function +```c +return_type function_name(parameters) { + //code +} +``` \ No newline at end of file diff --git a/src/cpp/README.md b/src/cpp/README.md new file mode 100644 index 00000000..389da78e --- /dev/null +++ b/src/cpp/README.md @@ -0,0 +1,123 @@ +## C++ Language Basic Syntax Review +C++ is one of the most popular programming languages. C++ can be found in todays operating systems, Graphical User Interfaces, and embedded systems. C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be reused, lowering development costs. Note, C++ is an extension of C. + +Key features: + +- Supports different platforms like Windows, various Linux flavours, MacOS etc +- C++ supports OOPS concepts like Inheritance, Polymorphism, Encapsulation and Abstraction. +- Case-sensitive +- C++ is a compiler based language +- C++ supports structured programming language +- C++ provides alot of inbuilt functions and also supports dynamic memory allocation. +- Like C, C++ also allows you to play with memory using Pointers. + + +#### 1. Read inputs +````cpp +#include +#include +using namespace std; + +int main() +{ + string name; + cout << "Enter name:"; + getline (cin, name); + cout << "Hello " << name; + return 0; +} +} +```` +#### Loops and Conditionals + +##### 2. If-Else: + +When ever you want to perform a set of operations based on a condition if-else is used. +```cpp +if(conditional-expression) { + // code +} else { + // code +} +``` +You can also use if-else for nested Ifs and if-else-if ladder when multiple conditions are to be performed on a single variable. + +##### 3. Switch: + +Switch is an alternative to if-else-if ladder. + +````cpp +switch(conditional-expression) { +case value1: + // code + break; // optional +case value2: + // code + break; // optional +... + +default: + // code to be executed when all the above cases are not matched; +} +```` + +##### 4. For: + +For loop is used to iterate a set of statements based on a condition. + +````cpp +for(Initialization; Condition; Increment/decrement){ + // code +} +```` + +##### 5. While: + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance. + +````cpp +while(condition) { + // code +} +```` + +##### 6. Do-While: + +Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once. + +````cpp +do { + // code +} while (condition); + +```` +#### 7. Arrays +Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index. Index starts from 0 to size-1. + +1. One dimentional Array: ` data-type array-name[size];` +2. Two dimensional array: `data-type array-name[size][size];` + +#### 8. Functions +Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. + +Two types of functions are present in C++ + +1. Library Functions: Library functions are the in-built functions which are declared in header files like `floor(x)`, `tolower(x)`, `toupper()` etc., +2. User defined functions: User defined functions are the ones which are written by the programmer based on the requirement. + + +##### How to declare a Function +```cpp +return_type function_name(parameters);` +``` +##### How to call a Function +```cpp +function_name (parameters) +``` + +##### How to define a FunctionHow to define a Function +```cpp +return_type function_name(parameters) { + //code +} +``` \ No newline at end of file diff --git a/src/elixir/CalculatePi.ex b/src/elixir/CalculatePi.ex new file mode 100644 index 00000000..b4b6c9f6 --- /dev/null +++ b/src/elixir/CalculatePi.ex @@ -0,0 +1,31 @@ +# Module to calculate an approximation of Pi +defmodule PiApproximation do + + # Function to calculate pi given number of terms + def calculate_pi(terms) do + + # Initialize pi accumulator + pi = 0.0 + + # Reduce over 1..terms range + # Accumulator is a tuple with pi, denominator, and operation + Enum.reduce(1..terms, {pi, 1.0, 1.0}, fn _, {acc_pi, acc_denom, acc_op} -> + + # Calculate new pi value + new_pi = acc_pi + acc_op * (4.0 / acc_denom) + + # Return tuple with updated values + {new_pi, acc_denom + 2.0, -acc_op} + end) |> elem(0) + end + +end + +# Number of terms to approximate +terms = 100_000 + +# Call approximation function +result = PiApproximation.calculate_pi(terms) + +# Print result +IO.puts(result) \ No newline at end of file diff --git a/src/elixir/FactorialIterative.ex b/src/elixir/FactorialIterative.ex new file mode 100644 index 00000000..c509bde0 --- /dev/null +++ b/src/elixir/FactorialIterative.ex @@ -0,0 +1,26 @@ +defmodule Factorial do + # Define a module called Factorial. + + def factorial(n) when n >= 0 do + # Calculate the factorial using Enum.reduce. + Enum.reduce(1..n, 1, &(&1 * &2)) + end + + defp format_factorial(i, result) do + # Format the output string. + "#{i}! = #{result}" + end + + def main do + # Entry point of the program. + nums = [0, 1, 2, 3, 4, 5] + + Enum.each(nums, fn i -> + # Iterate through the list of numbers. + result = factorial(i) + IO.puts(format_factorial(i, result)) + end) + end +end + +Factorial.main() # Execute the program. diff --git a/src/elixir/FactorialRecursive.ex b/src/elixir/FactorialRecursive.ex new file mode 100644 index 00000000..2ac02996 --- /dev/null +++ b/src/elixir/FactorialRecursive.ex @@ -0,0 +1,23 @@ +# Define Math module for math utilities +defmodule Math do + + # Recursive factorial function + def factorial(0), do: 1 # Base case + + def factorial(n) when n > 0 do + # Recursive case + n * factorial(n-1) + end + +end + +# Array of numbers to get factorials for +nums = [0, 1, 2, 3, 4, 5] + +# Loop through the nums array +for i <- nums do + + # Calculate and print factorial + IO.puts "#{i}! = #{Math.factorial(i)}" + +end \ No newline at end of file diff --git a/src/elixir/FibonacciIterative.ex b/src/elixir/FibonacciIterative.ex new file mode 100644 index 00000000..295ae7b5 --- /dev/null +++ b/src/elixir/FibonacciIterative.ex @@ -0,0 +1,24 @@ +# Define a Fibonacci module +defmodule Fib do + + # Function to calculate nth Fibonacci number + def fibonacci(n) when n >= 0 do + + # Initialize starting values + last = 0 + curr = 1 + + # Use Enum.reduce as a loop from 0 to n-1 + Enum.reduce(0..(n-1), {last, curr}, fn _, {last, curr} -> + + # Update last and curr, returning as a tuple + {curr, curr + last} + end) + + # Return the last value after reducing + |> elem(0) + end +end + +# Print 10th Fibonacci number +IO.puts(Fib.fibonacci(10)) \ No newline at end of file diff --git a/src/elixir/FibonacciRecursive.ex b/src/elixir/FibonacciRecursive.ex new file mode 100644 index 00000000..9ca4b823 --- /dev/null +++ b/src/elixir/FibonacciRecursive.ex @@ -0,0 +1,14 @@ +# Define a Fibonacci module +defmodule Fibonacci do + # Base case: If n is 0 or 1, return n. + def fibonacci(n) when n <= 1, do: n + + # Recursive case: Calculate the Fibonacci number by summing the results + # of the previous two Fibonacci numbers. + def fibonacci(n) do + fibonacci(n - 1) + fibonacci(n - 2) + end +end + +# Print the Fibonacci number for n = 10. +IO.puts("Fibonacci(n): #{Fibonacci.fibonacci(10)}") \ No newline at end of file diff --git a/src/elixir/MaxRecursive.ex b/src/elixir/MaxRecursive.ex new file mode 100644 index 00000000..75a942cd --- /dev/null +++ b/src/elixir/MaxRecursive.ex @@ -0,0 +1,19 @@ +defmodule MaxRecursive do + # Base case: When n is 1, return the first element of the list (head). + def max_recursive(nums, 1), do: hd(nums) + + # Recursive case: Calculate the maximum recursively. + def max_recursive(nums, n) do + aux = max_recursive(nums, n - 1) + if aux > Enum.at(nums, n - 1) do + aux + else + Enum.at(nums, n - 1) + end + end +end + +# Example usage +nums = [1, 2, 3, 4, 32, 6, 7, 8, 9, 10] +IO.inspect "nums = #{inspect(nums)}" +IO.inspect "Max = #{MaxRecursive.max_recursive(nums, length(nums))}" diff --git a/src/elixir/README.md b/src/elixir/README.md new file mode 100644 index 00000000..0ed034ad --- /dev/null +++ b/src/elixir/README.md @@ -0,0 +1,112 @@ +## Elixir Language Basic Syntax Review +Elixir is a general purpose programming language built on top of Erlang or Ericsson language. It is very efficient for building distributed, fault tolerant appications. It's been used by many companies like Pinterest, PagerDuty, FarmBot, E-Metro Tel etc. + +Key features: + +- Built especially for scalable and maintanable applications. +- Everything is an expression +- Compiles to bytecode +- Built-in tooling for compilation, testing, debugging, formatting code etc. +- Erlang functions can be called directly as it get compiled to Erlang bytecode. + +#### 1. Variables + +````elixir +variable-name = value +```` + +#### 2. Data types + +|Data type | Usage | Description | +| ------------ | ------------ | ------------ | +| Numeric |x = 21|Elixir supports not only integer and float values but also a number can be defined in octal, hexadecimal and binary bases. | +| Atom | :true|Atoms are constant values whose name is same as their value | +| Boolean | : false, :true| Either true or false, usually declared as atoms | +| Strings | "Hello" | Strings are enclosed in double quotes(" ") and multi line strings are enclosed in triple double quotes(""" """) | +|Lists | ['a', 10, :true] | Lists are used to store different types of values and are represented in square brackets [] | +|Tuples | {'apple', 100, :false} | Similar to Lists and are represented in curly brackets {}. Tuples are good for accessing the values and lists are good for insertion and deletion of values | + + +#### 3. Loops and Conditionals + +##### If-Else and If-Else: + +When ever you want to perform a set of operations based on a condition If is used. + +```elixir +if condition do + #Code +end +``` + +When there is requirement to add code for false condition to IF block. + +```elixir +if condition do + #Code +else + #code +end +``` + +##### Unless and Unless-Else: + +Unless is similar to If but the code get executed only if the condition fails. + +````elixir +unless condition do + #Code +end +```` + +Unless-Else is similar to If-Else but the code get executed only if the condition fails. + +````elixir +unless condition do + #Code if condition fails +else + #Code if condition satisfies +end +```` + +##### Cond: +Cond is used when you want to execute a piece of code based on multiple conditions. + +````elixir +cond do + condition-1 -> #code if condition is true + condition-2 -> #code if condition is true + ... + true -> #code if none of the above are true +end +```` + +##### Case: + +Case is similar to switch in C/C++ language. + +````elixir +case value do + value-1 -> #code if value matches value-1 + value-2 -> #code if value matches value-2 + value-3 -> #code if value matches value-3 + ... + _ -> #code if value does not match any of the above and is similar to default in switch +end +```` + +#### 4. Functions +Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. + +Two types of functions are present in Elixir + +1. Anonymous Functions: Anonymous functions are functions with no name and they use `fn..end` constructs. +2. Named functions: Assign names to functions so that they can be called easily. Always named functions are defined in modules. + +```elixir +defmodule modulename do + def function_name(parameter1, parameter2) do + #code + end +end +``` \ No newline at end of file diff --git a/src/go/README.md b/src/go/README.md new file mode 100644 index 00000000..4c726f49 --- /dev/null +++ b/src/go/README.md @@ -0,0 +1,102 @@ +## Go Language Basic Syntax Review +Go language is an open-source, statically typed programming language by Google. Go is highly recommended for creation of highly scalable and available web applications. +Some of the products developed using Go are Kubernetes, Docker, Dropbox, Infoblox etc. + +Key features: + +- Fast compilation +- Easy to write concurrent programs +- Simple and concise syntax +- Supports static linking +- Opensource and huge community support. + +#### 1. Read Inputs + +````go +package main +import "fmt" + +func main() { + var name string + fmt.Scanf("%s", &name) + fmt.Printf("Hello %s", name) +} +```` + +#### 2. Variables + +````elixir +var varible-names datatype; +```` + + +#### 3. Loops and Conditionals + +##### If-Else and If-Else: + +When ever you want to perform a set of operations based on a condition If is used. + +```go +if(conditional-expression) { + // code +} +``` + +When there is requirement to add code for false condition to IF-ELSE block. + +```go +if(conditional-expression) { + // code +} else { + // code +} +``` +When there is requirement to have nested IF-ELSE block. + +```go +if(conditional-expression) { + // code +} else if(conditional-expression) { + // code +} else { + // code +} +``` + +##### Switch: +Switch is an alternative to If-Else-If ladder. + +```go +switch conditional-expression { +case value1: + // code + break; // optional +case value2: + // code + break; // optional +... + +default: + // code to be executed when all the above cases are not matched; +} +``` +*Note: Go doesn't have while or do-while loops like in C.* + +##### For: + +For loop is used to iterate a set of statements based on a condition. + +````go +for Initialization; Condition; Increment/decrement { + // code +} +```` + +#### 4. Functions +Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. + +```go +func functionname(parameter-name type) returntype { + //code +} +``` \ No newline at end of file diff --git a/src/java/README.md b/src/java/README.md new file mode 100644 index 00000000..d3388d17 --- /dev/null +++ b/src/java/README.md @@ -0,0 +1,135 @@ +## Java Language Basic Syntax Review +Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development. + +Key features: + +- Well maintained +- Object-oriented +- Robust and Secure +- Multithreading +- Distributed Computing +- Dynamic and Extensible +- Owned by oracle. Positive or negative you decide. + +#### 1. Read Inputs + +````java +import java.util.Scanner; +class Input { + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + System.out.println("Enter your name: "); + String inp = input.next(); + System.out.println("Hello, " + inp); + } +} +```` + +#### 2. Variables + +````java +short x = 999; // -32768 to 32767 +int x = 99999; // -2147483648 to 2147483647 +long x = 99999999999L; // -9223372036854775808 to 9223372036854775807 + +float x = 1.2; +double x = 99.99d; + +byte x = 99; // -128 to 127 +char x = 'A'; +boolean x = true; +```` + + +#### 3. Loops and Conditionals + +##### If-Else and If-Else: + +When ever you want to perform a set of operations based on a condition If-Else is used. + +```java +if(conditional-expression) { + // code +} else { + // code +} +``` + +##### Switch: +Switch is an alternative to If-Else-If ladder and to select one among many blocks of code. + +```java +switch() { +case value1: + // code + break; // optional +case value2: + // code + break; // optional +... + +default: + //code to be executed when all the above cases are not matched; +} +``` + +##### For: + +For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance. + +````java +for(Initialization; Condition; Increment/decrement){ + //code +} +```` +##### While: + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance. + +````java +while(){ + // code +} +```` + +##### Do-while: + +Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once. + +````java +do { + // code +} while (); +```` + +##### 4. Classes and Objects: + +Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class. + +**How to create a Class:** +`class` keyword is required to create a class. + +````java +class Mobile { + public: // access specifier which specifies that accessibility of class members + string name; // string variable (attribute) + int price; // int variable (attribute) +}; +```` +**How to create a Object:** +````java +Mobile m1 = new Mobile(); +```` +**How to define methods (functions) in a class:** + +````java +public class Greeting { + static void hello() { + System.out.println("Hello.. Happy learning!"); + } + + public static void main(String[] args) { + hello(); + } +} +```` diff --git a/src/javascript/README.md b/src/javascript/README.md new file mode 100644 index 00000000..6d7ae26d --- /dev/null +++ b/src/javascript/README.md @@ -0,0 +1,194 @@ +## JavaScript Language Basic Syntax Review +Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages. + +Key features: + +- Open-source +- Just-in-time compiled language +- Embedded along with HTML and makes web pages alive +- Originally named as LiveScript. +- Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc. + +#### 1. Read Inputs + +````js +var readline = require('readline'); +var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: false +}); + +rl.on('line', function(line){ + console.log("Hello, " + line); +}); +```` + +#### 2. Variables + +| Keyword | Description |Scope | +| ------------ | ------------ | ------------ | +| var |Var is used to declare variables(old way of declaring variables)| Function or global scope | +| let |let is also used to declare variables(new way) | Global or block Scope | +| const | const is used to declare const values. Once the value is assigned, it can not be modified | Global or block Scope | + +##### Backtick Strings +Interpolation: +```js +let greetings = `Hello ${name}` +``` +Multi line Strings: +```js +const msg = ` +hello +world! +` +``` +##### Arrays +An array is a collection of items or values. + +```js +let arrayName = [value1, value2,..etc]; +// or +let arrayName = new Array("value1","value2",..etc); +``` + +##### Arrow functions +Arrow Functions helps developers to write code in concise way, it’s introduced in ES6. Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well. + +````js +() => expression + +//const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +//const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0) +// .map(ele => ele ** 2); +//console.log(squaresOfEvenNumbers); +```` + +##### De-structuring Arrays +````js +let [firstName, lastName] = ['Foo', 'Bar'] +```` + +##### De-structuring Objects +````js +let {firstName, lastName} = { + firstName: 'Foo', + lastName: 'Bar' +} +```` +##### De-structuring rest(...) operator +````js + const { + title, + firstName, + lastName, + ...rest + } = record; +```` +##### De-structuring Spread(...) operator +````js +//Object spread +const post = { + ...options, + type: "new" +} +//array spread +const users = [ + ...adminUsers, + ...normalUsers +] +```` + +#### 3. Functions + +````js +function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo + console.log(`Hello ${name}!`); +} + +greet() // Hello Foo +greet({ name: 'Bar' }) // Hi Bar +```` + +##### 4. Loops and Conditionals + +IF is used to execute a block of code based on a condition. + +```js +if(condition){ + // code +} +``` + +Else part is used to execute the block of code when the condition fails. + +````js +if(condition){ + // code +} else { + // code +} +```` + +##### Switch: +Switch is used to replace nested If-Else statements. +```js +switch(condition){ + case 'value1' : + //code + [break;] + case 'value2' : + //code + [break;] + ....... + default : + //code + [break;] +} +``` + +##### For: + +For loop is used to iterate a set of statements based on a condition. + +````js +for(Initialization; Condition; Increment/decrement){ +//code +} +```` +##### While: + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance. + +````js +while (condition) { + // code +} +```` + +##### Do-while: + +Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once. + +````js +do { + // code +} while (); +```` + +##### 5. Classes + +ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class. + +**How to create a Class:** +`class` keyword is required to create a class. + +````js +class className { + constructor() { ... } //Mandatory Class method + method1() { ... } + method2() { ... } + ... +} +```` diff --git a/src/kotlin/README.md b/src/kotlin/README.md new file mode 100644 index 00000000..f123622e --- /dev/null +++ b/src/kotlin/README.md @@ -0,0 +1,77 @@ +## Kotline Language Basic Syntax Review +Kotlin is a new open source programming language like Java, JavaScript, Python etc. It is a high level strongly statically typed language that combines functional and technical part in a same place. Currently, Kotlin mainly targets the Java Virtual Machine (JVM), but also compiles to JavaScript. + +Kotlin is influenced by other popular programming languages such as Java, C#, JavaScript, Scala and Groovy. The syntax of Kotlin may not be exactly similar to Java Programming Language, however, internally Kotlin is reliant on the existing Java Class library to produce wonderful results for the programmers. Kotlin provides interoperability, code safety, and clarity to the developers around the world. + +Kotlin was developed and released by JetBrains in 2016. Kotlin is free, has been free and will remain free. It is developed under the Apache 2.0 license and the source code is available on GitHub. + +Key features: + +- Cross-platform Mobile applications. +- Android Application Development. +- Web Application Development +- Server Side Applications +- Desktop Application Development +- Data science based applications + + +#### 1. Variables + +```kotlin +var name = "Zara Ali" +var age = 19 +var height = 5.2 +``` + + +##### 2. Loops and Conditionals + +**IF**: +Used to execute a block of code based on a condition. Else part is used to execute the block of code when the condition fails. + +````kotlin +if (condition) { + // code block A to be executed if condition is true +} else { + // code block B to be executed if condition is false +} +```` + +##### When: +Kotlin when expression is similar to the switch statement in C, C++ and Java. +```kotlin +fun main(args: Array) { + val day = 2 + + val result = when (day) { + 1 -> "Monday" + 2 -> "Tuesday" + 3 -> "Wednesday" + 4 -> "Thursday" + 5 -> "Friday" + 6 -> "Saturday" + 7 -> "Sunday" + else -> "Invalid day." + } + println(result) +} +``` + +##### For: + +Kotlin does not provide a conventional for loop which is available in C, C++ and Java etc. + +`````kotlin +for (item in collection) { + // body of loop +} +````` +##### While: + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance. + +````js +while (condition) { + // code +} +```` diff --git a/src/python/README.md b/src/python/README.md new file mode 100644 index 00000000..e8c53ea4 --- /dev/null +++ b/src/python/README.md @@ -0,0 +1,90 @@ +## Python Language Basic Syntax Review +Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language. + +***NOTE Indentation is very important in Python, make sure the indentation is followed correctly*** + + +Key features: + +- Most popular and beginner friendly. +- Learn it now. + +#### 1. Taking inputs + +````python +import sys +name = sys.stdin.readline() +print("Hello "+ name) +```` + +##### 2. Loops and Conditionals + + + + +**IF-Else**: +Used to execute a block of code based on a condition. Else part is used to execute the block of code when the condition fails. + +````python +if conditional-expression + #code +elif conditional-expression + #code +else: + #code +```` +##### For: + +For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings. + +`````python +mylist=("Iphone","Pixel","Samsung") +for i in mylist: + print(i) +````` + +##### While: + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance. + +````python +while condition + #code +```` + +#### 3. Collections +There are four types of collections in Python. + +##### List: +List is a collection which is ordered and can be changed. Lists are specified in square brackets. + +````python +mylist=["iPhone","Pixel","Samsung"] +print(mylist) +```` + +##### Tuple: +Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets. + +````python +myTuple=("iPhone","Pixel","Samsung") +print(myTuple) +```` +##### Set: +Set is a collection which is unordered and unindexed. Sets are specified in curly brackets. + +````python +myset{"iPhone","Pixel","Samsung"} +print{myset} +```` + +##### Dictionary: +Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs. + +````python +mydict = { + "brand" :"iPhone", + "model": "iPhone 11" +} +print(mydict) +```` diff --git a/src/ruby/README.md b/src/ruby/README.md new file mode 100644 index 00000000..9c233b50 --- /dev/null +++ b/src/ruby/README.md @@ -0,0 +1,107 @@ +## Ruby Language Basic Syntax Review +Ruby is a general purpose object oriented programming language developed by Yukihiro Matsumoto. + +Key features: + +- More commonly used in Rails applications. +- Concise and simple to read and powerful too. +- Open-source +- Expressive features and visual appearance +- Flexible language + +#### 1. Taking inputs + +````ruby +name = gets.chomp +print "Hello #{name}.\n" +```` + +##### 2. Datatypes +| Data type | Description | Usage | +| ------------ | ------------ | ------------ | +| Fixnum | Represents normal numbers |x = 10| +| Bignum | Represents big numbers | x =9999999999| +|Float | Represents decimal numbers |x = 3.14 | +| Complex |Represents imaginary numbers | x = 1 + 2i | +| Rational | Represents fractional numbers | x = 1/4 | +| BigDecimal | Represents precision decimal numbers | x=1.0 | +| Hash |Represents key value pairs |{"Website"=>"onecompiler","message" => "Happy learning"} | + + +##### 3. Variabels +In Ruby, there is no need to explicitly declare variables to reserve memory space. When you assign a value to a variable, declaration happens automatically and a prefix is needed to indicate the following variable types. + +| Variable type | Description | +| ------------ | ------------ | +|Local variables | Scope is limited to the block of the variable initialization. Variable name must start with either `_ ` or lowercase letter. | +|Class variables | Class variables belongs to whole class and can be accessible anywhere inside the class. Variable name must start with `@@`. They must be initialized before use. | +|Instance variables | Instance variables belongs to a instance of the class. They can be accessed from any instance of the class within a method. Variable name must start` @` | +| Global variables | Scope is global and hence they can be accessible anywhere in the program. Variable name must start with `$` | + +##### 2. Loops and Conditionals + + +**IF-Else**: +If, If-else, Nested-Ifs are used when you want to perform a certain set of operations based on conditional expressions. + +````ruby +if(conditional-expression) + #code if condition is true +else + #code if condition is false +end +```` + +**Nested IF-Else**: + +````ruby +if(condition-expression1) + #code if above condition is true + elsif(condition-expression2) + #code if above condition is true +elsif(condition-expression3) + #code if above condition is true +... +else + #code if all the conditions are false +end +```` + +##### Case: +Case is similar to Switch statement, where it is used to execute one set of a statement from multiple conditions. + +````ruby +case expression +[when expression [, expression ...] [then] + # code ]... +[else + # code ] +end +```` +##### For: + +For loop is used to iterate a set of statements based on a condition. + +`````ruby +for variable in expression do + # code +end +````` +##### While: + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance. + +`````ruby +while condition do + # code +end +````` +##### Do-while: +Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once. + +`````ruby +loop do + #code + break if conditional-expression +end +````` diff --git a/src/rust/README.md b/src/rust/README.md new file mode 100644 index 00000000..4f1b3355 --- /dev/null +++ b/src/rust/README.md @@ -0,0 +1,47 @@ +## Rust Language Basic Syntax Review +Rust is a modern systems programming language developed by the Mozilla Corporation. It is intended to be a language for highly concurrent and highly secure systems. It compiles to native code; hence, it is blazingly fast like C and C++. This tutorial adopts a simple and practical approach to describe the concepts of Rust programming. + + +Key features: +- Safety +- Speed +- Concurrency + + +##### 1. Variabels +The data type is optional while declaring a variable in Rust. The data type is inferred from the value assigned to the variable. + +The syntax for declaring a variable is given below. +```rust +let variable_name = value; // no type specified +let variable_name:dataType = value; //type specified +``` + +##### 2. Loops and Conditionals + +##### For: + +The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as given below + + +`````rust +for temp_variable in lower_bound..upper_bound { + //statements +} +````` + +#### 3. Function +A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The function body contains code that should be executed by the function. The rules for naming a function are similar to that of a variable. Functions are defined using the `fn` keyword. The syntax for defining a standard function is given below + +````rust +fn function_name(param1,param2..paramN) { + // function body +} +```` +##### Invoking a Function + +````rust +function_name(val1,val2,valN) + +```` + diff --git a/src/scala/README.md b/src/scala/README.md new file mode 100644 index 00000000..45dc1bf1 --- /dev/null +++ b/src/scala/README.md @@ -0,0 +1,94 @@ +## Scala Language Basic Syntax Review +Scala is both object-oriented and functional programming language by Martin Odersky in the year 2003. + + +Key features: +- Concise syntax +- Expressive type system +- Support for both functional and object-oriented programming +- Seamless interaction with Java + +#### 1. Taking inputs + +````scala +object Hello { + def main(args: Array[String]): Unit = { + val name = scala.io.StdIn.readLine() + println("Hello " + name ) + } +} +```` + +##### 2. Variabels +Variable is a name given to the storage area in order to identify them in our programs. + +```scala +var or val Variable-name [: Data-Type] = [Initial Value]; +``` + +##### 3. Loops and Conditionals + +**IF-Else**: +If, If-else, Nested-Ifs are used when you want to perform a certain set of operations based on conditional expressions. + +````scala +if(conditional-expression) { +//code if condition is true +} else { +//code if condition is false +} +```` + +**Nested IF-Else**: + +````scala +if(condition-expression1) { +//code if above condition is true +} else if (condition-expression2) { +//code if above condition is true +} +else if(condition-expression3) { +//code if above condition is true +} +... +else { +//code if all the above conditions are false +} +```` + +##### For: + +For loop is used to iterate a set of statements based on a criteria. + +`````scala +for(index <- range){ + // code +} +````` +##### While: + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance. + +`````scala +while(condition) { + // code +} +````` +##### Do-while: +Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once. + +`````scala +do { + // code +} while (condition) +````` +#### 4. Function +Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. + +````scala +def functionname(parameters : parameters-type) : returntype = { //code +} +````` +You can either use `=` or not in the function definition. If `=` is not present, function will not return any value. + + diff --git a/src/swift/README.md b/src/swift/README.md new file mode 100644 index 00000000..1926ab8f --- /dev/null +++ b/src/swift/README.md @@ -0,0 +1,109 @@ +## Swift Language Basic Syntax Review +Swift 4 is a new programming language developed by Apple Inc for iOS and OS X development. Swift 4 adopts the best of C and Objective-C, without the constraints of C compatibility. Swift 4 uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift 4 programs to run on many existing iOS 6 and OS X 10.8 platforms. + + +Key features: +- Makes use of safe programming patterns. +- Provides modern programming features. +- Provides Objective-C like syntax. +- A fantastic way to write iOS and OS X apps. +- Provides seamless access to existing Cocoa frameworks. +- Unifies the procedural and object-oriented portions of the language. +- Does not need a separate library import to support functionalities like input/output or string handling. + + +##### 1. Variabels +Variable is a name given to the storage area in order to identify them in our programs. + +```swift +var variableName = +``` + +##### 2. Loops and Conditionals + +We have covered conditional ** operator ? :** in the previous chapter which can be used to replace if...else statements. It has the following general form − + +````swift +Exp1 ? Exp2 : Exp3; +```` + +The syntax of an** if...else if...else** statement in Swift 4 is as follows − + + +````swift +if boolean_expression_1 { + /* Executes when the boolean expression 1 is true */ + +} else if boolean_expression_2 { + /* Executes when the boolean expression 2 is true */ + +} else if boolean_expression_3 { + /* Executes when the boolean expression 3 is true */ + +} else { + /* Executes when the none of the above condition is true */ +} +```` + +**Nested IF-Else**: +The syntax for a nested if statement is as follows − + +````scala + +if boolean_expression_1 { + /* Executes when the boolean expression 1 is true */ + + if boolean_expression_2 { + /* Executes when the boolean expression 2 is true */ + } +} +```` + +##### For: + +For loop performs a set of statements for each item in a range, sequence, collection, or progression. + +`````swift +for index in var { + statement(s) +} +````` + +##### While: + +A while loop statement repeatedly executes a target statement as long as a given condition is true. + +`````swift +while condition { + statement(s) +} +````` + +##### repeat-while: +A repeat...while loop is similar to a while loop, except that a repeat...while loop is guaranteed to execute at least once. + + +`````swift +repeat { + statement(s); +} +while( condition ); +````` + +#### 3. Function +Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. + +````swift +func funcname(Parameters) -> returntype { + Statement1 + Statement2 + --- + Statement N + return parameters +} +```` +##### Invoking a Function + +````swift +funcname(val1,val2,valN) +````