Past puzzles

2025-12-07

Submitted at

2025-10-24 22:00:27
sql AI generated puzzle
DECLARE @StartOfLastMonth DATE;
DECLARE @EndOfLastMonth DATE;

-- Calculate the total sales for the previous month
SET @StartOfLastMonth = DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) - 1, 1);
SET @EndOfLastMonth = EOMONTH(@StartOfLastMonth);

SELECT
    CustomerID,
    SUM(TotalAmount) AS MonthlySales
FROM dbo.SalesOrders
WHERE OrderDate BETWEEN @StartOfLastMonth AND @EndOfLastMonth
  AND IsCancelled = 0
GROUP BY CustomerID
ORDER BY MonthlySales DESC;

Solution

DATEFROMPARTS with MONTH(GETDATE()) - 1 produces an invalid month (0) in January; use DATEADD(MONTH, -1, CAST(GETDATE() AS DATE)) before DATEFROMPARTS or use EOMONTH(GETDATE(), -1) to get safe boundaries.

2025-12-06

Submitted at

2025-11-02 23:00:06
bash AI generated puzzle
# Script to check if a given filename exists and is a non-empty regular file
filename="data.txt"
# Check if file exists and is not empty
if [[ -e $filename && -s $filename ]]; then
    echo "$filename exists and is not empty."
else
    echo "$filename does not exist or is empty."
fi

Solution

The bug is that '&&' inside [[ ... ]] is not valid; instead, you should use '-a' for 'and'. Replace '&&' with '-a' in the condition to fix the logic.

2025-12-05

Submitted at

2025-11-04 23:00:11
csharp AI generated puzzle
using System;
using System.Threading.Tasks;
using System.Collections.Generic;

class Program
{
    static async Task Main(string[] args)
    {
        var processor = new DataProcessor();
        await processor.ProcessMultipleItems();
    }
}

class DataProcessor
{
    // Process multiple data items concurrently and aggregate results
    public async Task ProcessMultipleItems()
    {
        var items = new List<int> { 1, 2, 3, 4, 5 };
        var tasks = new List<Task<string>>();
        
        foreach (var item in items)
        {
            tasks.Add(ProcessItemAsync(item));
        }
        
        // Wait for all tasks to complete
        await Task.WhenAll(tasks);
        
        Console.WriteLine("Processing complete. Results:");
        foreach (var task in tasks)
        {
            Console.WriteLine(task.Result);
        }
    }
    
    private async Task<string> ProcessItemAsync(int itemId)
    {
        // Simulate async operation
        await Task.Delay(100);
        return $"Processed item {itemId}";
    }
}

Solution

The bug is a closure capture issue in the foreach loop. The variable 'item' is captured by reference in the lambda/async context, not by value. By the time the async tasks execute, the loop may have already progressed, causing multiple tasks to process the same (final) value. Fix: Create a local copy inside the loop: 'var localItem = item;' and pass 'localItem' to ProcessItemAsync, or use a for loop with an index variable.

2025-12-04

Submitted at

2025-11-12 23:00:15
csharp AI generated puzzle
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var orderProcessor = new OrderProcessor();
        orderProcessor.ProcessOrders();
    }
}

class OrderProcessor
{
    private List<Order> orders = new List<Order>();

    public OrderProcessor()
    {
        // Initialize with sample orders
        orders.Add(new Order { Id = 1, Amount = 100.50m, Status = "Pending" });
        orders.Add(new Order { Id = 2, Amount = 250.75m, Status = "Completed" });
        orders.Add(new Order { Id = 3, Amount = 75.25m, Status = "Pending" });
    }

    // Process all pending orders and calculate total
    public void ProcessOrders()
    {
        decimal total = 0;
        var pendingOrders = orders.Where(o => o.Status == "Pending").ToList();
        
        foreach (var order in pendingOrders)
        {
            Console.WriteLine($"Processing order {order.Id} with amount {order.Amount}");
            order.Status = "Completed";
            total += order.Amount;
        }
        
        Console.WriteLine($"Total processed: {total}");
        Console.WriteLine($"Remaining pending orders: {orders.Count(o => o.Status == "Pending")}");
    }
}

class Order
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public string Status { get; set; }
}

Solution

The bug is that ToList() creates a new list containing references to the Order objects. While modifying the Order objects themselves (changing Status) works because they're reference types, the count of pending orders is recalculated from the original 'orders' list which was updated. However, the subtle issue is that this code actually works correctly in this case because Order is a reference type. The real bug is more subtle: the code appears to work but relies on side effects. If Order were a struct instead of a class, the Status changes wouldn't persist. The fix is to either iterate directly over the original list with a for loop, or ensure you're aware of reference vs value semantics when using LINQ operations that create new collections.

