利用DuckDB SQL求解集合数学题

已知集合I={1,2,3,4,5,6},A={(s,t)|s ∈I,t∈I},若B包含于A,且对任意的(a,b)∈B,(x,y)∈B,均有(a-x)(b-y)<=0,则集合B中元素个数的最大值是几?

sql 复制代码
set variable n=6;
with recursive i as(select i from range(1,getvariable('n')+1)t(i)),
a as(select 1::bigint<<((i1.i-1)*getvariable('n')+i2.i)m, i1.i s, i2.i t from i i1,i i2),
b as(select 1 lv,m,[(a,b),(x,y)]st from(select a.m+a1.m m,a.s a,a.t b,a1.s x,a1.t y from a,a a1 where a.m<a1.m) where (a-x)*(b-y)<=0 
union all
select lv+1,a.m+b.m,st +[(a.s,a.t)] from b,a where a.m>b.m /*and a.m & b.m=0*/ and not exists(select 1 from range(1,lv+2) un(nb) where (a.s-b.st[nb][1])*(a.t-b.st[nb][2])>0))
from b where lv=(select max(lv) from b);

求出的最大元素个数是11,一共有252个不同的集合满足要求。本来是需要用对二进制位与运算为0来判断的,但是由于低位全1也比高位1低位0的二进制数小,所以有了a.m>b.m,注释掉与运算判断也不影响结果。

也可以不用range笛卡尔积,而用unnest函数来实现,不过慢一点

sql 复制代码
set variable n=6;
with recursive i as(select i from range(1,getvariable('n')+1)t(i)),
a as(select 1::bigint<<((i1.i-1)*getvariable('n')+i2.i)m, i1.i s, i2.i t from i i1,i i2),
b as(select 1 lv,m,[(a,b),(x,y)]st from(select a.m+a1.m m,a.s a,a.t b,a1.s x,a1.t y from a,a a1 where a.m<a1.m) where (a-x)*(b-y)<=0 
union all
select lv+1,a.m+b.m,st +[(a.s,a.t)] from b,a where a.m>b.m and not exists(select 1 from unnest(b.st) un(nb) where (a.s-nb[1])*(a.t-nb[2])>0))
from b where lv=(select max(lv) from b);

比起python程序,SQL还是简练一点。

相关推荐
起个名字费劲死了14 分钟前
VisionMaster集成深度学习算法(基础狗)
人工智能·深度学习·算法
adinnet202618 分钟前
多轮对话与上下文压缩:追问时模型怎么记住前面说的
数据库·microsoft
lengxuenong18 分钟前
枚举例题分析
c++·算法·青少年编程
Navigator_Z36 分钟前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
2601_9657422239 分钟前
短视频脚本创作方法分享:本地生活类账号的起步思路
大数据·人工智能·算法·ai·新媒体运营·生活
JosieBook41 分钟前
【数据库】MySQL 实战精通系列 · 第11篇:Redis 缓存与 MySQL 一致性实战
数据库·mysql·缓存
55873生态系统手记1 小时前
读完 55873 资产钱包的技术栈,我重新理解了 "合规钱包" 应该长什么样
算法·架构
旋生万物1 小时前
素数螺旋映射 $z_n=n^{1+i}$ 的角分布统计检验与零模型对比
大数据·前端·人工智能·算法·云原生·螺旋生成论·螺旋相位
HRTOS1 小时前
HRTOS Shell继续完善:优化printf缓冲区与字符串越界保护,国庆后随新版本更新
运维·单片机·嵌入式硬件·算法·51单片机
Leo.yuan1 小时前
2026企业级数据集成平台市场报告:国内外厂商格局与技术路线
数据库·oracle