Comparing values in an array

Hi, I am looking to write a short code to compare values in an array.

For example, I want to have a list of values in a text file and then have each value compared to all of the other values to find out which ones are within 8 of each other.

Example: 8, 9, 20, 22, 40, 39. Answer would be that the group of 8 and 9 and 20 and 22 would be within 8 of each other.

I have no real world programming experience. I imagine this should be a simple task.

Thanks.

Yes, it should be a simple task. The best suggestion I could give would be to sort the values so that you don’t have to compare each to all of the others.

Thanks for the reply. Would you be able to provide a code example ?

Sorting the list so you can bail out early is an optimization that complicates the task significantly. For the first draft, I would leave that out.

Is this homework? A programming exercise? What have you tried?

Break the problem up into sub-problems.

Firstly, start with writing a function that reads values from a text file and returns a list of ints, not strings.

Then write a second function that takes a list of ints such as:

[8, 9, 20, 22, 40, 39]

and compares each value with every other value, collecting the pairs which are within 8 of each other.

Don’t be scared to write a function which almost works, and then incrementally improve it until it works.

Is that enough to get started?

If given the integers 1 to 32 in some order, would the grouping depend on the order? What makes a usable grouping for you as your numbers you provide would work with more than one grouping method, but my suggested numbers could give multiple answers specific to the grouping method chosen.