楼主: midfirefly
跳转到指定楼层
上一主题 下一主题
收起左侧

[Coursera]Stanford 算法课 Design and Analysis of Algorithm I 第二期 Week1 加分贴

🔗
shidaohang 2012-6-22 09:30:47 | 只看该作者
全局:
shidaohang 发表于 2012-6-22 09:25

第一次用vim+gcc+gdb写代码,那个SplitCountInv搞的比较久。
收获:
1.gdb真的还蛮好用的
2.vim也熟练很多了
不足:
还是不够熟练,要多加练习,写好代码找好工作,大家一起加油
回复

使用道具 举报

🔗
shidaohang 2012-6-22 09:32:49 | 只看该作者
全局:
sevensin 发表于 2012-6-19 15:02
用了C++和Python写第一次作业。先写心得再贴代码。总的来说目标如下:想写的代码比较通用,比如适应不同输入 ...

你好有心啊,话说我最近也打算再学一门python的,去年学过的perl很久没用过了,基本和没学过差不多了,python要好好学
回复

使用道具 举报

全局:
本帖最后由 蜡笔小丸子 于 2012-6-22 22:04 编辑

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;


unsigned int MergeAndCountSplit(int Array[], int iFirst,int iLast)
{
        int iMid = (iLast+iFirst)/2;
        int lenLeft = iMid-iFirst+1; // length of left sub array
        int lenRight = iLast-iMid; //length of right subarray
        unsigned int Count=0;

        // split the array into two subarrays
        int iLeft = iFirst;
        int iRight = iMid +1;
        
        int * LeftArray = new int[lenLeft];
        for (int l=0 ;l<iMid-iFirst+1;l++)
        {
                LeftArray[l]=Array[iLeft];
                iLeft++;
        }
        int * RightArray = new int[lenRight];
        for (int l=0 ;l<iLast-iMid;l++)
        {
                RightArray[l]=Array[iRight];
                iRight++;
        }      
        int i=0;
        int j=0;
        while (i<lenLeft || j<lenRight ) //traverse the two subarrays
        {
                if (i==lenLeft)
                {
                        Array[iFirst +i +j] = RightArray[j];
                        j++;
                }else if (j==lenRight)
                {
                        Array[iFirst +i +j] = LeftArray;
                        i++;
                }
                else if (LeftArray[i]<=RightArray[j]) // left<=right, put left item into sorted array

                {
                        Array[iFirst +i +j] = LeftArray[i];

                        i++;//left array index +1
                }
                else // left> right, put the right item into sorted array
                {
                        Array[iFirst +i+j] = RightArray[j];
                        j++; //right array index +1
                        Count += (lenLeft -i);
                }
        }
        //delete the temporary subarrays
        delete RightArray;
        delete LeftArray;
[/i][/i]
[i][i]
        return Count;
}

unsigned int SortAndCount(int arrayA[], int iFirst, int iLast)
{
        if (iLast==iFirst) return 0;
        else
        {
                int iMid = (iLast+iFirst)/2 ;
                int firstHalfInv = SortAndCount(arrayA,iFirst,iMid);//sort and count inversions in the 1st half of array A
                int secondHalfInv = SortAndCount(arrayA,iMid+1, iLast);//sort and count inversions in the 1st half of array A
                unsigned int splitInv = MergeAndCountSplit(arrayA, iFirst,iLast);  //count inversions and merge the two halves of array A
                return firstHalfInv + secondHalfInv + splitInv;  //total inversion
        }
}
[/i][/i]
[i][i]
void main()
{
        int *myArray = new int[100000];
        ifstream myFile("IntegerArray.txt");
        if (myFile.is_open())
        {
                string line;
                for (int i = 0; !myFile.eof(); i++)
                {
                        getline(myFile,line);
                        myArray[i]=atoi(line.c_str());

                }
                myFile.close();
        }
        else
                cout<<"Unable to open file."<<endl;
        
        const clock_t begin_time = clock();
        unsigned int count = SortAndCount(myArray,0,99999);
        cout<<"inversions = "<<count<<endl;
        cout<<"time = "<<float(clock() - begin_time)/CLOCKS_PER_SEC;
        
        system("pause");
}
[/i][/i][/i][i][i][i]
time =0.343s

[/i][/i][/i]

评分

参与人数 1大米 +20 收起 理由
paradox + 20

查看全部评分

回复

使用道具 举报

🔗
paradox 2012-6-22 14:26:37 | 只看该作者
全局:

点评

Sharing source code of PA is against the honor code of coursera  发表于 2012-12-17 08:33
回复

