Commit a853f759 authored by Muhammad, Hammad's avatar Muhammad, Hammad

created a separate file like a class and used in main function and write data on file

parent e5041f69
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
)
// Create a new type of 'deck'
// which is a slice of strings
type deck []string
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" of "+suit)
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
func (d deck) toString() string {
return strings.Join([]string(d), ",")
}
func (d deck) saveToFile(filename string) error {
return ioutil.WriteFile(filename, []byte(d.toString()), 0666)
}
func newDeckFromFile(filename string) deck {
bs, err := ioutil.ReadFile(filename)
if err != nil {
// Option #1 - log the error and return a call to newDeck()
// Option #2 - Log the error and entirely quit the program
fmt.Println("Error:", err)
os.Exit(1)
}
s := strings.Split(string(bs), ",")
return deck(s)
}
func (d deck) shuffle() {
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
for i := range d {
newPosition := r.Intn(len(d) - 1)
d[i], d[newPosition] = d[newPosition], d[i]
}
}
package main
import "fmt"
type ShapeCalculator interface {
Area() int
Perimeter() int
}
type Rectangle struct {
Width int
Height int
}
func (r *Rectangle) Area() int {
return r.Width * r.Height
}
// func (r *Rectangle) Perimeter() int {
// return r.Width * r.Height
// }
// uncomment the following line to guarantee that Implementation implements all methods of SomeInterface
// var _ ShapeCalculator = (*Rectangle)(nil) // ← this is the line
func main() {
rect := &Rectangle{
Width: 10,
Height: 3,
}
fmt.Println(rect.Area())
cards := newDeck()
cards.shuffle()
cards.print()
}
// Execute commond both file like : go run main.go deck.go
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment