Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Library

case class Book(title: String, author: String, year: Int, category: String)

object LibraryManagement extends App {
  var library = List(
    Book("1984", "George Orwell", 1949, "Dystopian"),
    Book("To Kill a Mockingbird", "Harper Lee", 1960, "Fiction"),
    Book("The Great Gatsby", "F. Scott Fitzgerald", 1925, "Classic"),
    Book("Brave New World", "Aldous Huxley", 1932, "Dystopian"),
    Book("Moby Dick", "Herman Melville", 1851, "Classic"),
    Book("The Catcher in the Rye", "J.D. Salinger", 1951, "Fiction")
  )

  def addBook(library: List[Book], book: Book): List[Book] = {
    book :: library
  }

  def searchBooks(library: List[Book], query: String): List[Book] = {
    library.filter(book => book.title.contains(query) || book.author.contains(query))
  }

  def filterByCategory(library: List[Book], category: String): List[Book] = {
    library.filter(_.category == category)
  }

  def totalBooks(library: List[Book]): Int = {
    library.length
  }

  def averagePublicationYear(library: List[Book]): Double = {
    if (library.isEmpty) 0.0
    else library.map(_.year).sum.toDouble / library.length
  }

  println("Initial Library:")
  library.foreach(println)

  // Add a new book
  val newBook = Book("Sapiens", "Yuval Noah Harari", 2011, "Non-Fiction")
  library = addBook(library, newBook)

  println("\nLibrary after adding a new book:")
  library.foreach(println)

  // Search for books
  val searchQuery = "George Orwell"
  val searchResults = searchBooks(library, searchQuery)

  println(s"\nSearch results for '$searchQuery':")
  searchResults.foreach(println)

  // Filter by category
  val category = "Dystopian"
  val dystopianBooks = filterByCategory(library, category)

  println(s"\nBooks in the '$category' category:")
  dystopianBooks.foreach(println)

  // Calculate statistics
  val total = totalBooks(library)
  val averageYear = averagePublicationYear(library)

  println(s"\nTotal number of books: $total")
  println(f"Average publication year: $averageYear%.2f")
}