Hi MacScripters,
I’m working on a project which requires me to partition a list using a list. Here’s an example:
Example input:
list to partition by = {4, 1, 9, 6, 2, 2}
list to partition = {1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 1}
the sum of each list will always be equal
Example output:
output list = {{1,1,1,1}, {1}, {2,2,2,3}, {3,3}, {1,1}, {1,1}}
I created a solution which works, but I’m very new to algorithms, and was curious if there’s a better solution?
Here’s my current function:
set partition1 to {4, 1, 9, 6, 2, 2}
set input1 to {1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 1}
set output1 to {}
partitionList(input1, output1, partition1)
on partitionList(inputList, outputList, partitionBy)
set partitionStartIndex to 1
set inputStartIndex to 1
set inputEndIndex to 1
repeat (count of partitionBy) times
set currentPartitionItem to item partitionStartIndex of partitionBy
set currentInputItem to item inputStartIndex of inputList
if currentInputItem < currentPartitionItem then
set sum to currentInputItem
repeat while sum < currentPartitionItem
set nextInputItem to item (inputEndIndex + 1) of inputList
set sum to sum + nextInputItem
set inputEndIndex to inputEndIndex + 1
end repeat
copy (items inputStartIndex thru inputEndIndex of inputList as list) to end of outputList
else
copy (currentInputItem as list) to end of outputList
end if
set partitionStartIndex to partitionStartIndex + 1
set inputEndIndex to inputEndIndex + 1
set inputStartIndex to inputEndIndex
end repeat
return outputList
end partitionList
Any thoughts regarding efficiency or redundancy that I probably overlooked would be welcome