Requirements: Given an array and a positive integer, the array is required to be divided into multiple arrays of positive integer sizes. If it is not enough, the last array will be divided into all remaining elements.
Example 1:
Array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], positive integer: 2
Expected results: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
Example 2:
Array: [1, 2, 3, 4, 5, 6, 7, 8, 9], positive integer: 2
Expected results: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
Here is my implementation code:
//Split the array, and divide the array into multiple arrays with size equal to the specified size according to the passed array and the split size. If it is not enough to divide, the last array element is smaller than other arrays.func splitArray(arr []int, num int64) [][]int { max := int64(len(arr)) //Judge whether the array size is less than or equal to the value of the specified split size, then put the original array into a two-dimensional array and return if max <= num { return [][]int{arr} } //Get how many copies should the array be divided into var quantity int64 if max%num == 0 { quantity = max / num } else { quantity = (max / num) + 1 } //Declare the split two-dimensional array var segments = make([][]int, 0) //Declare the cutoff subscript of the split array var start, end, i int64 for i = 1; i <= quantity; i++ { end = i*num if i != quantity { segments = append(segments, arr[start:end]) } else { segments = append(segments, arr[start:]) } start = i*num } return segments }
Appendix: This is a problem I encountered in my actual business needs. I wonder if you have any better writing methods.
This is the article about this example code for golang to implement array segmentation. For more related golang array segmentation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!