2025-12-03

Submitted at

2025-11-19 23:00:10
javascript AI generated puzzle
// Function to check if a user has permission to delete a resource
// Users can delete if they are the owner OR if they are an admin
function canDeleteResource(user, resource) {
  const isOwner = user.id === resource.ownerId;
  const isAdmin = user.role === 'admin';
  const isResourceLocked = resource.locked === true;
  
  // Allow deletion if user is owner or admin, but not if resource is locked
  if (isOwner || isAdmin && !isResourceLocked) {
    return true;
  }
  
  return false;
}

// Test cases
const admin = { id: 1, role: 'admin' };
const owner = { id: 2, role: 'user' };
const otherUser = { id: 3, role: 'user' };
const lockedResource = { ownerId: 2, locked: true };
const unlockedResource = { ownerId: 2, locked: false };

console.log('Admin can delete unlocked:', canDeleteResource(admin, unlockedResource)); // Expected: true
console.log('Owner can delete locked:', canDeleteResource(owner, lockedResource)); // Expected: false, Actual: true (BUG!)
console.log('Other user cannot delete:', canDeleteResource(otherUser, unlockedResource)); // Expected: false

Solution

The bug is due to operator precedence. The && operator has higher precedence than ||, so the expression evaluates as: (isOwner) || (isAdmin && !isResourceLocked). This means owners can delete even locked resources. Fix: Add parentheses to enforce correct logic: if ((isOwner || isAdmin) && !isResourceLocked)

2025-12-02

Submitted at

2025-11-20 23:00:07
php AI generated puzzle
<?php
// Process user registration with email verification
function validateUserRegistration($email, $password, $isEmailVerified, $accountAge) {
    $isValidEmail = filter_var($email, FILTER_VALIDATE_EMAIL);
    $isStrongPassword = strlen($password) >= 8;
    $isAccountOldEnough = $accountAge >= 30; // Account must be at least 30 days old
    
    // Check if user meets all registration requirements
    if ($isValidEmail && $isStrongPassword && ($isEmailVerified || $isAccountOldEnough)) {
        return true;
    }
    return false;
}

$result = validateUserRegistration('user@example.com', 'password123', false, 20);
echo $result ? 'Registration approved' : 'Registration denied';
?>

Solution

The bug is in the conditional logic: `($isEmailVerified || $isAccountOldEnough)`. For a NEW user registration, the account age will always be 0 or very small, so the `||` (OR) operator makes the email verification check meaningless. A new user with an unverified email can still register if they somehow have an old account age, which is illogical. This should use `&&` (AND) instead: `($isEmailVerified && $isAccountOldEnough)`, or the logic should be restructured to reflect the actual business rule - typically new registrations require email verification regardless of account age.

2025-12-01

Submitted at

2025-11-28 23:00:06
bash AI generated puzzle
#!/bin/bash

# Script to validate user age and grant access to premium features
user_age=25
min_age_required=18
access_granted=false

# Check if user meets minimum age requirement
if [ $user_age -ge $min_age_required ]; then
  access_granted=true
fi

# Display access status
if [ "$access_granted" = true ]; then
  echo "Access granted to premium features"
else
  echo "Access denied - user too young"
fi

Solution

The bug is in the string comparison `[ "$access_granted" = true ]`. In bash, when you assign `access_granted=true`, the variable contains the string "true", not a boolean. However, the comparison uses `=` which performs string comparison. The issue is subtle: while this specific case works, it relies on string matching rather than proper boolean logic. The correct approach is to use `[ "$access_granted" = "true" ]` (with quotes around true) or better yet, use `[ $access_granted = true ]` or the `if $access_granted` syntax. The real bug manifests when you later check conditions expecting actual boolean behavior - the variable is always a string, so comparisons should be explicit about this. The fix: use `if [ "$access_granted" = "true" ]` to properly compare strings, or use lowercase `true` and lowercase in the condition for consistency.

2025-10-22

Submitted at

2025-10-20 22:00:10
TypeScript AI generated puzzle
interface User {
  id: number;
  name: string;
}

// Adds a new user to the provided array if not present
function addUser(users: User[], newUser: User): User[] {
  if (!users.includes(newUser)) {
    users.push(newUser);
  }
  return users;
}

// Usage example:
const usersList = [ { id: 1, name: 'Alice' } ];
const updatedList = addUser(usersList, { id: 1, name: 'Alice' });
console.log(updatedList.length); // Supposed to print 1 if no duplicate

Solution

