firasx/algorithm-playground
0
1const express = require('express');2const cors = require('cors');3const bodyParser = require('body-parser');4const { exec } = require('child_process');5const fs = require('fs');6const path = require('path');7 8const app = express();9app.use(cors());10app.use(bodyParser.json());11 12const PORT = process.env.PORT || 5000;13 14// API endpoint to execute algorithms15app.post('/api/execute', (req, res) => {16 const { algorithm, input, language } = req.body;17 18 // Generate a unique filename19 const filename = `temp_${Date.now()}.${language === 'python' ? 'py' : 'js'}`;20 const filepath = path.join(__dirname, 'temp', filename);21 22 // Write the algorithm code to a temporary file23 fs.writeFileSync(filepath, algorithm);24 25 // Execute the code based on language26 const command = language === 'python' ? `python ${filepath}` : `node ${filepath}`;27 28 exec(command, { input }, (error, stdout, stderr) => {29 // Clean up the temporary file30 fs.unlinkSync(filepath);31 32 if (error) {33 return res.status(400).json({ error: stderr });34 }35 36 res.json({ result: stdout });37 });38});39 40// API endpoint to get algorithm templates41app.get('/api/algorithms', (req, res) => {42 const algorithms = {43 sorting: {44 bubble: `def bubble_sort(arr):45 n = len(arr)46 for i in range(n):47 for j in range(0, n-i-1):48 if arr[j] > arr[j+1]:49 arr[j], arr[j+1] = arr[j+1], arr[j]50 return arr`,51 quick: `def quick_sort(arr):52 if len(arr) <= 1:53 return arr54 pivot = arr[len(arr) // 2]55 left = [x for x in arr if x < pivot]56 middle = [x for x in arr if x == pivot]57 right = [x for x in arr if x > pivot]58 return quick_sort(left) + middle + quick_sort(right)`59 },60 searching: {61 binary: `def binary_search(arr, target):62 low, high = 0, len(arr) - 163 while low <= high:64 mid = (low + high) // 265 if arr[mid] < target:66 low = mid + 167 elif arr[mid] > target:68 high = mid - 169 else:70 return mid71 return -1`72 }73 };74 75 res.json(algorithms);76});77 78// Create temp directory if it doesn't exist79if (!fs.existsSync(path.join(__dirname, 'temp'))) {80 fs.mkdirSync(path.join(__dirname, 'temp'));81}82 83app.listen(PORT, () => {84 console.log(`Server running on port ${PORT}`);85});