C语言实现文件内容按行随机排列的算法示例

2025-05-27 0 95

本文实例讲述了C语言实现文件内容按行随机排列的算法。分享给大家供大家参考,具体如下:

在实际工作上有种需求, 就是需要从给定的数据里,随机抽取一部分。

有一种简单的方法是根据总的数据条数和要抽取的数据条数, 通过简单方法,隔几行取一个,这样也能达到随机抽取一部分的目的。

但这样,源数据是顺序的,则抽取的数据也是顺序的,不满足一些情境。

这里实现的功能是: 将全部数据,按行重新随机排列, 这样从结果头部选几行,就是随机抽取的几行了,比较方便。

实现的思路: 对于N行的数据, 给每一行用[1-N]之间不重复的数做标记, 最后按标记数排列即可。(不重复上要稍微费点儿心思)

实现思路比较重要,实现就简单了~

实现上用c结合shell的方式,下面为参考代码。

总控脚本:用不重复随机数做标记,然后按标记排序

?

1

2

3

4

5

6

7
#!/bin/sh

### note: sh random.sh in_fname out_fname ###

infile=$1

outfile=$2

line_num=`cat $infile | wc -l `

./random $line_num $infile $outfile.tmp

sort $outfile.tmp -k 2 -n -t ' ' | cut -f1 > $outfile

随机化的执行程序random的实现

?

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

84

85

86

87

88

89

90

91

92

93
//random.c

#include <string>

#include <iostream>

#include <ctime>

#include <cstdlib>

using namespace std;

const int LEN = 4098;

//返回属于[p,q)的随机整数

int rand(int p, int q)

{

int size = q-p+1;

return p+ rand()%size;

}

//交换两个元素值

void swap(int& a , int& b)

{

int temp = a;

a = b;

b = temp;

}

//打印数组值

void print(int *v, int n)

{

for(int i=0; i < n ; i++)

{

printf("%u\\n", v[i]);

}

}

//给数组a[n], 随机不重复赋值[1,n]之间的数

void randomize(int *v, int n)

{

//initialize

for(int i=0; i < n; i++)

{

v[i] = i+1;

}

for(int i=n-1; i>0; i--)

{

int r = rand(0,i+1);

swap(v[r], v[i]);

}

}

//删除换行符

int chomp(char *str)

{

int len = strlen(str);

while(len > 0 && (str[len - 1] == '\\n' || str[len - 1] == '\\r'))

{

str[len - 1] = 0;

len--;

}

return len;

}

//主函数

int main(int argc, char *argv[])

{

int line_num = atoi(argv[1]);

printf("%u\\n",line_num);

int *value = (int*)malloc((line_num) * sizeof(int));

printf("%u\\n",line_num);

randomize(value, line_num);

//print(value, N);

FILE* infile = fopen(argv[2], "r");

if( infile == NULL )

{

printf("Cann't open file %s.", argv[1]);

return 0;

}

FILE* outfile = fopen(argv[3], "w");

if( outfile == NULL)

{

printf("Cann't open file %s to write.", argv[2]);

return 0;

}

int i=0;

char str[LEN];

str[0] = 0;

str[LEN-1] = 0;

while( !feof(infile) )

{

if( !fgets(str, sizeof(str),infile))

{

break;

}

str[LEN- 1] = 0;

chomp(str);

fprintf(outfile, "%s\\t%u\\n", str, value[i]);

i++;

}

fclose(infile);

fclose(outfile);

return 0;

}

希望本文所述对大家C语言程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C语言实现文件内容按行随机排列的算法示例 https://www.kuaiidc.com/73152.html

相关文章

发表评论
暂无评论