The bug is using users.includes(newUser), which checks reference equality for objects, not structural equality. Thus, two users with the same data but different object references are considered different. To fix, use a check like users.some(u => u.id === newUser.id && u.name === newUser.name) for proper duplicate detection.

2025-10-20

Submitted at

2025-10-18 12:07:07
php AI generated puzzle
<?php

class UserPermissionManager {
    private $users = [];
    private $roles = ['admin', 'editor', 'viewer'];
    private $permissions = [];

    public function addUser($userId, $role, $isActive = true) {
        $this->users[$userId] = [
            'role' => $role,
            'active' => $isActive,
            'createdAt' => time()
        ];
    }

    // Determines if a user can perform an action based on role and active status
    public function canPerformAction($userId, $action) {
        if (!isset($this->users[$userId])) {
            return false;
        }

        $user = $this->users[$userId];
        
        // Check if user is active AND has appropriate role for the action
        $isActive = $user['active'];
        $hasPermission = $this->hasRolePermission($user['role'], $action);
        
        return $isActive && $hasPermission || $user['role'] === 'admin';
    }

    private function hasRolePermission($role, $action) {
        $permissions = [
            'admin' => ['read', 'write', 'delete', 'manage'],
            'editor' => ['read', 'write'],
            'viewer' => ['read']
        ];
        
        return isset($permissions[$role]) && in_array($action, $permissions[$role]);
    }

    public function revokeUserAccess($userId) {
        if (isset($this->users[$userId])) {
            $this->users[$userId]['active'] = false;
        }
    }
}

// Test the class
$manager = new UserPermissionManager();
$manager->addUser('user1', 'editor', true);
$manager->addUser('user2', 'viewer', false);
$manager->addUser('user3', 'admin', true);

// Expected: user1 (editor, active) can write = true
var_dump($manager->canPerformAction('user1', 'write'));

// Expected: user2 (viewer, inactive) cannot read even if viewer can = false
var_dump($manager->canPerformAction('user2', 'read'));

// Expected: user3 (admin, active) can delete = true
var_dump($manager->canPerformAction('user3', 'delete'));

// This should be false but will return true due to the bug
$manager->revokeUserAccess('user1');
var_dump($manager->canPerformAction('user1', 'write'));

?>

Solution

The bug is in the `canPerformAction` method's return statement: `return $isActive && $hasPermission || $user['role'] === 'admin';`. Due to operator precedence, `&&` binds tighter than `||`, so this evaluates as `($isActive && $hasPermission) || ($user['role'] === 'admin')`. This means any admin user can perform any action regardless of active status, and more critically, if a user is not an admin but inactive with a permission, the OR operator still allows access. The fix is to use explicit parentheses: `return ($isActive && $hasPermission) || ($user['role'] === 'admin' && $isActive);` or restructure to `return $isActive && ($hasPermission || $user['role'] === 'admin');` to ensure inactive users are always denied access.

2025-10-19

Submitted at

2025-10-18 12:10:11
php AI generated puzzle
<?php

// Function to validate and sanitize user input before database insertion
function sanitizeUserData($userData) {
    $sanitized = [];
    
    foreach ($userData as $key => $value) {
        // Remove any HTML tags and trim whitespace
        $sanitized[$key] = trim(strip_tags($value));
    }
    
    return $sanitized;
}

// Simulate user registration data
$userInput = [
    'username' => 'john_doe',
    'email' => 'john@example.com',
    'bio' => 'Software developer from NYC',
    'is_active' => true,
    'age' => 25
];

// Sanitize the user data
$cleanData = sanitizeUserData($userInput);

// Display the sanitized data
echo "Sanitized Data:\n";
print_r($cleanData);

// Check if user is active
if ($cleanData['is_active']) {
    echo "\nUser account is active\n";
} else {
    echo "\nUser account is inactive\n";
}

?>

Solution

The bug is that strip_tags() and trim() expect string inputs, but the function receives mixed data types (boolean and integer). When strip_tags() receives a boolean true, it converts it to the string '1', and false becomes an empty string. This means $cleanData['is_active'] will be the string '1' instead of boolean true. In PHP, any non-empty string (including '1') evaluates to true in conditionals, but this creates subtle bugs when doing strict comparisons or type checks. Fix: Check the data type before applying string functions: if (is_string($value)) { $sanitized[$key] = trim(strip_tags($value)); } else { $sanitized[$key] = $value; }

2025-10-05

Submitted at

2025-10-03 22:00:12
bash AI generated puzzle
#!/bin/bash
# Check if user has valid permissions based on role hierarchy
declare -a roles=("guest" "user" "moderator" "admin" "superadmin")
declare -a user_perms=("read" "write" "delete" "manage" "full")

