Rectangle into Squares

The drawing below gives an idea of how to cut a given "true" rectangle into squares ("true" rectangle meaning that the two dimensions are different).

alternative text

Can you translate this drawing into an algorithm?

You will be given two dimensions

  1. a positive integer length (parameter named lng)
  2. a positive integer width (parameter named wdth)

You will return an array or a string (depending on the language; Shell bash, PowerShell and Fortran return a string) with the size of each of the squares.

  sqInRect(5, 3) should return [3, 2, 1, 1]
  sqInRect(3, 5) should return [3, 2, 1, 1]
  or (Haskell)
  squaresInRect  5  3 `shouldBe` Just [3,2,1,1]
  squaresInRect  3  5 `shouldBe` Just [3,2,1,1]
  or (Fsharp)
  squaresInRect  5  3 should return Some [3,2,1,1]
  squaresInRect  3  5 should return Some [3,2,1,1]
  or (Swift)
  squaresInRect  5  3 should return [3,2,1,1] as optional
  squaresInRect  3  5 should return [3,2,1,1] as optional
  or (Cpp)
  sqInRect(5, 3) should return {3, 2, 1, 1}
  sqInRect(3, 5) should return {3, 2, 1, 1}
  (C)
  C returns a structure, see the "Solution" and "Examples" tabs.
  Your result and the reference test solution are compared by strings.
typedef struct Data Data;
struct Data {
     int *array;
     int sz;
};

Data* sqInRect(int lng, int wdth) {
  
  int tmplng = lng;
  int tmpwdth = wdth;
  Data* pData = (Data*)malloc(sizeof(Data));
  int i;
  int size = 0;
  int * pIntarr;
  
  while(tmplng != tmpwdth)
  {
    if(tmplng > tmpwdth)
    {
      tmplng = tmplng - tmpwdth;
    }
    else
    {
      tmpwdth = tmpwdth - tmplng;
    }
    size ++;
  }
  
  if(size != 0)
  { 
    size ++;
    tmplng = lng;
    tmpwdth = wdth;
    pIntarr = (int*)malloc(sizeof(int) * size);
    for(i=0; i<size-1; i++)
    {
      if(tmplng > tmpwdth)
      {
        tmplng = tmplng - tmpwdth;
        pIntarr[i] = tmpwdth;
      }
      else
      {
        tmpwdth = tmpwdth - tmplng;
        pIntarr[i] = tmplng;
      }
    }
    pIntarr[i] = pIntarr[i-1];
  }
  
  pData->sz = size;
  pData->array = pIntarr;
  return pData;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值