iT邦幫忙

0

C語言 陣列切割並排序

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
小魚
iT邦大師 1 級 ‧ 2021-06-13 08:49:35

我最討厭文謅謅的東西,
(雖然我很喜歡背古文)
所以我都會跟客戶討論"需求"到底是甚麼,
直接跳過繁文縟節...

他的意思應該是說,
完成排序的號碼有幾個,
前三個都完成排序了,
所以就直接回傳陣列的長度,
第四個因為是反過來的,
所以只能抓到最後1個,
第五個陣列有 1,3 是排序完成的,
所以有兩個,
其實說白了判斷方式就是 array[i+1] >= array[i]
剩下的就是你程式怎麼寫的問題,
這個就要先請你自己寫了.

ywdeng iT邦新手 5 級 ‧ 2021-06-13 10:03:33 檢舉

https://ithelp.ithome.com.tw/upload/images/20210613/201144378wQIXH5nYt.png

/**
 * dscseqcnt.c
 * @ywdeng20210613
 * To compile, execute:
 *      gcc -g -O2 dscseqcnt.c -o dscseqcnt.exe
 * To run, execute:
 *      dscseqcnt.exe < input.txt
 * Example input.txt file content:
[1, 1, 1, 1, 1, 1, 1],
[1, 3, 5, 7, 9],
[1, 2, 3],
[5, 4, 3, 2, 1],
[2, 1, 3, 2]
 * Example output:
[7,5,3,1,2]
 **/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

// length limit of an input line
#define LINE_LEN 4096
char line[LINE_LEN];    // buffer for an input line
int sequence[LINE_LEN]; // current input sequence
int seq_len = 0;        // length of current input sequence

int isLB(char ch) {
    return (ch == '[');
}

int isRB(char ch) {
    return (ch == ']');
}

/**
 * Read sequence from an input line
 * ex. [1, 1, 1, 1, 1, 1, 1]
 **/ 
int read_seq(char* line) {
    seq_len = 0;
    int i = 0;    
    // seek for start of sequence 
    while (line[i] && !isLB(line[i])) i++;
    if (!line[i]) return -1;    // ERROR: no start-of-sequence
    i++;
    while (line[i] && !isRB(line[i])) {
        // seek for digits 0 1 2 3 4 5 6 7 8 9
        while (line[i] && !(isdigit(line[i]) || isRB(line[i]))) i++;
        if (!line[i]) return -2;    // ERROR: no end-of-sequence
        if (isdigit(line[i])) {
            sequence[seq_len] = atoi(&line[i]);
            seq_len++;
            while (line[i] && isdigit(line[i]) && !isRB(line[i])) i++;
        }
        if (isRB(line[i])) return seq_len;
        i++;
    }
    if (!line[i]) return -2;    // ERROR: no end-of-sequence
    return seq_len;
}

/**
 * Count the occurance of descending-order sequences
 **/
int count_dsc_seq(int arr[], int arr_len) {
    if (arr_len < 1) return 0;
    int i, cnt = 1;
    for (i = 0; i < (arr_len-1); i++) {
        if (arr[i] > arr[i+1]) continue;
        else cnt++;
    }
    return cnt;
}

int main(int argc, char* argv[]) {
    putchar('[');
    int cnt = 0, seq = 0;
    while (fgets(line, LINE_LEN, stdin)) {
        cnt = read_seq(line);
        if (cnt < 0) {
            perror("ERROR: invalid input!");
            return -1;
        }
        cnt = count_dsc_seq(sequence, seq_len);
        if (seq) putchar(',');
        printf("%d", cnt);
        seq++;
        memset(line, 0, LINE_LEN);
    }
    printf("]\n");
    return 0;
}
小魚 iT邦大師 1 級 ‧ 2021-06-13 11:06:25 檢舉

寫好了嗎?
那應該就可以了吧.

我要發表回答

立即登入回答