function check_auth() {
    local user_role="$1"
    local required_role="$2"
    local user_idx=-1
    local req_idx=-1
    
    for i in "${!roles[@]}"; do
        [[ "${roles[$i]}" == "$user_role" ]] && user_idx=$i
        [[ "${roles[$i]}" == "$required_role" ]] && req_idx=$i
    done
    
    [[ $user_idx -ge 0 && $req_idx -ge 0 && $user_idx -gt $req_idx ]] && echo "Access granted: ${user_perms[$user_idx]}" || echo "Access denied"
}

check_auth "admin" "moderator"

Solution

The bug is on line 16: the condition uses '$user_idx -gt $req_idx' (greater than) instead of '$user_idx -ge $req_idx' (greater than or equal). This causes users with the exact required role to be denied access. Fix: Change '-gt' to '-ge' to allow users with the same or higher role level to access resources.

2025-10-03

Submitted at

2025-09-29 18:35:50
html AI generated puzzle
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Button demo</title>
<style>
:root {
  --primary-color: #1e90ff;
  --btn-radius: 8px;
}

body {
  font-family: system-ui, sans-serif;
  background: #f7f7f7;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
}

.button {
  background: var(--primray-color);
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: var(--btn-radius);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0,0,0,0.15);
  font-size: 16px;
}
</style>
</head>
<body>
<button class="button">Click me</button>
</body>
</html>

Solution

The button's background uses var(--primray-color) but the variable declared is --primary-color (missing the 'i'). Because of the typo the variable is invalid and the background falls back to nothing. Fix by using the correct name: background: var(--primary-color);

2025-10-02

Submitted at

2025-09-29 18:45:14
python AI generated puzzle
def make_squares(n):
    funcs = []
    for i in range(n):
        # bug: lambda closes over loop variable i
        funcs.append(lambda: i * i)
    return funcs

funcs = make_squares(5)
for f in funcs:
    print(f())

Solution

Bug: The lambdas close over the loop variable i (late binding), so when the functions run they all use i's final value. Fix: bind the current i as a default argument (or use functools.partial). Example fix: def make_squares(n): funcs = [] for i in range(n): funcs.append(lambda i=i: i * i) # bind current i return funcs # Now prints 0,1,4,9,16 funcs = make_squares(5) for f in funcs: print(f())

2025-10-01

Submitted at

2025-09-09 22:00:06
sql AI generated puzzle
SELECT customer_id, order_date, total_amount
FROM orders
WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31'
ORDER BY order_date;

Solution

The bug is in the BETWEEN clause with dates. When using BETWEEN with dates that only specify the date (not time), the end date '2023-12-31' is interpreted as '2023-12-31 00:00:00', which excludes any orders placed later in that day. To fix this, either use '2023-12-31 23:59:59' as the end date, or change the WHERE clause to: WHERE order_date >= '2023-01-01' AND order_date < '2024-01-01'

2025-09-30

Submitted at

2025-09-17 22:00:05
javascript AI generated puzzle
function addNumbers(a, b) {
  return a + b;
}

const result = addNumbers('5', 10);
console.log(result);

Solution

The bug is due to JavaScript's + operator concatenating a string and a number, resulting in '510' instead of numeric addition. To fix it, explicitly convert the inputs to numbers inside the function, e.g., use `return Number(a) + Number(b);`.

2025-09-29

Submitted at

2025-09-18 22:00:10
php AI generated puzzle
<?php
function calculateDiscount($price, $percentage) {
    $discount = $price * $percentage / 100;
    return $price - $discount;
}

$originalPrice = 100;
$discountRate = '15%';
$finalPrice = calculateDiscount($originalPrice, $discountRate);
echo "Final price: $" . $finalPrice;
?>

Solution

The bug is that the discount rate '15%' is passed as a string with a percentage symbol, but the function expects a numeric value. PHP will convert '15%' to just 15 when used in mathematical operations, but the '%' character makes it behave unexpectedly. The string '15%' converts to 15 in numeric context, so instead of 15% discount, it calculates 15% as 1500% (since the function divides by 100). Fix: Remove the '%' symbol from the input or use intval() to extract the numeric part: $discountRate = 15; or $discountRate = intval($discountRate);

2025-09-28

Submitted at

2025-09-22 22:00:05
SQL AI generated puzzle
SELECT employee_id, CONCAT(first_name, last_name) AS full_name FROM employees WHERE department = 'Sales';

Solution

The CONCAT function concatenates the first_name and last_name without a space, causing the full_name to be merged without separation (e.g., 'JohnSmith'). To fix it, add a space between the two names: SELECT employee_id, CONCAT(first_name, ' ', last_name) AS full_name FROM employees WHERE department = 'Sales';