使用道具 举报

🔗
lotustree 2012-6-23 01:23:03 | 只看该作者
全局:
我的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;




public class mergeCountInverse {


        public static long countSplit(Integer[] intArray, int start, int end){
               
                int mid = (start+end)/2;
                int i = start;
                int j = mid +1;
                long num = 0;
               
                while (i<=mid && j<=end){               
                        if (intArray[i]<intArray[j]){
                                i++;
                        }       
                        else{
                                int tmp = intArray[j];
                               
                                for(int n = j; n>i; n--){
                                        intArray[n]=intArray[n-1];
                                }
                               
                                intArray[i] = tmp;
                                i++;
                                j++;
                                mid++;
                                num = num + mid - i + 1 ;
                        }
                }                       
               
                return num;
        }
       
       
       
        public static long mergeCountInv(Integer[] intArray, int start, int end ){
                long leftNum, rightNum,splitNum;
               
                if (start>=end)       
                        return 0;
                else {
                        leftNum = mergeCountInv(intArray, start,(start+end)/2);
                        rightNum = mergeCountInv(intArray, (start+end)/2 + 1,end );
                       
                        splitNum= countSplit(intArray, start, end);
               
                        return (leftNum+rightNum+splitNum);
                }
               
        }
        /**
         * @param args
         * @throws IOException
         * @throws NumberFormatException
         */
        public static void main(String[] args) throws NumberFormatException, IOException {
               
                List<Integer> list=new ArrayList<Integer>();
                BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(new File("IntegerArray.txt"))));
                String str=null;
                while((str=br.readLine())!=null)
                {
                list.add(new Integer(str));


                }
                Integer[] intArray=new Integer[list.size()];
                intArray=list.toArray(intArray);               
               
                // TODO Auto-generated method stub
                //int [] intArray = {3,2,1,5,6,8};
                long num = 0;
                num = mergeCountInv(intArray,0,intArray.length-1);
                System.out.println("Inversed Number=: " + num);
//                 for(int i = 0; i <intArray.length; i++){
//                          System.out.print(intArray[i]+"  ");
//                          //System.out.println();
//                         // System.out.println("PAUSE");
//                          }
        }


}



回复

使用道具 举报

🔗
497760339 2012-6-23 11:27:46 | 只看该作者
全局:
本帖最后由 497760339 于 2012-6-23 11:30 编辑

来晚了。。也贴一下python的代码
有个地方没有注意,花了一点时间调试,python读取文件后是字符串,所以1和10比好像1比较大,转成int就可以了,但是这个错误比较隐蔽,调了有个十几二十分钟。。。

01 def merge_sort(list_in):
02     if(len(list_in)<=1):
03         return list_in
04     left = list_in[:len(list_in)/2]
05     right = list_in[len(list_in)/2:]
06     left_result = merge_sort(left)
07     right_result = merge_sort(right)
08     return merge(left_result,right_result)
09
10 def merge(list_left,list_right):
11     count = len(list_left)+len(list_right)
12     list_left.append(-1)
13     list_right.append(-1)
14     result = []
15     while(count>0):
16         if(int(list_left[0])>int(list_right[0])):
17             global inversions
18             increase = len(list_right)-1
19             inversions += increase
20             result.append(list_left.pop(0))
21         else:
22             result.append(list_right.pop(0))
23         count -= 1
24     return result
25
26 txt_to_list = open("IntegerArray.txt")
27 #txt_to_list = open("1.txt")
28 txt_to_list = txt_to_list.readlines()
29 inversions = 0
30 inversions2 = 0
31 merge_sort(txt_to_list)
32 print inversions

回复

使用道具 举报

🔗
光殇 2012-6-23 19:08:20 | 只看该作者
全局:
本帖最后由 光殇 于 2012-6-23 20:29 编辑

来水个分。。。程序写得有点乱,先贴着吧,回头再整理把注释添上
看了前面童鞋们的心得和问题,也有几点想法。。
1. 输入。本菜感觉C++用流输入直接>>会比较方便,也不用考虑什么行之类的了,题目说的是10W个数据,就直接把循环变量设为10W,一直读就好了。不知道这个方法有没有什么缺陷或者考虑不周的地方,希望大牛们指出。
2. 验证。本菜写了一个暴力方法来验证merge的正确率。随机生成1k或者是几百的数字,然后两个分别算,验证是否一样。本菜觉得这验证方法不错~本菜就是验证了几次后,比较自信代码写对了,所以后面出现错误就能比较好地改正。
3. 精度。这个在写的时候真的没考虑到,失策了。用int类型直接爆了,出来的是一个乱七八糟的复数。因为通过了前面的验证,所以知道程序应该没问题,就从精度上想。long其实和int类型的精度是一样的,不过unsigned long就要大一点。如果这数据再多一点的话,可能就要用到64位的数据类型了。
4. 数组表示。其实本菜以前一直是用栈里面的数据的,,因为不用涉及到指针,本菜以前一看指针就放弃了~但是用栈的数组,对于在函数传值来说非常不方便,所以这次试着用了一下指针,当学习学习。感觉挺爽,数组指针也可以直接用方括号[]的表示方法来取值,所以程序看上去不是很纠结,只是声明的时候不一样,并且要记着new和delete就好了。如果不想用指针的童鞋也可以用vector,灰强好用~~~

