Git Product home page Git Product logo

dsa_intersectingtriangles's Introduction

Intersecting Triangles

Strategy

int counting(left, right)
    if (left+1 == right)
        return 0
    mid = (left + right) / 2
    cnt = counting(left, mid)
    cnt += counting(mid,left)

    r = mid
    for l = left to mid
        while (r<right && A[l]>A[r]) //l<r
            r++
        cnt += r-mid

    return cnt
  1. Convert Q, and R to max and min
  2. Sort P along with max, min
  3. Sort max and min at the same time with sorted P

Count inversions with C

// C program to Count
// Inversions in an array
// using Merge Sort
#include <stdio.h>
#include <stdlib.h>
 
int _mergeSort(int arr[], int temp[],
               int left, int right);
int merge(int arr[], int temp[],
          int left, int mid,
          int right);
 
/* This function sorts the input array and returns the
   number of inversions in the array */
int mergeSort(int arr[], int array_size)
{
    int* temp = (int*)malloc(sizeof(int) * array_size);
    return _mergeSort(arr, temp, 0,
                      array_size - 1);
}
 
/* An auxiliary recursive function
   that sorts the input
  array and returns the number
  of inversions in the array.
*/
int _mergeSort(int arr[], int temp[], int left, int right)
{
    int mid, inv_count = 0;
    if (right > left)
    {
        /* Divide the array into two parts and call
       _mergeSortAndCountInv() for each of the parts */
        mid = (right + left) / 2;
 
        /* Inversion count will be the sum of inversions in
        left-part, right-part and number of inversions in
        merging */
        inv_count += _mergeSort(arr, temp, left, mid);
        inv_count += _mergeSort(arr, temp, mid + 1, right);
 
        /*Merge the two parts*/
        inv_count += merge(arr, temp, left, mid + 1, right);
    }
    return inv_count;
}
 
/* This funt merges two sorted
   arrays and returns inversion
   count in the arrays.*/
int merge(int arr[], int temp[], int left, int mid,
          int right)
{
    int i, j, k;
    int inv_count = 0;
 
    i = left; /* i is index for left subarray*/
    j = mid; /* j is index for right subarray*/
    k = left; /* k is index for resultant merged subarray*/
    while ((i <= mid - 1) && (j <= right)) {
        if (arr[i] <= arr[j]) {
            temp[k++] = arr[i++];
        }
        else
        {
            temp[k++] = arr[j++];
 
            /*this is tricky -- see above
             * explanation/diagram for merge()*/
            inv_count = inv_count + (mid - i);
        }
    }
 
    /* Copy the remaining elements of left subarray
   (if there are any) to temp*/
    while (i <= mid - 1)
        temp[k++] = arr[i++];
 
    /* Copy the remaining elements of right subarray
   (if there are any) to temp*/
    while (j <= right)
        temp[k++] = arr[j++];
 
    /*Copy back the merged elements to original array*/
    for (i = left; i <= right; i++)
        arr[i] = temp[i];
 
    return inv_count;
}
 
/* Driver code*/
int main(int argv, char** args)
{
    int arr[] = { 1, 20, 6, 4, 5 };
    printf(" Number of inversions are %d \n",
           mergeSort(arr, 5));
    getchar();
    return 0;
}

Ref: https://www.geeksforgeeks.org/counting-inversions/

How to know two triangles have intersection(s)?

