Apriori算法的C/C#实现(一)

2014-11-24 10:45:17 · 作者: · 浏览: 0

数据结构的选取,还做得不太好,会继续改进,请大牛多多指点。

之后我会比较C#与C的Apriori程序,总结一些区别,谈谈面向对象编程在这个算法上的体现与数据结构的选择问题。


001 1 #include

002 2 #include

003 3 #include

004 4 #include

005 5 #include

006 6

007 7 #define ItemNumSize 2

008 8 #define TranNumSize 100

009 9 #define LISTINCREMENT 1

010 10 #define OK 1

011 11 #define TRUE 1

012 12 #define FASLE 0

013 13 #define ERROR 0

014 14 #define MAX_ARRAY_DIM 100

015 15 #define MAXSIZE 100

016 16 typedef char ItemType;

017 17 typedef int ElemType;

018 18 float minSupport,minConfidence;

019 19 //动态内存分配,item用什么数据结构 动态数组,线性表好:数组是整体创建,整体删除的

020 20 typedef struct www.2cto.com

021 21 {

022 22 ItemType *item;//项目

023 23 int length;//当前项目个数

024 24 int listsize;//当前分配的存储容量

025 25 }SqList;

026 26 //事务数组集合

027 27 typedef struct

028 28 {

029 29 SqList r[MAXSIZE+1];

030 30 int Length;

031 31 }TranList;

032 32

033 33 //初始化项目的线性表

034 34 int InitListSq(SqList &L)

035 35 {

036 36 L.item=(ItemType * )malloc(ItemNumSize *sizeof(ItemType));

037 37 if (!L.item)exit(OVERFLOW);//存储分配失败

038 38 L.length=0;//空表长度为0

039 39 L.listsize=ItemNumSize;//初始化存储容量

040 40 return OK;

041 41 }

042 42 //初始化事务的线性表

043 43 int InitListTran(TranList &TranL)//还有更好的动态分配方式初始化

044 44 {

045 45 for (int i=1;i<=TranNumSize;i++)

046 46 {

047 47 InitListSq(TranL.r[i]);

048 48 }

049 49 return OK;

050 50 }

051 51 //插入项目线性表

052 52 int listInsertSq(SqList &L,int i,ItemType e)

053 53 {

054 54 //在线性表L中第i个位置之前插入新元素e

055 55 //i的合法值为1<=i<=l.listlength+1

056 56 ItemType *newbase,*q,*p;

057 57 if(i<1||i>L.length+1)return ERROR;//i值不合法

058 58 if (L.length>=L.listsize)//当前存储空间已满,添加分配

059 59 {

060 60 //重新分配内存空间

061 61 newbase=(ItemType *)realloc(L.item,(L.listsize+LISTINCREMENT)*sizeof(ItemType));

062 62 if (!newbase)exit(OVERFLOW);

063 63 L.item=newbase;//新基址

064 64 L.listsize+=LISTINCREMENT;//增加存储容量

065 65 }

066 66 q=&(L.item[i-1]);//q为插入位置

067 67 for(p=&(L.item[L.length-1]);p>=q;--p)

068 68 *(p+1)=*p;//插入位置,及之后的元素右移

069 69 *q=e;

070 70 ++L.length;

071 71 return OK;

072 72 }

073 73 void main()

074 74 {

075 75 int c;

076 76 ItemType e;

077 77 SqList L;

078 78 int sn;

079 79 int ItemNum; //项目个数

080 80 int trannum[20]={0}; //事务数量

081 81 char b2[100][10];

082 82 char b21[100][10];

083 83 TranList TranL;

084 84 SqList L1;

085 85 InitListSq(L);

086 86 InitListTran(TranL);

087 87 printf ("链表长度:%d\n", L.length); // 线性表当前的元素个数

088 88 printf ("链表大小:%d\n", L.listsize); // 线性表最多可存放元素的个数

089 89 while (1)

090 90 {

091 91 system("cls");

092 92 printf_s("\n Apriori算法的C语言实现\n");

093 93 printf_s(" 1 输入项目集合\n");

094 94 printf_s(" 2 添加事务\n");

095 95 printf_s(" 3 设定最小支持度与最小置信度\n");

096 96 printf_s(" 4 输出结果\n");

097 97 printf_s(" 5 退出\n");

098 98 printf_s("请输入:\n");

099 99 scanf_s("%d",&c);

100 100 switch (c)

101 101 {

102 102