2025-09-06

Submitted at

2025-08-21 22:00:08
php AI generated puzzle
<?php
function calculateTotal($items) {
    $total = 0;
    foreach ($items as $item) {
        $total += $item['price'] * $item['quantity'];
    }
    return $total;
}

$products = [
    ['name' => 'Apple', 'price' => '2.50', 'quantity' => 3],
    ['name' => 'Banana', 'price' => '1.20', 'quantity' => 5],
    ['name' => 'Orange', 'price' => '3.00', 'quantity' => 2]
];

echo "Total: $" . calculateTotal($products);
?>

Solution

The bug is that the 'price' values are stored as strings instead of floats/integers. While PHP's type juggling makes the multiplication work, it can lead to unexpected results with floating-point arithmetic. Fix by converting prices to float: change the array values to floats like 2.50 instead of '2.50', or use floatval() in the calculation: $total += floatval($item['price']) * $item['quantity'];

2025-09-05

Submitted at

2025-08-29 22:00:08
javascript AI generated puzzle
function findMaxValue(numbers) {
  let max = 0;
  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] > max) {
      max = numbers[i];
    }
  }
  return max;
}

console.log(findMaxValue([5, 3, 8, 1])); // Works fine
console.log(findMaxValue([-2, -5, -1, -8])); // Bug appears here

Solution

The bug is that `max` is initialized to 0, so when all numbers in the array are negative, the function returns 0 instead of the actual maximum negative number. Fix: Initialize `max` to `numbers[0]` or `Number.NEGATIVE_INFINITY` instead of 0, or add a check for empty arrays.

2025-08-22

Submitted at

2025-08-07 18:04:24
javascript AI generated puzzle
function findLargestNumber(numbers) {
  let largest = 0;
  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] > largest) {
      largest = numbers[i];
    }
  }
  return largest;
}

console.log(findLargestNumber([5, 2, 8, 1]));
console.log(findLargestNumber([-3, -1, -7, -2]));

Solution

The bug is that `largest` is initialized to 0, which causes issues when all numbers in the array are negative. The function will return 0 instead of the actual largest negative number. Fix: Initialize `largest` to the first element of the array: `let largest = numbers[0];` or use `let largest = -Infinity;`

2025-08-21

Submitted at

2025-08-12 22:00:09
css AI generated puzzle
button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 24px;
  border: none;
  border-radius: 12px 12px 12px 12px 12px;
  cursor: pointer;
  font-size: 16px;
}

Solution

The 'border-radius' property has five values specified, but it should only have one to four. CSS only accepts 1 to 4 values for 'border-radius'. Fix by reducing values to four or fewer, e.g., 'border-radius: 12px;' or 'border-radius: 12px 12px 12px 12px;'.

2025-08-20

Submitted at

2025-08-14 22:00:04
php AI generated puzzle
<?php
function addToArray($arr) {
    $arr[] = 'new item';
}

$myArray = ['item1', 'item2'];
addToArray($myArray);
print_r($myArray);
?>

Solution

The function addToArray() does not modify the original array because arrays are passed by value, not by reference. To fix this, change the function parameter to accept the array by reference: function addToArray(&$arr) { $arr[] = 'new item'; }

2025-08-08

Submitted at

2025-07-13 11:38:18
csharp AI generated puzzle
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var numbers = new List<int> { 1, 2, 3, 4, 5 };
        
        foreach (var num in numbers)
        {
            if (num % 2 == 0)
            {
                numbers.Remove(num);
            }
        }
        
        Console.WriteLine("Remaining numbers: " + string.Join(", ", numbers));
    }
}

Solution

The bug is that the code modifies the collection (removes items) while iterating over it with foreach, which throws an InvalidOperationException. To fix this, either iterate backwards with a for loop, use RemoveAll() method, or collect items to remove first then remove them: numbers.RemoveAll(num => num % 2 == 0); or use a for loop: for(int i = numbers.Count - 1; i >= 0; i--) { if(numbers[i] % 2 == 0) numbers.RemoveAt(i); }

2025-08-07

Submitted at

2025-07-15 22:00:07
php AI generated puzzle
<?php
function calculateDiscount($price, $discount) {
    if ($discount > 0 && $discount < 100) {
        return $price - ($price * $discount / 100);
    }
    return $price;
}

$originalPrice = 50.00;
$discountPercent = "10";
$finalPrice = calculateDiscount($originalPrice, $discountPercent);
echo "Final price: $" . $finalPrice;
?>

Solution

The bug is in the condition `$discount < 100` which excludes a 100% discount (free item). A 100% discount is valid and should result in a price of 0. The condition should be `$discount <= 100` to include 100% discounts. Additionally, the function should handle the string input by converting it to a number, though PHP's type juggling handles this automatically in arithmetic operations.

