-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.c
84 lines (74 loc) · 1.54 KB
/
utils.c
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* utils.c
* 工具函数
*/
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void print_array(int nums[], int len) {
printf("[");
for (int i = 0; i < len; i++) {
if (i < len-1) {
printf("%d, ", nums[i]);
} else {
printf("%d", nums[i]);
}
if (((i + 1) % 5 == 0) && (i != len - 1)) {
printf("\n");
}
}
printf("]\n");
}
void print_array2(int **nums, int rows, int cols) {
printf("[\n");
for (int i = 0; i < rows; i++) {
printf("[");
for (int j = 0; j < cols; j++) {
if (j < cols-1) {
printf("%d, ", nums[i][j]);
} else {
printf("%d", nums[i][j]);
}
if (j != 0 && j%10 == 0) printf("\n");
}
printf("]\n");
}
printf("]\n");
}
void swap(int nums[], int a, int b) {
if (a == b) return;
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
int maxnum(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
int minnum(int a, int b) {
if (a < b) {
return a;
} else {
return b;
}
}
int get_ith_dgt(int num, int i) {
return num % (int)pow(10, i+1) / (int)pow(10, i);
}
int get_dgt_cnt(int num) {
int i = 1;
while (num > pow(10, i)-1) {
i++;
}
return i;
}
void shuffle(int nums[], int len) {
// 最后一个位置自动确定了
for (int i = len-1; i > 0; i--) {
swap(nums, i, rand()%(i+1));
}
}