Past puzzles

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;
}