How to resolve the algorithm Greatest element of a list step by step in the Go programming language

Published on 12 May 2024 09:40 PM
#Go

How to resolve the algorithm Greatest element of a list step by step in the Go programming language

Table of Contents

Problem Statement

Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Greatest element of a list step by step in the Go programming language

First Source Code:

  • The largest function takes a slice of integers a as input and returns the largest integer in the slice.
  • The function first checks if the slice is empty. If it is, the function returns nil and false.
  • If the slice is not empty, the function initializes the lg variable to the first element in the slice.
  • The function then iterates over the remaining elements in the slice, comparing each element to lg.
  • If an element is greater than lg, the function updates lg to the new value.
  • After the iteration is complete, the function returns lg and true.

Second Source Code:

  • The largest function is similar to the first but it takes a map of float64s as input.
  • The map represents a set of numbers.
  • The function returns three values:
    • The largest number in the set.
    • A boolean indicating whether the set contains any NaNs (math.NaN()).
    • A boolean indicating whether the set contains any infinities (math.Inf()).
  • The function first checks if the set is empty. If it is, the function returns nil, false, and false.
  • If the set is not empty, the function initializes the lg, ok, and nan variables to 0, false, and false.
  • The function then iterates over the keys in the map.
  • For each key, the function checks if the key is NaN or infinity.
  • If the key is NaN, the function sets the nan variable to true.
  • If the key is infinity, the function sets the ok variable to false.
  • If the key is not NaN or infinity, the function compares the key to lg.
  • If the key is greater than lg, the function updates lg to the new value and sets the ok variable to true.
  • After the iteration is complete, the function returns lg, ok, and nan.

Usage:

  • The main function in both source codes calls the largest function with some sample input.
  • The main function in the first source code prints the largest integer in the slice and the main function in the second source code prints the largest number in the set, the presence of any NaNs, and the presence of any infinities.

Source code in the go programming language

package main

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

// function, per task description
func largest(a []int) (lg int, ok bool) {
    if len(a) == 0 {
        return
    }
    lg = a[0]
    for _, e := range a[1:] {
        if e > lg {
            lg = e
        }
    }
    return lg, true
}

func main() {
    // random size slice
    rand.Seed(time.Now().UnixNano())
    a := make([]int, rand.Intn(11))
    for i := range a {
        a[i] = rand.Intn(101) - 100 // fill with random numbers
    }

    fmt.Println(a)
    lg, ok := largest(a)
    if ok {
        fmt.Println(lg)
    } else {
        fmt.Println("empty list.  no maximum.")
    }
}


package main

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

// Function, per task description.  Interesting with the float64 type because
// of the NaN value.  NaNs do not compare to other values, so the result of
// a "largest" function on a set containing a NaN might be open to
// interpretation.  The solution provided here is to return the largest
// of the non-NaNs, and also return a bool indicating the presense of a NaN.
func largest(s map[float64]bool) (lg float64, ok, nan bool) {
    if len(s) == 0 {
        return
    }
    for e := range s {
        switch {
        case math.IsNaN(e):
            nan = true
        case !ok || e > lg:
            lg = e
            ok = true
        }
    }
    return
}

func main() {
    rand.Seed(time.Now().UnixNano())
    // taking "set" literally from task description
    s := map[float64]bool{}
    // pick number of elements to add to set
    n := rand.Intn(11)
    // add random numbers, also throw in an occasional NaN or Inf.
    for i := 0; i < n; i++ {
        switch rand.Intn(10) {
        case 0:
            s[math.NaN()] = true
        case 1:
            s[math.Inf(1)] = true
        default:
            s[rand.ExpFloat64()] = true
        }
    }

    fmt.Print("s:")
    for e := range s {
        fmt.Print(" ", e)
    }
    fmt.Println()
    switch lg, ok, nan := largest(s); {
    case ok && !nan:
        fmt.Println("largest:", lg)
    case ok:
        fmt.Println("largest:", lg, "(NaN present in data)")
    case nan:
        fmt.Println("no largest, all data NaN")
    default:
        fmt.Println("no largest, empty set")
    }
}


  

You may also check:How to resolve the algorithm Knapsack problem/Continuous step by step in the Forth programming language
You may also check:How to resolve the algorithm Doubly-linked list/Definition step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm List comprehensions step by step in the Insitux programming language
You may also check:How to resolve the algorithm Empty string step by step in the Swift programming language
You may also check:How to resolve the algorithm Lucas-Lehmer test step by step in the Seed7 programming language