Sample code for golang to implement array segmentation

Time:2022-6-1

Requirements: given an array and a positive integer, it is required to divide the array into multiple arrays of positive integer size. If 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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Split array: according to the passed in array and split size, the array is divided into multiple arrays with a size equal to the specified size. If the score is not enough, 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 partition size. If yes, put the original array into a two-dimensional array and return
 if max <= num {
  return [][]int{arr}
 }
 //Get how many copies the array should be divided into
 var quantity int64
 if max%num == 0 {
  quantity = max / num
 } else {
  quantity = (max / num) + 1
 }
 //Declare a partitioned two-dimensional array
 var segments = make([][]int, 0)
 //Declare the cutoff subscript of a 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
}

Attachment: This is a problem I encountered in my actual business needs. I wonder if you have a better way to write it

This is the end of this article about the sample code of golang to implement array segmentation. For more information about golang array segmentation, please search the previous articles of developeppaper or continue to browse the related articles below. I hope you will support developeppaper in the future!

Recommended Today

A front-end developer's Vim is the same as an IDE

Here is my new configurationjaywcjlove/vim-webI've been grinding it, and it's basically ready to use. Take it out and cheat the star Install The latest version of Vim 7.4+ uses (brew install macvim) installation, vim version updatebrew install macvim –override-system-vim View configuration locations # Enter vim and enter the following characters :echo $MYVIMRC download vim-web Download […]