2025-08-06

Submitted at

2025-07-16 22:00:07
bash AI generated puzzle
#!/bin/bash

files=$(ls *.txt)
for file in $files; do
    if [ -f $file ]; then
        echo "Processing: $file"
        wc -l $file
    fi
done

Solution

The bug occurs when no .txt files exist - the ls command fails and returns an error, but the variable assignment still happens with the literal string '*.txt'. The script then tries to process a file named '*.txt' which doesn't exist. Fix by adding error handling: `files=$(ls *.txt 2>/dev/null)` and check if files variable is empty, or use a more robust approach like `for file in *.txt; do [ -f "$file" ] || continue; ...`

2025-08-05

Submitted at

2025-07-02 07:59:10
python AI generated puzzle
def calculate_total(items, discount_rate=0.1):
    total = sum(item['price'] for item in items)
    return total * (1 - discount_rate)

Solution

The bug is that if 'items' is an empty list, the function will return a negative value instead of zero. To fix this, add a check for empty list: if not items: return 0 before calculating the total.

2025-07-23

Submitted at

2025-07-20 22:00:08
typescript AI generated puzzle
class Calculator {
  private history: number[] = [];

  add(a: number, b: number): number {
    const result = a + b;
    this.history.push(result);
    return result;
  }

  getAverage(): number {
    const sum = this.history.reduce((acc, val) => acc + val, 0);
    return sum / this.history.length;
  }

  clear(): void {
    this.history = [];
  }
}

const calc = new Calculator();
console.log(calc.add(5, 3));
console.log(calc.add(10, 2));
console.log('Average:', calc.getAverage());
calc.clear();
console.log('Average after clear:', calc.getAverage());

Solution

The bug occurs in the getAverage() method when called after clear(). When the history array is empty, this.history.length is 0, causing division by zero which returns NaN. Fix: Check if the array is empty and return 0 or throw an error: `return this.history.length === 0 ? 0 : sum / this.history.length;`

2025-07-22

Submitted at

2025-07-20 20:40:30
sql AI generated puzzle
SELECT customer_name, order_date, total_amount FROM orders WHERE order_date >= '2023-01-01' AND order_date < '2024-01-01' ORDER BY order_date GROUP BY customer_name;

Solution

The bug is that ORDER BY appears before GROUP BY, but in SQL the correct clause order is: SELECT, FROM, WHERE, GROUP BY, ORDER BY. The GROUP BY clause must come before ORDER BY. Fix: Move 'GROUP BY customer_name' before 'ORDER BY order_date'. Also note that when using GROUP BY, aggregate functions should be used for non-grouped columns like order_date and total_amount.

2025-07-14

Submitted at

2025-07-13 11:37:40
bash AI generated puzzle
#!/bin/bash

read -p "Enter a number: " num
if [ $num -gt 10 ]; then
    echo "Number is greater than 10"
elif [ $num -eq 10 ]; then
    echo "Number equals 10"
else
    echo "Number is less than 10"
fi

Solution

The bug occurs when the variable $num is empty or contains non-numeric data. The script will fail with an error like 'integer expression expected' because the test operators (-gt, -eq) expect numeric values. To fix this, add input validation: check if the variable is empty using [ -z "$num" ] and verify it contains only digits using a regex pattern like [[ $num =~ ^[0-9]+$ ]] before performing numeric comparisons.

2025-07-09

Submitted at

2025-07-05 22:00:05
csharp AI generated puzzle
public class UserManager {
    private static List<string> _users = new List<string>();
    
    public void AddUser(string username) {
        if (_users.Contains(username)) {
            _users.Add(username);
        }
    }
    
    public bool UserExists(string username) {
        return _users.Contains(username);
    }
}

Solution

In the AddUser method, the condition is reversed. It should be `if (!_users.Contains(username))` to add a user only if they don't already exist. The current code prevents adding new users because it only adds a username if it's already in the list.

2025-07-08

Submitted at

2025-07-07 23:17:15
sql
fdsqfdq

Solution

fdsqfdsq

2025-07-05

Submitted at

2025-07-04 22:00:06
css AI generated puzzle
.container {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    width: 100%;
}

.item {
    flex-shrink: 0;
    min-width: 250px;
    margin-right: 10px;
}

Solution

The flex-shrink: 0 prevents items from shrinking, which can cause unexpected overflow. Remove or adjust this property to allow responsive sizing. Setting flex-shrink to a value less than 1 would allow controlled item compression.

2025-07-04

Submitted at

