Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added some docs #17

Merged
merged 1 commit into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/Hash/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Hash",
"position": 15,
"link": {
"type": "generated-index",
"description": "Hash is a data structure that maps keys to values. It uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found."
}
}
150 changes: 150 additions & 0 deletions docs/Hash/hash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# Hash in DSA (Data Structures and Algorithms)

Hash in DSA (Data Structures and Algorithms) is a function that takes an input (or "key") and produces a fixed-size string of characters, which is typically a unique representation of the input. Hash functions are commonly used in various applications, such as data indexing, password storage, and digital signatures.

![alt text](image.png)

- A hash function takes an input and applies a mathematical algorithm to generate a hash value. The hash value is a fixed-size string that is unique to the input data. It is important to note that even a small change in the input data will result in a completely different hash value.

![alt text](image-1.png)

- Hash functions are designed to minimize the occurrence of hash collisions, where two different inputs produce the same hash value. However, it is still possible for collisions to occur due to the limited size of the hash value compared to the potentially infinite input space.

- One common use of hash functions is in data indexing. Hash tables, also known as hash maps, use hash functions to map keys to specific locations in memory, allowing for efficient retrieval and storage of data.

Hash functions are also used in password storage. Instead of storing passwords in plain text, they are hashed and the hash value is stored. When a user enters their password, it is hashed and compared to the stored hash value for authentication.



Hash functions are an integral part of digital signatures. They are used to generate a unique hash value for a document or message, which is then encrypted with the sender's private key. The recipient can verify the integrity of the message by decrypting the hash value with the sender's public key and comparing it to the computed hash value of the received message.

Overall, hash functions play a crucial role in various applications by providing a unique representation of data, enabling efficient data retrieval, ensuring data integrity, and enhancing security.

## Implementing Hash Functions in Different Programming Languages

Here's a basic example of how to implement a hash function in different programming languages:

Python:
```python
import hashlib

def hash_string(input_string):
hash_object = hashlib.sha256(input_string.encode())
return hash_object.hexdigest()

input_string = "Hello, World!"
hashed_string = hash_string(input_string)
print(hashed_string)
```
Output: `2ef7bde608ce5404e97d5f042f95f89f1c232871`

Java:
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashExample {
public static String hashString(String inputString) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = md.digest(inputString.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : hashBytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}

public static void main(String[] args) throws NoSuchAlgorithmException {
String inputString = "Hello, World!";
String hashedString = hashString(inputString);
System.out.println(hashedString);
}
}
```
Output: `2ef7bde608ce5404e97d5f042f95f89f1c232871`

C++:
```cpp
#include <iostream>
#include <openssl/sha.h>

std::string hashString(const std::string& inputString) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, inputString.c_str(), inputString.length());
SHA256_Final(hash, &sha256);
std::stringstream ss;
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
return ss.str();
}

int main() {
std::string inputString = "Hello, World!";
std::string hashedString = hashString(inputString);
std::cout << hashedString << std::endl;
return 0;
}
```
Output: `2ef7bde608ce5404e97d5f042f95f89f1c232871`

Please note that these examples use the SHA-256 hash function as an illustration. Different hash functions may be used depending on the specific requirements of your application.

## Example Questions with Code in Python

Here are some example questions with code in Python to help you practice implementing hash functions:

1. **Question:** Write a Python function to calculate the MD5 hash of a given string.

```python
import hashlib

def calculate_md5_hash(input_string):
hash_object = hashlib.md5(input_string.encode())
return hash_object.hexdigest()

input_string = "Hello, World!"
md5_hash = calculate_md5_hash(input_string)
print(md5_hash)
```

**Output:** `3e25960a79dbc69b674cd4ec67a72c62`

2. **Question:** Implement a Python program to find the SHA-1 hash of a file.

```python
import hashlib

def calculate_sha1_hash(file_path):
sha1_hash = hashlib.sha1()
with open(file_path, 'rb') as file:
for chunk in iter(lambda: file.read(4096), b''):
sha1_hash.update(chunk)
return sha1_hash.hexdigest()

file_path = "path/to/file.txt"
sha1_hash = calculate_sha1_hash(file_path)
print(sha1_hash)
```

**Output:** `2ef7bde608ce5404e97d5f042f95f89f1c232871`

3. **Question:** Write a Python function to generate a random salt value for password hashing.

```python
import os
import hashlib

def generate_salt():
salt = os.urandom(16)
return salt.hex()

