TutorialEdge

Challenge 18 - Minimum Rotations

Welcome, everyone to the discussion thread for the 17th Go challenge posted to the site :tada:

Feel free to show us how you solved the challenge by posting your solutions below!

Graciously stolen from https://github.com/shomali11/go-interview

Solution:

package main

import "fmt"

func MinRotations(array []int) int {
	// Implement me :)
	size := len(array)
	if size <= 1 {
		return 0
	}

	lowIndex := 0
	middleIndex := 0
	highIndex := size - 1
	for array[lowIndex] > array[highIndex] {
		middleIndex = (lowIndex + highIndex) / 2
		if array[middleIndex] > array[highIndex] {
			lowIndex = middleIndex + 1
		} else {
			highIndex = middleIndex
		}
	}
	return lowIndex
}

func main() {
	fmt.Println("Min Rotation Challenge")

	testArr := []int{15, 18, 2, 3, 6, 12}
	min := MinRotations(testArr) // returns 2
	fmt.Println(min)

	testArr2 := []int{7, 9, 11, 12, 5}
	min2 := MinRotations(testArr2) // return 4
	fmt.Println(min2)

}
1 Like

Got a simpler solution, did not attempt to algorithm complexity

package main

import "fmt"

func MinRotations(array []int) int {
  calc1 := 0
  calc2 := 0
  
  // rotation clockwise
  for i := 0; i < len(array)-1; i++ {
    if array[i] < array[i+1] {
     	calc1 = i
      	break
    }
  }
  
  // rotation anticlockwise
  for i := len(array)-1; i > 0; i-- {
    if array[i] < array[i-1] {
     	calc2 = i
      	break
    }
  }
  
  if calc1 > calc2 {
   	return calc1 
  }
  
  return calc2
}

func main() {
  fmt.Println("Min Rotation Challenge")

  testArr := []int{15, 18, 2, 3, 6, 12}
  min := MinRotations(testArr) // returns 2
  fmt.Println(min)

  testArr2 := []int{7, 9, 11, 12, 5}
  min2 := MinRotations(testArr2) // return 4
  fmt.Println(min2)

}
func MinRotations(array []int) int {
	count := 0
	for i := 0; i < len(array)-1; i++ {
		if array[i] > array[i+1] {
			count = i + 1
		}
	}
	return count
}