2025-07-02 08:09:18
php AI generated puzzle
<?php
function calculateTotal($items, $tax = 0.1) {
    $total = 0;
    foreach ($items as $item) {
        $total += $item['price'];
    }
    return $total * (1 + $tax);
}

$products = [
    ['name' => 'Laptop', 'price' => 1000],
    ['name' => 'Phone', 'price' => 500],
    ['name' => 'Tablet', 'price' => null]
];

echo calculateTotal($products);

Solution

The bug is in handling null prices, which will cause a type conversion issue and potentially lead to unexpected calculation results. Validate price values before calculation or use a default value to prevent null-related errors.

2025-07-03

Submitted at

2025-07-02 08:05:55
csharp AI generated puzzle
public class NumberProcessor {
    public static int CalculateSum(int[] numbers) {
        int result = 0;
        foreach (int num in numbers) {
            result += num;
        }
        return result / numbers.Length;
    }

    public static void Main() {
        int[] data = { 10, 20, 30 };
        Console.WriteLine(CalculateSum(data));
    }
}

Solution

The bug is in the CalculateSum method, where it divides the total sum by the array length, which effectively calculates the average instead of the sum. To fix this, remove the division operation: 'return result;'

2025-07-02

Submitted at

2025-06-30 08:58:28
php AI generated puzzle
<?php
function calculateSum($a, $b) {
    return $a + $b;
}

$result = calculateSum('5 apples', 10);
echo "Sum is: $result";
?>

Solution

The bug is that the function receives a string with non-numeric characters ('5 apples'), which PHP loosely converts to integer 5, but this can lead to unexpected behavior if inputs change. To fix it, validate and sanitize inputs before performing arithmetic, for example: function calculateSum($a, $b) { if (!is_numeric($a) || !is_numeric($b)) { throw new InvalidArgumentException('Both inputs must be numeric'); } return $a + $b; } Alternatively, cast inputs explicitly to ensure numeric addition.

2025-07-01

Submitted at

2025-06-27 22:00:04
javascript AI generated puzzle
const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(num => {
  num * num;
});
console.log(squared);

Solution

The arrow function in map lacks a return statement, so it returns undefined for each element. Add a return keyword or use an implicit return: const squared = numbers.map(num => num * num);

2025-06-30

Submitted at

2025-06-27 11:44:23
javascript AI generated puzzle
function calculateTotal(items) {
    return items.reduce((total, item) => {
        return total + item.price * item.quantity;
    }, 0);
}

const cart = [
    { name: 'Laptop', price: 1000, quantity: 1 },
    { name: 'Mouse', price: 50 }
];

console.log(calculateTotal(cart));

Solution

The bug occurs because the 'Mouse' object lacks a 'quantity' property, which will default to undefined. When multiplied with price, this results in NaN. To fix this, add a default quantity of 1 or validate item properties before calculation.

2025-06-29

Submitted at

2025-06-27 09:54:52
csharp AI generated puzzle
public class UserManager {
    private List<string> userNames = new List<string>();

    public void AddUser(string name) {
        if (name != null && name.Length > 2) {
            userNames.Add(name.ToLower());
        }
    }

    public bool IsUserNameUnique(string name) {
        return !userNames.Contains(name);
    }
}

Solution

The bug is in the IsUserNameUnique method. Because AddUser converts names to lowercase, but IsUserNameUnique checks the original case, the uniqueness check can be inconsistent. To fix this, modify IsUserNameUnique to use name.ToLower() when checking: return !userNames.Contains(name.ToLower());

2025-06-28

Submitted at

2025-06-27 09:22:15
typescript
class Rectangle {
    width: number;
    height: number;

    constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
    }

    getArea(): number {
        return this.width * this.heigth;
    }
}

Solution

In the method getArea, there's a typo in the property name: this.heigth. The correct property is this.height. This typo will cause a runtime error or produce NaN because this.heigth is undefined.

2025-05-06

Submitted at

2023-11-29 02:27:40
css
body {
    background-color: #GGG;
}

Solution

The color code '#GGG' is not a valid hexadecimal color representation. It should be replaced with a valid hex code like '#FFF'.

2025-05-05

Submitted at

2023-11-29 02:27:40
javascript
function greet(name) {
    return 'Hello, ' + name;
}
greet();

Solution

The function greet is called without arguments, which will result in 'Hello, undefined'. A default value or a check should be implemented.

2025-05-04

Submitted at

2023-11-29 02:27:40
python
def divide_numbers(a, b):
    return a / b

Solution

The function does not handle division by zero, which will cause an exception. A check should be added to handle this scenario.

2025-04-26

Submitted at

2025-04-22 10:15:55
css
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  z-index: 10;
}

Solution

