简体   繁体   中英

Permutations and then sorting in Java

I have a sorting problem.

Let's say I have 4 strings stored in an array, out of these I want to generate all combinations in pairs. And from these pairs sort them so that no 2 array positions get after each other in the greatest extend possible

Example:

String[] array = {"one", "two", "three", "four"};

// want to generate

one - two
one - three
one - four
two - three
two - four
three - four

// then sort

one - two
three - four
one - four
two - three      //two "three" after each other
one - three
two - four

(the one that gets 2 after each other in this case "three" has too be random when sorted)

I have no idea how to do this in Java. Tried nested for loops, some has told me recursive loops. And i don't want:

" Just copy paste this code and everything will work " i really really want to understand how to write something like this.

How should i approach this problem?

Here's your not Just copy paste this code and everything will work : -

Step 1: - Initialize an temp variable to 0 .

Step 2: - Iterate over your array from 0 to arr.length - temp

Step 3: - Print arr[i][temp] - arr[i][i + temp]

Step 4: - Increment temp by 1

Step 5: - Repeat step 2 if temp < arr.length - 1 , as (i + temp) cannot be more than arr.length .

So, for the given array it will print: -

String arr[] = {"one", "two", "three", "four"};

First iteration (Index pair with difference 1) : -

1. arr[0][0] - arr[0][1], then ("one" - "two")
2. arr[0][1] - arr[0][2],      ("two" - "three")
.. so on, 

and then move to next iteration. Increment temp by 1 : -

Second Iteration (Index pair with difference 2) : -

1. arr[0][0] - arr[0][2], then  ("one" - "three")
2. arr[0][1] - arr[0][3]        ("two" - "four")

.. so on.

Last Iteration (Index pair with difference arr.length - 1 ) : -

1. max = arr.length - 1;
2. arr[0][0] - arr[0][max]      ("one" - "four")

So, you can see that, there is nothing as such sorting involved here. If you try to do this with sorting, it will be hell lot of complex.

First come up with an algorithm. it doesn't have to have a particular language set up for it. It's just how you yourself would solve the problem.

Then translate that to the computer.

here's some psudocode to get you started.

public pair[] getPairs(string[] arr)
{

    pair[] retval;
    foreach(string s in arr)
    {
        string first = arr.first
        foreach(string s2 in arr.subArray(allbutfirst))
        {
             retval.Add(newPair(s, s2)
        }
    }
}

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