Home > Blockchain >  Golang Program to Find the Position of the Rightmost Number
Golang Program to Find the Position of the Rightmost Number

Time:12-29

Help me, please.

Please make Golang program to find the position of the rightmost number. For example: There are 10 arrays one dimention Number: 1 4 7 8 9 2 3 5 3 2 Position: 0 1 2 3 4 5 6 7 8 9 Input the number you want to find the position: 3 Output: The rightmost position of 3 is at index 8

CodePudding user response:

This can be done with a for loop

numbers := // slice of 1 4 7 8 9 2 3 5 3 2
numberToFind := 3

found := false
var position int

for index, number := range numbers {
   if number == numberToFind {
      found = true
      position = index
   }
}

if found {
   fmt.Println(fmt.Sprintf("found rightmost index of %v at %v", numberToFind, position))
} else {
   fmt.Println("number is not in the slice")
}

Running in Go Playground

CodePudding user response:

There are two important lessons to be learned from the problem.

First, encapsulate the solution in a function.

Functions organize code, making it more readable. Functions make code easy to reuse.

Second, to find the position of the last matching element in the list, start at the end.

If we start at the beginning, we have to scan the entire list to be sure that we have found the last matching list element. If we start at the end, we can stop scanning the list as soon as we find a matching list element.

If we don't find a matching list element then we return a special value of -1. The found condition is position >= 0, and not found is position < 0.


package main

import "fmt"

// LastIndex returns the index of the last instance of x in s,
// or -1 if x is not present in s.
func lastIndex(s []int, x int) int {
    i := len(s) - 1
    for ; i >= 0; i-- {
        if x == s[i] {
            return i
        }
    }
    return i
}

func main() {
    haystack := []int{1, 4, 7, 8, 9, 2, 3, 5, 3, 2}
    needle := 3

    position := lastIndex(haystack, needle)
    if position < 0 {
        fmt.Printf(
            "%v is not in %v\n",
            needle, haystack,
        )
    } else {
        fmt.Printf(
            "The rightmost position of %v is at index %v\n",
            needle, position,
        )
    }
}

https://go.dev/play/p/G7PCSX8IrNY

The rightmost position of 3 is at index 8
  • Related