The bug is that the modal's z-index (10) is lower than the backdrop's z-index (100), so the modal will be hidden behind the backdrop. The modal's z-index should be higher than the backdrop's.

2025-04-25

Submitted at

2025-04-15 14:40:18
bash
#!/bin/bash

filename=$1

if [ -f $filename ]; then
  echo "Processing $filename"
  grep "ERROR" $filename > errors.log
else
  echo "File not found"
fi

Solution

The bug is missing quotes around the $filename variable. If the filename contains spaces, the script will fail. It should be: if [ -f "$filename" ] and grep "ERROR" "$filename" > errors.log

2025-04-24

Submitted at

2025-04-12 11:20:33
csharp
public class UserManager {
  private List<User> users;
  
  public void AddUser(User user) {
    users.Add(user);
  }
  
  public User FindUser(string username) {
    return users.FirstOrDefault(u => u.Username == username);
  }
}

Solution

The bug is that the 'users' list is never initialized. In the constructor, it should include 'users = new List();' Otherwise, when AddUser is called, it will throw a NullReferenceException.

2025-04-23

Submitted at

2025-04-09 14:22:33
javascript
function createCounter() {
  let count = 0;
  
  function increment() {
    count++;
    return count;
  }
  
  return {
    increment: increment,
    reset: function() {
      count = 0;
    },
    getCount: function() {
      return Count;
    }
  };
}

Solution

The bug is in the getCount method. It tries to return 'Count' (with capital C) instead of 'count' (lowercase). JavaScript is case-sensitive, so this will cause a reference error.

2025-04-22

Submitted at

2025-04-17 14:23:10
typescript
function reverseString(str: string): string {
  let reversed = '';
  for (let i = 0; i <= str.length; i++) {
    reversed = str[i] + reversed;
  }
  return reversed;
}

Solution

The loop condition uses <= instead of <, causing it to access an undefined character at str.length. Also, when i=str.length, str[i] is undefined and will appear as 'undefined' at the beginning of the result.

2025-04-21

Submitted at

2025-04-17 14:24:55
javascript
async function fetchUserData(userId) {
    const response = await fetch(`/api/users/${userId}`);
    const data = response.json();
    return data;
}

Solution

The function doesn't await the response.json() promise, which means it returns a Promise instead of the resolved data.

2025-04-20

Submitted at

2025-04-17 14:28:00
csharp
public class User
{
    private string _name;
    private int _age;
    
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
    
    public bool IsAdult()
    {
        return Age > 18;
    }
}

Solution

The IsAdult method checks if Age > 18, but the legal adult age is typically 18 and above, so it should be Age >= 18 instead.

2025-04-19

Submitted at

2025-04-17 14:36:40
typescript
interface User {
  id: number;
  name: string;
  email: string;
  active: boolean;
}

function filterActiveUsers(users: User[]): User[] {
  return users.filter(user => user.active = true);
}

Solution

The filter callback uses the assignment operator (=) instead of the equality operator (==) or strict equality operator (===). This assigns true to user.active instead of checking if it's equal to true, effectively making all users active. It should be: users.filter(user => user.active === true) or simply users.filter(user => user.active).

2025-04-18

Submitted at

2025-04-12 13:22:06
php
function incrementCounter() {
    static $counter = 0;
    counter++;
    return $counter;
}

echo incrementCounter();

Solution

The variable "counter" is missing a dollar sign

2025-04-17

Submitted at

2025-04-12 13:25:22
javascript
function setupButton() {
    const button = document.getElementById('myButton');
    
    button.addEventListener('click', function() {
        button.textContent = 'Clicked!';
        setupButton();
    });
}

Solution

Remove the recursive call (setupButton) to prevent adding multiple listeners

2025-04-16

Submitted at

2025-04-12 13:21:13
javascript
function getLastElement(array) {
    return array[array.length];
}

const arr = [1, 2, 3, 4, 5];
console.log(getLastElement(arr));

Solution

Change "array[array.length]" to "array[array.length - 1]". The last element's index is always one less than the array's length.

2025-04-15

Submitted at

2025-04-12 13:18:02
css
.container {
    width: 100;
    height: 200px;
    padding: 20px;
    margin: 10px;
}

Solution

100 what? cows? No pixels: 100px;

2025-04-14

Submitted at

2025-04-12 13:16:22
bash
#!/bin/bash
if [ $1 -eq "yes" ]; then
  echo "You said yes"
fi

Solution

Use = to compare strings.

2025-04-13

Submitted at

2025-04-08 12:12:18
php
function sanitizeInput($input)
{
    $clean = strip_tags($input);
    $clean = htmlspecialchars($clean);
    return $input;
}