Algorithms!

Algorithms are the backbone of modern technology. but what is an algorithm?

Algorithm
al·go·rithm /ˈalɡəˌriT͟Həm/ noun
plural: algorithms

Definition:
A process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer.
Example sentence:
“a basic algorithm for division”
Origin:
Late Middle English: from French algorisme, from medieval Latin algorismus, from the name of the mathematician al-Khwārizmī (9th century), who introduced Arabic numerals.
Oxford Languages Dictionary

In short...

An algorithm is a sequence of instructions to follow to get a specified outcome.
For Example: Making a sandwich

  • Get two slices of bread
  • Put cheese on one slice
  • Put some vegetables on top of it
  • Put some sauce on top of that
  • Put the other slice of bread on top

This is a simple algorithm for making a sandwich. Algorithms can be much more complex, especially in computer science where they can involve sorting data, searching for information, or performing calculations.

scroll down for algorithm demos and examples

Binary Search

Binary search is an efficient algorithm for finding an item in a sorted list of items.

Play Demo

Binary search works like finding a word in a dictionary:

  1. Look at the middle page.
  2. If the word is there, found it!
  3. If the word comes after, look in the second half.
  4. If before, look in the first half.
  5. Repeat until you find it or know it's not there.
def binary_search(arr, target):
  low, high = 0, len(arr) - 1
  while low <= high:
      mid = (low + high) // 2
      if arr[mid] == target:
          return mid
      elif arr[mid] < target:
          low = mid + 1
      else:
          high = mid - 1
  return -1

Quick Sort

Quick sort is a divide-and-conquer sorting algorithm that works by selecting a pivot element and partitioning the array around it.

Play Demo

Quick sort is like sorting cards:

  1. Pick a card as the "pivot".
  2. Put cards smaller than pivot on left, bigger on right.
  3. Do the same for the left and right groups.
  4. Keep doing until everything is sorted.

def quicksort(arr):
  if len(arr) <= 1:
      return arr
  pivot = arr[len(arr) // 2]
  left = [x for x in arr if x < pivot]
  middle = [x for x in arr if x == pivot]
  right = [x for x in arr if x > pivot]
  return quicksort(left) + middle + quicksort(right)
    

DFS

Depth-First Search (DFS) is an algorithm for pathfinding, traversing or searching tree or graph data structures.

Play Demo

Depth-First Search explores like exploring a cave:

  1. Start at one spot.
  2. Go as deep as possible down one path.
  3. If stuck, back up and try another path.
  4. Mark places you've been so you don't go again.
def dfs(graph, node, visited=None):
    if visited is None:
        visited = set()
    
    if node not in visited:
        print(node)
        visited.add(node)
        for neighbor in graph[node]:
            dfs(graph, neighbor, visited)
    return visited

# Example Graph
# graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []}

The previous algorithms are simple. here's what intermediate algorithms look like

Image to ASCII Converter


Generated ASCII Art

No file chosen

Python Code

ASCII art turns pictures into text:

  1. Take the picture and make it smaller.
  2. Turn it to black and white.
  3. For each part, pick a character like @ for dark, . for light.
  4. Put them in rows to make text art.
from PIL import Image

def image_to_ascii(image, width=100):
    ascii_chars = "@%#*+=-:. "
    aspect_ratio = image.height / image.width
    new_height = int(aspect_ratio * width * 0.55)
    img_resized = image.resize((width, new_height))
    img_gray = img_resized.convert("L")
    pixels = img_gray.getdata()
    ascii_str = "".join(ascii_chars[pixel * len(ascii_chars) // 256] for pixel in pixels)
    ascii_rows = [ascii_str[i:i+width] for i in range(0, len(ascii_str), width)]
    return ascii_rows

Social Media also uses algorithm. here's how it works.

click on any "video" to initialize the algorithm

Python Code

Social media algorithm learns what you like:

  1. Start with showing random videos.
  2. When you watch or like something, remember that category and tags.
  3. Show more of those kinds next time.
  4. Over time, it shows stuff you probably like more.
import random

# 1. SETUP: The Metadata
CATEGORIES = ["Tech", "Gaming", "Music", "Food", "Travel"]
TAGS = ["Lofi", "Tutorial", "Hardware", "Review", "Live", "Budget", "AI", "Retro"]

# 2. STATE: The "User Profile" (Initial interest is equal)
category_weights = {cat: 1.0 for cat in CATEGORIES}
tag_weights = {tag: 1.0 for tag in TAGS}

def generate_random_video():
    """Simulates a video being uploaded to the platform."""
    cat = random.choice(CATEGORIES)
    # Pick 2 random tags
    v_tags = random.sample(TAGS, 2)
    return {
        "title": f"{cat} Video {random.randint(100, 999)}",
        "category": cat,
        "tags": v_tags
    }

def get_algorithm_score(video):
    """The Core Algorithm: Multi-factor ranking."""
    c_score = category_weights[video["category"]]
    t_score = sum(tag_weights[tag] for tag in video["tags"])
    return (c_score * 1.5) + t_score  # Categories slightly more important

def display_feed(limit=3):
    """Generates a large pool but only shows the 'Recommended' top results."""
    pool = [generate_random_video() for _ in range(20)]
    # Sort the pool using our algorithm
    recommended = sorted(pool, key=get_algorithm_score, reverse=True)
    
    print("\n--- YOUR RECOMMENDED FEED ---")
    for i, v in enumerate(recommended[:limit]):
        print(f"{i+1}. {v['title']} | Category: {v['category']} | Tags: {v['tags']}")
    print("------------------------------")

def simulate_click(category, tags):
    """Update weights based on user engagement."""
    category_weights[category] += 2.0
    for t in tags:
        tag_weights[t] += 1.5
    
    # Simulation of 'Interest Decay' (others lose priority over time)
    for c in category_weights:
        category_weights[c] *= 0.95
    for t in tag_weights:
        tag_weights[t] *= 0.95

# --- EXECUTION SIMULATION ---

# Step 1: Show initial random feed
print("SYSTEM: New user detected. Showing baseline content.")
display_feed()

# Step 2: User clicks a 'Tech' video with '#Hardware'
print("\n[USER CLICK]: Tech Video with #Hardware and #Review")
simulate_click("Tech", ["Hardware", "Review"])

# Step 3: Show feed again. 
# It will now prioritize Tech, but also anything with Hardware/Review tags!
print("\nSYSTEM: Recalculating weights...")
display_feed()

# Step 4: User clicks a 'Gaming' video with '#Hardware'
# This is the 'Cross-over' - the user likes Hardware regardless of the category.
print("\n[USER CLICK]: Gaming Video with #Hardware and #Retro")
simulate_click("Gaming", ["Hardware", "Retro"])

print("\nSYSTEM: Final Result (Algorithm now understands you like #Hardware everywhere)")
display_feed()

Algorithms are everywhere. they help us sort data, make decisions, and solve complex problems. understanding algorithms is key to navigating the modern world.