根据特定条件将整数数组拆分为多个整数数组

时间:2018-10-26 04:53:32

标签: neo4j cypher

我正在尝试使用Neo4j Cypher查询根据特定条件将单个整数数组拆分为多个整数数组。以下是示例:

Input - [1,2,3,4,5,6,7,8,9]
Output - [1,2,3,4],[5,6],[7,8],[9] ==> Split the array as soon as the sum of elements is greater than 8

是否可以在Cypher查询中实现这一目标?

谢谢, 维沙尔

1 个答案:

答案 0 :(得分:2)

可以在Cypher中执行此操作,但是代码可能有点吓人:-)。

例如,此查询:

WITH [1,2,3,4,5,6,7,8,9] AS input
RETURN REDUCE(s = {sum:0, res:[]}, x IN input | CASE
  WHEN s.sum + x > 8 THEN CASE
    WHEN s.sum = 0 THEN {sum:0, res:s.res+[[x]]}
    ELSE {sum:0, res:s.res[..-1]+[s.res[-1]+x]} END
  ELSE CASE
    WHEN s.sum = 0 THEN {sum:s.sum+x, res:s.res+[[x]]}
    ELSE {sum:s.sum+x, res:s.res[..-1]+[s.res[-1]+[x]]} END
  END
).res AS result

产生以下结果:

╒═══════════════════════════╕
│"result"                   │
╞═══════════════════════════╡
│[[1,2,3,4],[5,6],[7,8],[9]]│
└───────────────────────────┘

注意:对于上述查询,最后一个子列表将始终包含输入列表的其余部分,并且其总和不一定超过8。如果最后一个子列表的总和也必须超过8,则此修改后的查询: / p>

WITH [1,2,3,4,5,6,7,8,8] AS input, 8 AS bound
WITH bound, REDUCE(s = {sum:0, res:[]}, x IN input | CASE
  WHEN s.sum + x > bound THEN CASE
    WHEN s.sum = 0 THEN {sum:0, res:s.res+[[x]]}
    ELSE {sum:0, res:s.res[..-1]+[s.res[-1]+x]} END
  ELSE CASE
    WHEN s.sum = 0 THEN {sum:s.sum+x, res:s.res+[[x]]}
    ELSE {sum:s.sum+x, res:s.res[..-1]+[s.res[-1]+[x]]} END
  END
).res AS res
RETURN CASE
  WHEN REDUCE(t=0, y IN res[-1] | t+y) > bound THEN res
  ELSE res[..-1] END AS result

产生以下结果:

╒═══════════════════════╕
│"result"               │
╞═══════════════════════╡
│[[1,2,3,4],[5,6],[7,8]]│
└───────────────────────┘