bestchains / HackTheAI

Apache License 2.0
2 stars 7 forks source link

AI评测: 代码生成 #6

Open bjwswang opened 1 year ago

bjwswang commented 1 year ago

Case 1 解析字符串,转为time.Time

Result

import (
    "errors"
    "fmt"
    "regexp"
    "strconv"
    "time"
)

func parseDuration(s string) (time.Time, error) {
    // Use regular expressions to extract the duration components
    r := regexp.MustCompile(`(\d+)days(\d+)hours(\d+)minutes(\d+)seconds`)
    matches := r.FindStringSubmatch(s)
    if len(matches) != 5 {
        return time.Time{}, errors.New("invalid duration format")
    }

    // Parse the duration components into integers
    days, _ := strconv.Atoi(matches[1])
    hours, _ := strconv.Atoi(matches[2])
    minutes, _ := strconv.Atoi(matches[3])
    seconds, _ := strconv.Atoi(matches[4])

    // Calculate the total duration in seconds
    totalSeconds := (days * 24 * 60 * 60) + (hours * 60 * 60) + (minutes * 60) + seconds

    // Get the current time and add the duration to it
    now := time.Now()
    duration := time.Duration(totalSeconds) * time.Second
    future := now.Add(duration)

    // Return the future time
    return future, nil
}