Past puzzles

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