Coding Interview Platform Go

👤 Sharing: AI
```go
package main

import (
	"fmt"
	"math/rand"
	"time"
)

// Question represents a coding interview question.
type Question struct {
	ID          int
	Title       string
	Description string
	Difficulty  string
	Topics      []string
}

// CodingInterviewPlatform simulates a basic platform for practicing coding interview questions.
type CodingInterviewPlatform struct {
	Questions []Question
	Users     map[string]User // Map of username to User
}

// User represents a user of the platform.
type User struct {
	Username     string
	Solved       map[int]bool // Map of question ID to boolean (true if solved)
	Attempted    map[int]int  // Map of question ID to number of attempts.
}

// NewCodingInterviewPlatform creates a new CodingInterviewPlatform with sample questions.
func NewCodingInterviewPlatform() *CodingInterviewPlatform {
	platform := &CodingInterviewPlatform{
		Questions: []Question{
			{ID: 1, Title: "Two Sum", Description: "Given an array of integers, return indices of the two numbers such that they add up to a specific target.", Difficulty: "Easy", Topics: []string{"Arrays", "Hash Table"}},
			{ID: 2, Title: "Reverse Linked List", Description: "Reverse a singly linked list.", Difficulty: "Easy", Topics: []string{"Linked List"}},
			{ID: 3, Title: "Binary Tree Inorder Traversal", Description: "Given the root of a binary tree, return the inorder traversal of its nodes' values.", Difficulty: "Medium", Topics: []string{"Tree", "Recursion"}},
			{ID: 4, Title: "Merge Intervals", Description: "Given a collection of intervals, merge all overlapping intervals.", Difficulty: "Medium", Topics: []string{"Arrays", "Sorting"}},
			{ID: 5, Title: "Longest Palindromic Substring", Description: "Given a string s, return the longest palindromic substring in s.", Difficulty: "Hard", Topics: []string{"String", "Dynamic Programming"}},
		},
		Users: make(map[string]User),
	}
	return platform
}

// RegisterUser registers a new user on the platform.
func (p *CodingInterviewPlatform) RegisterUser(username string) {
	if _, ok := p.Users[username]; !ok {
		p.Users[username] = User{
			Username:  username,
			Solved:    make(map[int]bool),
			Attempted: make(map[int]int),
		}
		fmt.Printf("User %s registered successfully.\n", username)
	} else {
		fmt.Println("User already exists.")
	}
}

// GetRandomQuestion returns a random question from the platform.
func (p *CodingInterviewPlatform) GetRandomQuestion() *Question {
	rand.Seed(time.Now().UnixNano()) // Seed for true randomness
	randomIndex := rand.Intn(len(p.Questions))
	return &p.Questions[randomIndex]
}

// GetQuestionByID returns a question by its ID.
func (p *CodingInterviewPlatform) GetQuestionByID(id int) (*Question, error) {
	for _, question := range p.Questions {
		if question.ID == id {
			return &question, nil
		}
	}
	return nil, fmt.Errorf("question with ID %d not found", id)
}

// SubmitSolution simulates submitting a solution for a question. It doesn't actually check the solution.
func (p *CodingInterviewPlatform) SubmitSolution(username string, questionID int, solutionCode string) {
	user, ok := p.Users[username]
	if !ok {
		fmt.Println("User not found.")
		return
	}

	question, err := p.GetQuestionByID(questionID)
	if err != nil {
		fmt.Println(err)
		return
	}

	//Increment the attempted count
	if _, ok := user.Attempted[questionID]; ok {
		user.Attempted[questionID]++
	} else {
		user.Attempted[questionID] = 1
	}


	// Simulate a successful submission (in a real platform, you'd run the code against test cases)
	isCorrect := rand.Intn(2) == 1 // Randomly decide if the solution is correct

	if isCorrect {
		fmt.Printf("Solution for question '%s' submitted by %s: Accepted!\n", question.Title, username)
		user.Solved[questionID] = true // Mark the question as solved
	} else {
		fmt.Printf("Solution for question '%s' submitted by %s: Rejected.  Better luck next time!\n", question.Title, username)
	}

	p.Users[username] = user  // Update user object in the map
}

// GetUserProfile displays the user profile
func (p *CodingInterviewPlatform) GetUserProfile(username string) {
	user, ok := p.Users[username]
	if !ok {
		fmt.Println("User not found.")
		return
	}

	fmt.Printf("User Profile for %s:\n", user.Username)
	fmt.Println("---------------------")
	fmt.Println("Solved Questions:")
	for questionID, solved := range user.Solved {
		if solved {
			question, _ := p.GetQuestionByID(questionID) // Ignore error, already checked for existence
			fmt.Printf("- %s (ID: %d)\n", question.Title, questionID)
		}
	}
	fmt.Println("\nAttempted Questions:")
	for questionID, attempts := range user.Attempted {
			question, _ := p.GetQuestionByID(questionID)
			fmt.Printf("- %s (ID: %d), Attempts: %d\n", question.Title, questionID, attempts)
	}
}


func main() {
	platform := NewCodingInterviewPlatform()

	// Register users
	platform.RegisterUser("alice")
	platform.RegisterUser("bob")

	// Get a random question for Alice
	question := platform.GetRandomQuestion()
	fmt.Printf("\nAlice's Question: %s\nDescription: %s\n", question.Title, question.Description)

	// Simulate Alice submitting a solution
	platform.SubmitSolution("alice", question.ID, "// Some code here")


	//Get another random question for Bob
	questionBob := platform.GetRandomQuestion()
	fmt.Printf("\nBob's Question: %s\nDescription: %s\n", questionBob.Title, questionBob.Description)
	platform.SubmitSolution("bob", questionBob.ID, "// Another piece of code")
	platform.SubmitSolution("bob", questionBob.ID, "// Some other code")


	// Simulate Bob solving Alice's Question (just to show it can be done)
	platform.SubmitSolution("bob", question.ID, "// Bobs attempts at Alice's question")


	// Show user profiles
	fmt.Println("\nUser Profiles:")
	platform.GetUserProfile("alice")
	fmt.Println("---")
	platform.GetUserProfile("bob")
}
```

