vicuna-33b· LMSYS
Arena Human Preference 55K
Optimise this golang program package main import ( "bufio" "container/ring" "fmt" "os"…
- User
Optimise this golang program
package main
import ( "bufio" "container/ring" "fmt" "os" "strconv" )
func main() { totalElves := readInput("day19/input.txt") winner := findWinningElf(totalElves) fmt.Println(winner) }
func readInput(filename string) int { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close()
scanner := bufio.NewScanner(file) if scanner.Scan() { totalElves, err := strconv.Atoi(scanner.Text()) if err != nil { panic(err) } return totalElves } panic("Failed to read the input")}
func findWinningElf(totalElves int) int { elves := ring.New(totalElves) for i := 1; i <= totalElves; i++ { elves.Value = i elves = elves.Next() }
across := elves.Move(totalElves / 2) for elves.Len() > 1 { across.Unlink(1) if elves.Len()%2 == 0 { across = across.Next() } elves = elves.Next() } return elves.Value.(int)}
- Assistant
Here's an optimized version of the program:
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { totalElves := readInput("day19/input.txt") fmt.Println(findWinningElf(totalElves)) } func readInput(filename string) int { file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() scanner := bufio.NewScanner(file) if scanner.Scan() { totalElves, err := strconv.Atoi(scanner.Text()) if err != nil { panic(err) } return totalElves } panic("Failed to read the input") } func findWinningElf(totalElves int) int { consecutiveElves := 1 elves := 2 * consecutiveElves for consecutiveElves <= totalElves { consecutiveElves <<= 1 elves <<= 1 } elves -= totalElves across := elves >> 1 for elves > 1 { across -= 1 if elves&1 == 0 { across >>= 1 } elves >>= 1 } return (across + 1) * 2 }This optimized version simplifies the logic and reduces the number of operations by:
- Calculating the number of elves in a row and the total elves in a more concise way.
- Removing the
ringpackage and using simple integer operations instead.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.