2017年5月18日 星期四

ITSA 52 - [Problem 1] 撲克牌大小 - 參考答案

Difficulty: Eazy
Ref: ITSA 52 - [Problem 1] 撲克牌大小
/*******************************************************/
/* [Problem 1] 撲克牌大小                               */
/* Author: awei0905  [at]  awei0905.blogspot.tw        */
/* Version: 2017/05/18                                 */
/*******************************************************/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 36*3 + 16*4

int main() {
 int n;
 scanf("%d ", &n);
 while (n--) {
  char buf[MAX], cards[52][4];
  fgets(buf, MAX, stdin);
  buf[strlen(buf) - 1] = '\0';

  int count = 0;
  char *pch = strtok(buf, " ");
  while (pch != NULL) {
   strcpy(cards[count++], pch);
   pch = strtok(NULL, " ");
  }

  for (int i = 0; i < count - 1; i++)
   for (int j = i + 1; j < count; j++)
    if ((cards[i][0] < cards[j][0]) || (cards[i][0] == cards[j][0]) && (atoi(&cards[i][1]) < atoi(&cards[j][1]))) {
     char temp[4];
     strcpy(temp, cards[i]);
     strcpy(cards[i], cards[j]);
     strcpy(cards[j], temp);
    }

  printf("%s", cards[0]);
  for (int i = 1; i < count; i++)
   printf(" %s", cards[i]);
  printf("\n");
 }
}
Debug: I/O
整行輸入後字串切割,使用泡沫排序法排序。
花色大小剛好對應到花色字元 ASCII 的大小,排序變得更簡單。
排序規則:如果花色比較大或花色相同但數字較大。
4
H5 D4 S2 C13
D8 S3 D10 C12 H7
H6 S3
C5 D11 S1
S2 H5 D4 C13
S3 H7 D10 D8 C12
S3 H6
S1 D11 C5

3 則留言:

  1. 不好意思 想請問cards[MAX / 3 + 1][4] = { 0 };和 一開始定義MAX 1024的意思 謝謝

    回覆刪除
    回覆
    1. MAX 1024 為自定義最大輸入文字長度,題目沒有描述,所以 1024 是隨便給的,最理想的大小是 36*3 + 16*4,為1c1d+1c2d的總長度。
      cards[MAX / 3 + 1][4] = { 0 }; 應更正為 cards[52][4]; 為最理想,當初寫只是想要把 cards 陣列大小弄小,但給的值的確詭異,我也不清楚。

      刪除
    2. 瞭解了 謝謝大大!!因為我在想明明其他方法也可以,滿好奇你的方法的!!😀

      刪除