Let points on two distinct triangles be (P,Q,R) and (P',Q',R').

  • No intersection happens when
    • P > P' and min(Q',R') > max(Q,R)
  • Intersection happens: Otherwise

Range of Int

  • Int: 4 bytes
    • 32 bit (1 byte = 8 bit)
    • Range: -2^31 ~ 2^31-1
  • Belongs to the range

Ref: https://www.tutorialspoint.com/cprogramming/c_data_types.htm

Hints

排序

  1. 排序 P
  2. 左邊 max
  3. 右邊 min

逆序述對

  • 定義

    • A[i] > A[j]
    • i<j
  • 計算逆序數對

Ref:

Merge sort

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


// Merge two subarrays of A[].
// First subarray is arr[head..mid]
// Second subarray is arr[mid+1..tail]
void merge(int arr[], int head, int mid, int tail){
  int lenA = mid - head + 1;
  int lenB = tail - (mid + 1) + 1;
  int A[lenA];
  int B[lenB];

  //Copy data to temp arrays A[] and B[]
  int i, j, k;
  for(i = 0; i < lenA; i++){
    A[i] = arr[head + i];
  }
  for(j = 0; j < lenB; j++){
    B[j] = arr[mid + 1 + j];
  }

  // Merge two temp arrays back into arr[head..tail]
  i = 0;
  j = 0;
  k = head;
  //while array A and B haven't finished scanning
  while(i < lenA && j < lenB){
    if(A[i] < B[j]){
      arr[k] = A[i];
      i++;
    }
    else{
      arr[k] = B[j];
      j++;
    }
    k++;
  }

  //Copy the remaing elements into arr[], if A[] haven't finished scanning
  while(i < lenA){
    arr[k] = A[i];
    i++;
    k++;
  }
  //Copy the remaing elements into arr[], if B[] haven't finished scanning
  while(j < lenB){
    arr[k] = B[j];
    j++;
    k++;
  }
}

void merge_sort(int arr[], int head, int tail){
  if(head < tail){
    int mid = (head + tail) / 2;
    merge_sort(arr, head, mid);
    merge_sort(arr, mid+1, tail);
    merge(arr, head, mid, tail);
  }
}


int main(){
  int count, i;
  scanf("%d", &count);

  int list[count];
  printf("Numbers to be sorted: ");
  for(i = 0; i<count; i++){
    scanf("%d", &list[i]);
    printf("%d ", list[i]);
  }
  printf("\n");

  merge_sort(list, 0, count-1);

  printf("Numbers Sorted: ");
  for(i = 0; i<count; i++){
    printf("%d ", list[i]);
  }

  return 0;
}

Ref:

Merge sort in CLRS

Merge Sort

MERGE_SORT(A,p,r)
  if p<r
    q = round( (p+r)/2 )
    MERGE-SORT(A,p,q)
    MERGE-SORT(A,q+1, r)
    MERGE(A,p,q,r)

Merge

MERGE(A,p,q,r)
  n1 = q - p + 1 // length of sub-array 1 [str, end]
  n2 = r - q // (str, end]
  let L[1..n1+1] and R[1..n2+1] be new arrays
  for i = 1 to n1
    L[i] = A[p+i-1]

  for j = 1 to n2
    R[j] = A[q+j]

  L[n1+1] = inf
  R[n2+1] = inf

  i = 1
  j = 1
  for k = p to r
    if L[i] <= R[j]
      A[k] = L[i]
      i = i+1
    else 
      A[k] = R[j]
      j = j + 1 

Draft


Returning array in C

Ref: https://www.javatpoint.com/return-an-array-in-c

Copy array with memcpy

https://stackoverflow.com/questions/2681061/memcpy-what-should-the-value-of-the-size-parameter-be

Draft

dsa_intersectingtriangles's People

Contributors

stevengogogo avatar

Stargazers

 avatar

Watchers

 avatar

dsa_intersectingtriangles's Issues

[HW2][P5] Problem with debugging for Wrong Answer

DSA 助教您好,

我想要詢問 Intersecting Triangle 的 Debug 問題.

簡介我的測試方法 [附上 zip 中的檔案路徑]

我目前使用自己生成的測資 (test/dataGen/*.txt) 用的是隨機生成和 naive 的方式計算 overlapped triangle (test/dataGen.jl). 多次測試都可以通過. 因為 naive 用的是 n^2 演算法, 我只測試 10000 以下的各種可能.

簡介我的方法 [gist]

我用的方法是使用 merge sort 排序 P, 用 struct 包住 保持 p/r/l 之間的關係, 其中 l<=r. 然後再用一次 merge sort 在 r/l 計算左邊 r / 右邊l 的逆序數對 (左邊 P<= 右邊P).
相同 P 的部分, 因為每次 merge 前都已確定為 monotonous increasing. 所以就看分割序號的 m/m+1 是否相同, 找到右邊同類的P數 Iden (gist line 180) 然後在計算逆序數對時, 如果右邊的 pivot 找到來自於相同P 則 --Iden, 因為已經是逆序數對了。所以遇上 r[k] 是來自相同的 P 時, 就把剩下的 Iden 加上 inv (逆序總數)

我還做了什麼測試

用 Valgrind 找出 malloc 記憶體計算錯誤的問題. 沒有 memory leak
將 malloc 預先在 merge sort 前弄好, 解決 TLE
用生成的測資測試正確性
避開 static variable 的名稱 p,q,r -> p_,q_,r_
計算需要的 heap 記憶體量為 23 * 8 * 3e6 B = 552MB . 23 為 array 數目 (包含 struct 內的); 8 為 integer size, 3e6 為最大 n.

問題

Wrong Answer [見附件 Result.png]

Source code
附件檔案(main.c)的 submit hash: 5ba84c8db0cda3804b2efa7e1d7afe9df5e878a0
Documentation: https://stevengogogo.github.io/DSA_IntersectingTriangles/files.html
[備註: main.c 是用 src/*.c 的檔案合併形成, 使用 quom 套件]

謝謝

邱紹庭敬上

Shao-Ting Chiu (Steven)
Master's student
Graduate Institute of Biomedical Electronics and Bioinformatics,
National Taiwan University
Email: [email protected]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.