【问题标题】:Sorting different sized cards in an array对数组中不同大小的卡片进行排序
【发布时间】:2018-03-22 01:37:40
【问题描述】:

我已经尝试解决这个问题很长一段时间了,但我似乎被卡住了,没有得到所需的结果。

假设我想在我的手中堆叠一些牌。 我必须使用结构数组,因为每张卡也有一个名称。

struct Creature {
std::string name;
int x, y;
};

在我的 main.cpp 中,我创建了变量

Creature c[MAX_CARDS]

我只能持有 100 张牌,所以 MAX_CARDS 为 100。 问题是,只有 10 张独特的卡片。每个人都有自己的名字和自己的大小。尺寸如 2x6、3x1、4x2、1x10、8x4、1x5、6x2 等...

规则是没有卡大于它下面的卡。以“最小”到最大的方式排序。例如,如果 card1 是 4x8 而 card2 是 2x9,那么这些卡是不可堆叠的,因此它们将被排序到数组的末尾,因为下一张抽出的卡可能是一张可以满足其中一张卡的卡,并且然后被洗牌到数组中的正确位置,与 x 和 y 大小相同的卡片相同,因此重复到后面。但是,如果 card1 是 1x2 而 card2 是 1x3,这可以工作并且是可堆叠的。

我希望能解释一下可堆叠卡片的逻辑,因为那是我认为我遇到问题的部分。

template <typename T>
void sortArray(T c[], const int size) {
  int positionOfMin, x1, x2, y1, y2;
  T minValue, temp;
  bool swap = false;
  for (int i = 0; i < size; i++) {
    minValue = c[i];
    positionOfMin = i;

    for (int j = i+1; j < size; j++) {
      x1 = minValue.x;
      y1 = minValue.y;
      x2 = c[j].x;
      y2 = c[j].y;

      if(x1 < x2 && y1 < y2) {
        swap = false;   
      }else if (((x1 > x2 && x1 > y2) || (y2 > x2 && y1 > y2))  )  {
        swap = true;
      }else if (x1 == x2 && y1 == y2){
        swap = false;
      }else{
        swap = true;
      }
      if (swap == true) {
         minValue = c[j];
         positionOfMin = j;
      }

    }

// Swap the values to the new or same minimum value
  temp = c[i];
  c[i] = minValue;
  c[positionOfMin] = temp;
  }
}

任何想法或帮助将不胜感激,我得到的结果根本不正确。

【问题讨论】:

  • 在我的主程序中,我将另一张卡片添加到“大小”,然后在循环中再次调用该函数,直到我有至少 4 张可堆叠卡片或 7 张独特卡片。
  • 按(递减){x, y} 排序,一旦遇到不可堆叠的卡片,它们就会创建不同的堆叠。

标签: c++ arrays struct


【解决方案1】:

按(递减){x, y} 排序,一旦遇到不可堆叠的卡片,它们就会创建不同的堆叠。

std::vector<std::vector<Card>> reorganize(std::vector<Card> cards)
{
    std::sort(cards.begin(), cards.end(),
              [](const Card& lhs, const Card& rhs){
                  return std::tie(rhs.width, rhs.height) < std::tie(lhs.width, lhs.height);
              });

    std::vector<std::vector<Card>> res;

    for (const auto& card : cards) {
        auto it = std::find_if(res.begin(), res.end(),
                               [&](const auto& stack) {
                                    return card.height <= stack.back().height;
                               });

        if (it == res.end()) {
            res.push_back({card});
        } else {
            (*it).push_back(card);
        }
    }
    return res;
}

Demo

【讨论】:

  • 谢谢,这很有帮助!
猜你喜欢
  • 2018-10-01
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
  • 2018-06-19
  • 2016-01-06
  • 1970-01-01
  • 2017-01-03
  • 2023-02-24
相关资源
最近更新 更多