ChatGPT coding challenge 2022.12.11 – complete game of Math24

“Write a GoLang program that can play the game of Math 24 and if the players gets the wrong answer, provide the answer.”

ChatGPT Answer (limitation, not able to validate anything more than simple addition)

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	// Generate 4 random numbers between 1 and 10
	rand.Seed(time.Now().UnixNano())
	n1 := rand.Intn(10) + 1
	n2 := rand.Intn(10) + 1
	n3 := rand.Intn(10) + 1
	n4 := rand.Intn(10) + 1

	// Make sure the numbers can be used to solve the equation 24 using only addition and multiplication
	for n1+n2+n3+n4 != 24 && (n1*n2 != 24 && n1*n3 != 24 && n1*n4 != 24 && n2*n3 != 24 && n2*n4 != 24 && n3*n4 != 24) {
		n1 = rand.Intn(10) + 1
		n2 = rand.Intn(10) + 1
		n3 = rand.Intn(10) + 1
		n4 = rand.Intn(10) + 1
	}

	// Ask the player to solve the equation 24 using the 4 numbers
	fmt.Printf("Solve the equation 24 using the numbers %d, %d, %d, and %d\n", n1, n2, n3, n4)
	fmt.Print("Enter your answer: ")

	// Read the player's answer
	reader := bufio.NewReader(os.Stdin)
	input, _ := reader.ReadString('\n')
	input = strings.TrimSpace(input)

	// Check if the player's answer is correct
	answer := strconv.Itoa(n1) + strconv.Itoa(n2) + strconv.Itoa(n3) + strconv.Itoa(n4)
	if input == answer {
		fmt.Println("Correct!")
	} else {
		fmt.Printf("Incorrect. The correct answer is %s\n", answer)
	}
}