SQL大賽 5X5方格棋盤難題

2021-09-04 15:46:21 字數 2290 閱讀 8963

「盛拓傳媒杯」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

5X5矩陣調換!

將乙個5x5矩陣中最大的元素放在中心,4個角分別放4個最小的元素,寫一函式實現之!include int main printf n return 0 void change int p temp p 12 p 12 pmax pmax temp temp p p pmin pmin temp pm...

5x5矩陣調整大小位置!

將乙個5x5的矩陣中最大的元素放在中心,4個角分別放4個最小的元素 順序為從左到右,從上倒下依次從小到大存放 寫一函式實現它!include int main return 0 void change int p temp p 12 將 p 12 的值儲存到temp p 12 是該矩陣的中心元素 序...

求5x5階螺旋方陣

實驗題目 求5x5階螺旋方陣 實驗目的 掌握陣列演算法設計 實驗內容 以下是乙個5x5階螺旋方陣。編寫程式,輸出該形式的nxn n 10 階方陣 順時針方向旋進 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9 inc...