Simple URL Shortener in C++

cppCopy code#include <iostream>
#include <unordered_map>
#include <string>
#include <ctime>

class URLShortener {
private:
    std::unordered_map<std::string, std::string> url_map; // Maps short URL to original URL
    std::unordered_map<std::string, std::string> reverse_map; // Maps original URL to short URL
    const std::string base_url = "http://short.url/";
    
    std::string generateShortURL() {
        static const char alphanum[] =
            "0123456789"
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "abcdefghijklmnopqrstuvwxyz";
        std::string short_url;
        
        for (int i = 0; i < 6; ++i) {
            short_url += alphanum[rand() % (sizeof(alphanum) - 1)];
        }
        
        return short_url;
    }

public:
    URLShortener() {
        std::srand(static_cast<unsigned>(std::time(nullptr))); // Seed for randomness
    }

    std::string shortenURL(const std::string& original_url) {
        if (reverse_map.find(original_url) != reverse_map.end()) {
            return base_url + reverse_map[original_url]; // Return existing short URL
        }
        
        std::string short_url = generateShortURL();
        while (url_map.find(short_url) != url_map.end()) {
            short_url = generateShortURL(); // Ensure unique short URL
        }
        
        url_map[short_url] = original_url;
        reverse_map[original_url] = short_url;

        return base_url + short_url;
    }

    std::string getOriginalURL(const std::string& short_url) {
        std::string short_code = short_url.substr(base_url.length());
        if (url_map.find(short_code) != url_map.end()) {
            return url_map[short_code];
        }
        return "URL not found!";
    }
};

int main() {
    URLShortener url_shortener;
    std::string original_url;

    std::cout << "Enter a URL to shorten: ";
    std::cin >> original_url;

    std::string short_url = url_shortener.shortenURL(original_url);
    std::cout << "Shortened URL: " << short_url << std::endl;

    std::cout << "Enter the short URL to retrieve the original: ";
    std::string input_short_url;
    std::cin >> input_short_url;

    std::string retrieved_url = url_shortener.getOriginalURL(input_short_url);
    std::cout << "Original URL: " << retrieved_url << std::endl;

    return 0;
}

How It Works

  1. URL Mapping: It uses two hash maps to store mappings between short URLs and original URLs.
  2. Short URL Generation: A random string of characters is generated for the short URL.
  3. Collision Handling: The program checks for existing short URLs to ensure uniqueness.
  4. User Input: The user can input a URL to shorten and retrieve the original URL using the shortened link.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *