golang.org/x/playground@v0.0.0-20230418134305-14ebe15bcd59/examples/test.txt (about)

     1  // Title: Test
     2  package main
     3  
     4  import (
     5  	"testing"
     6  )
     7  
     8  // LastIndex returns the index of the last instance of x in list, or
     9  // -1 if x is not present. The loop condition has a fault that
    10  // causes somes tests to fail. Change it to i >= 0 to see them pass.
    11  func LastIndex(list []int, x int) int {
    12  	for i := len(list) - 1; i > 0; i-- {
    13  		if list[i] == x {
    14  			return i
    15  		}
    16  	}
    17  	return -1
    18  }
    19  
    20  func TestLastIndex(t *testing.T) {
    21  	tests := []struct {
    22  		list []int
    23  		x    int
    24  		want int
    25  	}{
    26  		{list: []int{1}, x: 1, want: 0},
    27  		{list: []int{1, 1}, x: 1, want: 1},
    28  		{list: []int{2, 1}, x: 2, want: 0},
    29  		{list: []int{1, 2, 1, 1}, x: 2, want: 1},
    30  		{list: []int{1, 1, 1, 2, 2, 1}, x: 3, want: -1},
    31  		{list: []int{3, 1, 2, 2, 1, 1}, x: 3, want: 0},
    32  	}
    33  	for _, tt := range tests {
    34  		if got := LastIndex(tt.list, tt.x); got != tt.want {
    35  			t.Errorf("LastIndex(%v, %v) = %v, want %v", tt.list, tt.x, got, tt.want)
    36  		}
    37  	}
    38  }