Capstone Project: Ticket to Mars
An exercise in variable scope and short declarations.
Description
Lately I’ve been reading the book Get Programming with Go by Nathan Youngman and Roger Peppé (2018). It’s a well structured book with well thought through exercises and capstone projects sprinkled throughout. In order to advance my knowledge of go, I thought I’d do all the exercises in the book and make a post about each of the capstone projects and offer my take on how I solved them; an equal parts explorative and learning endeavour. The “Ticket to Mars” project is the first capstone project and thus closes off unit one of the book, which covers loops & branches, variable scope, basic logic, control flow and short declaration of variables among other things.
Task
Create a ticket generator for space trips to Mars. Conditions:
- The speed at which the ship will travel is assigned randomly
- Round-trips cost twice as much
- Faster trips are more expensive
- Distance to Mars at departure time: 62,100,000 km
For a full description of the project, see Get Programming with Go (Youngman, Peppé, 2018).
Method
I tried to limit myself to the topics that have been covered in the book while solving this exercise. This can result in some rather redundant and nonsensical code. For this exercise the tricky part was to figure out how to produce the table if no lists, arrays, matrices or dataframes are allowed. The next step was to figure out what part of the code to loop through when using this sort of pseudo-table. All-in-all the project was straight forward and the tricky bits arose due to more conventional methods being off limits.
Output
Spaceline Days Trip type Price
======================================
Virgin Galactic 44 Round-trip $ 72
Space Adventures 34 One-way $ 38
Space Adventures 44 Round-trip $ 72
Virgin Galactic 26 Round-trip $ 82
Space Adventures 35 Round-trip $ 76
Space Adventures 26 Round-trip $ 82
Virgin Galactic 31 One-way $ 39
Virgin Galactic 23 One-way $ 43
Space Adventures 25 One-way $ 42
Space Adventures 32 One-way $ 39
Code
package __CapstoneMars
import (
"fmt"
"math/rand"
)
const MarsDistance int = 62100000
func TicketPricing() {
var Spaceline string
var TripType string
fmt.Printf("\n%-15v %-5v %v %6v \n", "Spaceline", "Days", "Trip type", "Price")
fmt.Println("======================================")
for count := 10; count > 0; count-- {
Speed := rand.Intn(15) + 16
Price := 28 + (Speed / 2)
Days := MarsDistance / Speed / 60 / 60 / 24
switch pseudoseed := rand.Intn(3) + 1; pseudoseed {
case 1:
Spaceline = "Virgin Galactic "
case 2:
Spaceline = "SpaceX "
case 3:
Spaceline = "Space Adventures"
}
switch pseudoseed := rand.Intn(2) + 1; pseudoseed {
case 1:
TripType = "One-way "
case 2:
TripType = "Round-trip"
Price = 2 * Price
}
fmt.Printf("%v %3v %11v $ %3v \n", Spaceline, Days, TripType, Price)
}
}
References
Youngman, Nathan & Peppé, Roger. (2018). Get programming with go. Manning Publications.