#include<iostream>
#include<fstream>

using namespace std;
unsigned long CalInver(int* a, int n);
unsigned long Merge(int* a, int* b, int leftn, int* c, int rightn);
int main()
{
int n = 100000;
int* a;
ifstream ifs("D:\\input.txt");
a = new int[100000];

for(int i=0; i<n; i++)
  ifs>>a;


cout<<CalInver(a, n)<<endl;

return 0;
}


unsigned long CalInver(int* a, int n)
{
if(n<=1)
  return 0;


else
{
  int leftn = n/2;
  int rightn = n-leftn;
  int* b = new int[leftn+1];
  int* c = new int[rightn+1];


  for(int i=0; i<leftn; i++)
   b[i] = a[i];
  b[leftn] = 999999;
  for(i=0; i<rightn; i++)
   c[i] = a[i+leftn];
  c[rightn] = 999999;


  int leftnum = CalInver(b, leftn);
  int rightnum = CalInver(c, rightn);


  unsigned long num = Merge(a, b, leftn, c, rightn) + leftnum + rightnum;

  delete b;
  delete c;
  return num;
}
}


unsigned long Merge(int* a, int* b, int leftn, int* c, int rightn)
{
int j = 0;
int k = 0;
unsigned long count = 0;


for(int i=0; i<leftn+rightn; i++)
{
  if(b[j]<=c[k])
   a[i] = b[j++];


  else
  {
   a[i] = c[k++];
   count += leftn-j;
  }
}
return count;
}


[/i][/i][/i][/i][/i]
回复

使用道具 举报

🔗
touchzou 2012-6-23 22:09:45 | 只看该作者
全局:
本帖最后由 touchzou 于 2012-6-23 22:13 编辑

#include <stdio.h>
#include <stdlib.h>

void read_data(char *, int *);

void sort(int *, int, int);

void merge(int *, int, int, int);


long long number = 0;


int main(void)
{

    int array[100000];
    int x;

    read_data("D:\\IntegerArray.txt", array);
    printf("ok!\n");
    sort(array, 0, 99999);

    /**
    int array[3] = {5, 1, 2};
    int x;
    sort(array, 0, 2);
    */
    for(x = 0; x < 3; x++)
    {

        printf("%d\n", array[x]);
    }
    printf("%lld\n", number);
    printf("Hello World!\n");
    return 0;
}

void read_data(char * filename, int * point)
{
    char temp[20];
    int x = 0;
    FILE * pFile = fopen(filename, "rb");
    if(pFile == NULL)
    {
        printf("Cannot open the file %s!\n", filename);
        return;
    }
    while(x < 100000)
    {
        fscanf(pFile, "%s", temp);
        if(x == 0)
            printf("%s", temp);
        *point = atoi(temp);
        point++;
        x++;
    }
    fclose(pFile);
}

void sort(int *array, int low, int high)
{
    int mid = (low + high)/2;
    if(low < high)
    {
        sort(array, low, mid);
        sort(array, mid + 1, high);
        merge(array, low, mid, high);
    }
}

void merge(int *array, int low, int mid, int high)
{
    int temp[high - low + 1];
    int i = low;
    int j = mid + 1;
    int x = 0;
    while(i <= mid && j <= high)
    {
        if(array[i] >= array[j])
        {
            temp[x] = array[j];
            j++;
            number += mid - i + 1;
        }
        else
        {
            temp[x] = array[i];
            i++;
        }
        x++;
    }

        while(i <= mid)
        {
            temp[x] = array[i];
            x++;
            i++;
        }



        while(j <= high)
        {
            temp[x] = array[j];
            x++;
            j++;
        }

    for(x = 0; x < high - low + 1; x++)
        array[low + x] = temp[x];
}
Output is: 2407905288
回复

使用道具 举报