salt = generate_salt()
print(salt)
```

**Output:** `a5f7b9c8d7e6f5a4b3c2d1e0f9e8d7c6`

Remember to customize these examples based on your specific requirements and use appropriate hash functions for your application.
Binary file added docs/Hash/image-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/Hash/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions docs/Heaps/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"label": "Heaps",
"position": 10,
"link": {
"type": "generated-index",
"description": "Heaps are a type of binary tree-based data structure that satisfy the heap property. They are commonly used to implement priority queues and efficiently find the maximum or minimum element. Heaps can be either max heaps or min heaps, depending on whether the parent nodes are greater or smaller than their children. Operations like insertion, deletion, and retrieval of the maximum or minimum element can be performed efficiently on heaps."
}

}



134 changes: 134 additions & 0 deletions docs/Heaps/heaps.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
---
id: heaps-in-dsa
title: Heaps Data Structure
sidebar_label: Heaps
sidebar_position: 1
description: "Heaps are a type of binary tree-based data structure commonly used in computer science. They are often used to implement priority queues, where elements with higher priority are dequeued first. Heaps have two main variations: max heaps, where the parent node is always greater than or equal to its children, and min heaps, where the parent node is always less than or equal to its children. Heaps have efficient insertion and deletion operations, making them suitable for applications that require efficient priority-based processing."
tags: [dsa, data-structures, heaps]
---



## Python - Heaps

Heap is a special tree structure in which each parent node is less than or equal to its child node. Then it is called a Min Heap. If each parent node is greater than or equal to its child node then it is called a max heap. It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing.

A detailed discussion on heaps is available in our website here. Please study it first if you are new to heap data structure. In this chapter we will see the implementation of heap data structure using python.

![alt text](image.png)
## Create a Heap

A heap is created by using python’s inbuilt library named heapq. This library has the relevant functions to carry out various operations on heap data structure. Below is a list of these functions.

- heapify − This function converts a regular list to a heap. In the resulting heap the smallest element gets pushed to the index position 0. But rest of the data elements are not necessarily sorted.

- heappush − This function adds an element to the heap without altering the current heap.

- heappop − This function returns the smallest data element from the heap.

- heapreplace − This function replaces the smallest data element with a new value supplied in the function.

## Creating a Heap
A heap is created by simply using a list of elements with the heapify function. In the below example we supply a list of elements and the heapify function rearranges the elements bringing the smallest element to the first position.


**Python - Heaps**

Heap is a special tree structure in which each parent node is less than or equal to its child node. Then it is called a Min Heap.

If each parent node is greater than or equal to its child node then it is called a max heap.

It is very useful is implementing priority queues where the queue item with higher weightage is given more priority in processing.

A detailed discussion on heaps is available in our website here. Please study it first if you are new to heap data structure. In this chapter we will see the implementation of heap data structure using python.

**Example**
``` python
import heapq

H = [21,1,45,78,3,5]
# Use heapify to rearrange the elements
heapq.heapify(H)
print(H)
```

## Output
When the above code is executed, it produces the following result −
``` python
[1, 3, 5, 78, 21, 45]
```
## Inserting into heap

Inserting a data element to a heap always adds the element at the last index. But you can apply heapify function again to bring the newly added element to the first index only if it smallest in value. In the below example we insert the number 8.

**Example**

``` python
import heapq

H = [21,1,45,78,3,5]
# Covert to a heap
heapq.heapify(H)
print(H)

# Add element
heapq.heappush(H,8)
print(H)
```

## Output

When the above code is executed, it produces the following result −
```python
[1, 3, 5, 78, 21, 45]
[1, 3, 5, 78, 21, 45, 8]
```
## Removing from heap

You can remove the element at first index by using this function. In the below example the function will always remove the element at the index position 1.

**Example**
```python
import heapq

H = [21,1,45,78,3,5]
# Create the heap

heapq.heapify(H)
print(H)

# Remove element from the heap
heapq.heappop(H)

print(H)
Output
When the above code is executed, it produces the following result −
```python
[1, 3, 5, 78, 21, 45]
[3, 21, 5, 78, 45]
```
## Replacing in a Heap

The heap replace function always removes the smallest element of the heap and inserts the new incoming element at some place not fixed by any order.

**Example**
``` python
import heapq

H = [21,1,45,78,3,5]
# Create the heap

heapq.heapify(H)
print(H)

# Replace an element
heapq.heapreplace(H,6)
print(H)
```

## Output
When the above code is executed, it produces the following result −
```python
[1, 3, 5, 78, 21, 45]
[3, 6, 5, 78, 21, 45]
```
Binary file added docs/Heaps/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions docs/Matrix/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"label": "Matrix",
"position": 9,
"link": {
"type": "generated-index",
"description": "In data structures and algorithms (DSA), a matrix is a two-dimensional array consisting of rows and columns. It is often used to represent a grid-like structure or a table of values. Matrices are commonly used in various algorithms and mathematical operations, such as matrix multiplication, graph algorithms, image processing, and more. They provide a convenient way to organize and manipulate data in a structured manner."
}
}

Binary file added docs/Matrix/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading