package globals

import (
	"math/rand"
	"time"
)

const MAX_TRY_TIMES uint8 = 100

//n: total num; offset: every one + offset
func GetOrderSlice(n int, offset int) *[]int {
	out := make([]int, n)
	for i := 0; i < n; i++ {
		out[i] = i + offset
	}
	// 测试
	//for index, _ := range out {
	//	log.Println(log.DebugLog, index, ":", out[index])
	//}
	return &out
}

func GetRandSlice(n int, offset int, topIndex int) (out *[]int) {
	var tryTimes uint8
	for tryTimes = 0; tryTimes < MAX_TRY_TIMES; tryTimes++ {
		out = Perm(n)
		// 切片中数据有重复，无效，再次获取0
		if nil == out {
			continue
		}
		for index, val := range *out {
			// 随机切片中，第一个数据不能是0
			if 1 == n {
				goto OUT
			} else if 0 == val && 0 == index {
				break
			} else if index != val {
				goto OUT
			}
		}
	}
	return nil

OUT:
	for index, _ := range *out {
		(*out)[index] += offset
	}
	if n > topIndex {
		for index, tmp := range *out {
			if topIndex == tmp {
				(*out)[index] = (*out)[0]
				(*out)[0] = tmp
				break
			}
		}
	}
	// 测试
	//for index, _ := range *out {
	//	log.Println(log.DebugLog, index, ":", (*out)[index])
	//}
	return out
}

//use native golang realize perm
func Perm(n int) *[]int {
	rand.Seed(time.Now().UnixNano())
	tmp := rand.Perm(n)
	return &tmp
}

//no need do thus perm, golang has realize the right one
//func WKPerm(n int) *[]int {
//	var out []int = make([]int, n)
//	for i := 0; i < n; i++ {
//		r := rand.New(rand.NewSource(time.Now().UnixNano()))
//		j := r.Intn(i + 1)
//		out[i] = out[j]
//		out[j] = i
//	}
//	sumOrder := 0
//	sumRand := 0
//	for k, tmp := range out {
//		sumRand += tmp
//		sumOrder += k
//	}
//	// 检查产生的切片是否有重复
//	if sumRand != sumOrder {
//		return nil
//	}
//	return &out
//}