🔗
boplusplus 2012-6-24 02:19:08 | 只看该作者
全局:
赶了个晩集,工作太忙了。。。有点取巧了,用MATLAB写的,呵呵
function [ sorted,count] = inversion_count( data )
len = length(data);
if len == 1
    sorted = data;
    count = 0;
    return
end

a = data(1:floor(len/2));
b = data(floor(len/2)+1:len);
[c,count1] = inversion_count(a);
[d,count2] = inversion_count(b);
[sorted , count3]=mergesorted(c,d);
count = count1 + count2 + count3;
end


function [c,count] = mergesorted(a,b)

lena = length(a);
lenb = length(b);
c=zeros(1,lena+lenb);
count = 0;

inda = 1;      % index to move along vector 'a'
indb = 1;      % index to move along vector 'b'
indc = 1;      % index to move along vector 'c'
while ((inda <= lena) && (indb <= lenb))
if a(inda) < b(indb)
    c(indc) = a(inda);
    inda = inda + 1;
else
    c(indc) = b(indb);
    count = count + lena - inda +1;
    indb = indb + 1;
end
indc = indc + 1;
end

% copy any remaining elements of the 'a' into 'c'
while (inda <= lena)
  c(indc) = a(inda);
  indc = indc + 1;
  inda = inda + 1;
end
% copy any remaining elements of the 'b' into 'c'
while (indb <= lenb)
  c(indc) = b(indb);
  indc = indc + 1;
  indb = indb + 1;
end
end
回复

使用道具 举报

🔗
stephenK 2012-6-24 09:36:51 | 只看该作者
全局:
本帖最后由 stephenK 于 2012-6-24 09:38 编辑

#!/usr/bin/python
import sys
import os
import time
  
def count(array,low,high):
    if high ==low:
        return 0
    else:
        num1 = count(array, low, (low+high)/2)
        num2 = count(array, 1+(low+high)/2, high)
        num3 = mergecount(array, low, (low+high)/2, high)
        return num1+num2+num3
  
def mergecount(ar, low, mid, high):
    num = k= 0
    i = low
    j = 1 + mid
    du = [0]*(high-low+1)
    while (i<=mid) & (j<=high):
        if ar <= ar[j]:
            du[k] = ar
            i = i+1
        else:
            du[k] = ar[j]
            num = num + mid - i+1
            j = j+1
        k = k+1
    if i>mid:
        du[k:] = ar[j:high+1]
    else:
        du[k:] = ar[i:mid+1]        
    ar[low:high+1] = du
    return num
        
   
def main():
    t1 = time.clock()
    if len(sys.argv) <2:
        print "error! forgot to input data file?"
        sys.exit(1)
    filename = sys.argv[1]
    f = open(filename,'r')
    str = f.read()
    input = str.split("\n")
  #  input = input[:-1]
    inputArray = []
    for item in input:
        if item !="":
            inputArray.append(int(item))

    inversion_num = count(inputArray,0,len(inputArray)-1)
    t2 = time.clock()
    print "time elapsed: ",t2-t1
    print 'after sorting:'
    print "total num of inversion: ", inversion_num
        
   
if __name__ == "__main__":
    main()ort sys
import os
import time
  
def count(array,low,high):
    if high ==low:
        return 0
    else:
        num1 = count(array, low, (low+high)/2)
        num2 = count(array, 1+(low+high)/2, high)
        num3 = mergecount(array, low, (low+high)/2, high)
        return num1+num2+num3
  
def mergecount(ar, low, mid, high):
    num = k= 0
    i = low
    j = 1 + mid
    du = [0]*(high-low+1)
    while (i<=mid) & (j<=high):
        if ar <= ar[j]:
            du[k] = ar
            i = i+1
        else:
            du[k] = ar[j]
            num = num + mid - i+1
            j = j+1
        k = k+1
    if i>mid:
        du[k:] = ar[j:high+1]
    else:
        du[k:] = ar[i:mid+1]        
    ar[low:high+1] = du
    return num
        
   
def main():
    t1 = time.clock()
    if len(sys.argv) <2:
        print "error! forgot to input data file?"
        sys.exit(1)
    filename = sys.argv[1]
    f = open(filename,'r')
    str = f.read()
    input = str.split("\n")
  #  input = input[:-1]
    inputArray = []
    for item in input:
        if item !="":
            inputArray.append(int(item))

    inversion_num = count(inputArray,0,len(inputArray)-1)
    t2 = time.clock()
    print "time elapsed: ",t2-t1
    print 'after sorting:'
    print "total num of inversion: ", inversion_num
        
   
if __name__ == "__main__":
    main()


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表