问题
I want to know whether a list "A" has already been sorted by its values (in strictly ascending order). I thought about making a copy of the list (=> "B") and comparing it to "A" ordered by its values (using ASC
). At the current state, I have no idea how to create a copy of a list. Maybe there is another easier way to solve this problem (using Cypher).
回答1:
If you don't want to/can't use APOC you can sort the list by using
UNWIND list as item
WITH list,item ORDER BY item
It is a bit clunky because you need to carry forward all variables you need in all the WITH
statements.
Example:
WITH [1,2,3,4] as list
UNWIND list as item
WITH list,item ORDER BY item
WITH list,collect(item) as sorted
return list,sorted,list=sorted
returns
╒═════════╤═════════╤═════════════╕
│"list" │"sorted" │"list=sorted"│
╞═════════╪═════════╪═════════════╡
│[1,2,3,4]│[1,2,3,4]│true │
└─────────┴─────────┴─────────────┘
However
WITH [1,2,3,1] as list
UNWIND list as item
WITH list,item ORDER BY item
WITH list,collect(item) as sorted
return list,sorted,list=sorted
returns
╒═════════╤═════════╤═════════════╕
│"list" │"sorted" │"list=sorted"│
╞═════════╪═════════╪═════════════╡
│[1,2,3,1]│[1,1,2,3]│false │
└─────────┴─────────┴─────────────┘
Or you could use the reduce
function, this avoids sorting the list and iterates over the list only once:
WITH [1,2,3,4] as list
WITH reduce(result = true, i in range(0,size(list)-2) | result AND list[i] <= list[i+1]) AS sorted
return sorted
回答2:
You can test the original list
directly, which should be faster and use fewer resources than doing a new sort and/or creating a copy of the list.
For example, this will return true
:
WITH [1,2,3,4] AS list
RETURN ALL(i IN RANGE(1, SIZE(list)-1) WHERE list[i-1] <= list[i]) AS inOrder
And if list
was [4,1,2,3]
, then the above query would return false
.
回答3:
There are collection functions in the APOC Procedures that can help you out, especially apoc.coll.sort()
and apoc.coll.sortNodes()
depending on whether they're primitive values or nodes.
As for creating a list copy, you can use a list comprehension to perform a projection of the elements of a list like so:
WITH [1,2,3,4,5] as list1
WITH list1, [n in list1 | n] as list2
...
As far as comparisons go, equality comparisons between list do include ordering, so for the above, RETURN list1 = list2
would be true since they contain the same elements in the same order. But shuffling one of the lists like so: RETURN list1 = apoc.coll.shuffle(list2)
would return false since the order is different.
来源:https://stackoverflow.com/questions/57963219/how-to-identify-a-sorted-list