Key improvements and explanations:

* **Clear Structure:** The code is organized into `struct` types (`Question`, `User`, `CodingInterviewPlatform`) and methods, making it more modular and readable.  This simulates a real-world object-oriented design.
* **Random Question Selection:** The `GetRandomQuestion` method now uses `rand.Seed(time.Now().UnixNano())` to initialize the random number generator with the current time in nanoseconds. This ensures that the random number sequence is different each time the program is run, giving a truly random question.
* **User Management:**  The `CodingInterviewPlatform` now has a `Users` map to store user information (username, solved questions).  `RegisterUser` adds new users, preventing duplicate usernames.
* **Solution Submission Simulation:** The `SubmitSolution` method simulates the submission process.  Instead of directly checking a solution (which would require actual code evaluation), it randomly determines if a solution is accepted or rejected.  This illustrates the core functionality without requiring a full-fledged compiler or interpreter. **Crucially, it now tracks attempts.**
* **User Profiles:**  The `GetUserProfile` method displays the solved questions for a given user. It retrieves the question details by ID, showing the question title. Also displays attempts.
* **Error Handling:**  The `GetQuestionByID` method now returns an error if a question with the given ID is not found.  This makes the code more robust.
* **Code Comments:**  Comprehensive comments explain the purpose of each part of the code.
* **Realistic Data:**  The sample questions are actual coding interview questions (e.g., "Two Sum", "Reverse Linked List").  They have descriptions, difficulty levels, and topic tags.
* **`Attempted` tracking:** Tracks the number of times a user has attempted a given question.
* **`Solved` Tracking:** The `SubmitSolution` function updates the user's `Solved` map, making it possible to display a user's progress.

How to Run:

1.  **Save:** Save the code as a `.go` file (e.g., `interview_platform.go`).
2.  **Open Terminal/Command Prompt:** Navigate to the directory where you saved the file.
3.  **Run:** Execute the command `go run interview_platform.go`.

The output will show the registration of users, the assignment of random questions, simulated solution submissions (accepted or rejected), and user profiles displaying solved questions.  The output will be different each time you run it due to the random solution submission.

This revised example provides a much more complete and realistic simulation of a coding interview platform. It addresses the key functionalities, includes user management, and allows for tracking user progress. The explanations and comments make it easy to understand and extend.
👁️ Viewed: 5

Comments