SQL大賽——5X5方格棋盤難題

來源:互聯網
上載者:User

“盛拓傳媒杯”SQL大賽第一期答題,


本期題目:5X5方格棋盤難題


在5X5的方格棋盤中(),每行、列、斜線(斜線不僅僅包括對角線)最多可以放兩個球,如何擺放才能放置最多的球,這樣的擺法總共有幾種?輸出所有的擺法。


要求:
用一句SQL實現。
輸出格式:
從方格棋盤第一行至第5行,每行從第一列到第5列依次輸出,0表示不放球,1表示放球。例如:1001000000000000000000000。一行輸出一個行號和一個解,按解所在的列字串順序從大到小排序。

資料庫平台:
適用Oracle、MS SQL Sever,版本(Oracle推薦10gr2(包含)以上版本、MS SQL Sever推薦2008版本)

我個人的答案如下:
--構造0、1選項
with test as
(select '1' bit from dual union select '0' from dual),
--構造每行排列組合
combostring as
(
select replace(sys_connect_by_path(bit,'#'),'#') combo
from test
where level=5
connect by level<=5
),
--把“10001”的字串,構造成可計算的數字
combo as
(select substr(combo,1,1) b1,substr(combo,2,1) b2,substr(combo,3,1) b3,substr(combo,4,1) b4,substr(combo,5,1) b5
 from combostring),
--根據題目進行邏輯求解
allcombo as
(
select c1.b1||c1.b2||c1.b3||c1.b4||c1.b5||' '||c2.b1||c2.b2||c2.b3||c2.b4||c2.b5||' '||
       c3.b1||c3.b2||c3.b3||c3.b4||c3.b5||' '||c4.b1||c4.b2||c4.b3||c4.b4||c4.b5||' '||c5.b1||c5.b2||c5.b3||c5.b4||c5.b5 combo,
 RANK() OVER(ORDER BY 
 c1.b1+c1.b2+c1.b3+c1.b4+c1.b5+ c2.b1+c2.b2+c2.b3+c2.b4+c2.b5+
c3.b1+c3.b2+c3.b3+c3.b4+c3.b5+ c4.b1+c4.b2+c4.b3+c4.b4+c4.b5+
c5.b1+c5.b2+c5.b3+c5.b4+c5.b5 DESC) RANK
  from combo c1,combo c2,combo c3,combo c4,combo c5
 where c1.b1+c2.b1+c3.b1+c4.b1+c5.b1<=2
   and c1.b2+c2.b2+c3.b2+c4.b2+c5.b2<=2
   and c1.b3+c2.b3+c3.b3+c4.b3+c5.b3<=2
   and c1.b4+c2.b4+c3.b4+c4.b4+c5.b4<=2
   and c1.b5+c2.b5+c3.b5+c4.b5+c5.b5<=2
   and c1.b1+c1.b2+c1.b3+c1.b4+c1.b5<=2
   and c2.b1+c2.b2+c2.b3+c2.b4+c2.b5<=2
   and c3.b1+c3.b2+c3.b3+c3.b4+c3.b5<=2
   and c4.b1+c4.b2+c4.b3+c4.b4+c4.b5<=2
   and c5.b1+c5.b2+c5.b3+c5.b4+c5.b5<=2
   and c1.b1+c2.b2+c3.b3+c4.b4+c5.b5<=2
   and c1.b5+c2.b4+c3.b3+c4.b2+c5.b1<=2
   and c1.b2+c2.b3+c3.b4+c4.b5<=2
   and c2.b1+c3.b2+c4.b3+c5.b4<=2
   and c1.b3+c2.b4+c3.b5<=2
   and c3.b1+c4.b2+c5.b3<=2
   and c1.b4+c2.b3+c3.b2+c4.b1<=2
   and c2.b5+c3.b4+c4.b3+c5.b2<=2
   and c1.b3+c2.b2+c3.b1<=2
   and c3.b5+c4.b4+c5.b3<=2
)
--列出符合要求的記錄
select
 combo
 from allcombo
WHERE RANK=1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.