简体   繁体   中英

Finding best combinations of consecutive and same numbers in a list starting with a group of at least 3

I need to create a code that finds consecutive and same numbers in a list but It needs to pair them so they can not be used again and It needs to find the best possible combination. Think of it as a game. You have a number which can be used in both a consecutive group and same number group but one of them makes it so that more numbers are used. The main goal is to use more numbers.

List: [1, 2, 2, 5, 6, 8, 3, 2, 10, 2]

When we try to check it. The usual code prioritizes the first one it finds not the one which uses most numbers. So it looks like:

[1, 2, 3] but not [2, 2, 2, 2]

I'm not asking you guys for the whole code but can someone help me find a way, library or a basic tactic to recreate what I explained above.

Since you want the absolute biggest possible group of numbers, we're going to have to try every possible group. By this, I mean if we have a list [1,1,2,2,2,3,3,5,6,7,8,9] , you're going to compare the groups [1,1], [2,2,2], [3,3], [1,2,3], [5], [6], [7], [8], [9], [5,6,7,8,9] . We will not be comparing these with [1], [1,2], [5,6], etc.

Approach

First, you should probably sort the list - this makes sense, as then all elements that are the same will become adjacent, and then we can easily find consecutive numbers.

Now, we'll find the groups of consecutive numbers and groups of the same numbers differently.

Same Numbers

For this case, all you do is write a loop to go through the list, and adding something to the current group if it is the same. Otherwise, make a new group.

Consecutive Numbers

For this case, you want to remove all duplicates in the list, probably by converting it to a set. Then, you can loop through it, checking if the current number is exactly 1 more than the previous number. If it isn't, start a new group.

If you only want the largest possible group, you don't need to store all groups, just the currently largest group, and compare that with each new group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM