Please help with a programming assignment?

tl/dr: I need help with the "generate()" method described below... a nudge in the correct direction or perhaps, a good reference/tutorial/something that helps me understand dynamic programming better.

So I'm taking this Coursera course (Computer Science: Programming with a Purpose) not for certificate/credit -- just for the info -- and the programming assignments have been a lot harder than a 100-level, "intro to CS for non-CS folks" (that appears to be how its "marketed") should be (IMO). I'm an experienced programmer (or at least I thought I was) and went thru a CS program where I graduated with a bachelor's back in 1995.

Anyhow, I've been struggling with stuff that uses dynamic programming and the like (I don't remember ever "getting" dynamic programming back in the day) and I'm down to one program in the programming assignments in order to just close out the whole class (I HATE leaving things undone.)

Anyhow, this is the assignment specification: (spoilered 'cuz its kinda big and I don't know how Coursera or Princeton feel about my "publishing" this question)

Inversions. Suppose that a music site wants to compare your song preferences to those of a friend. One approach is to have you and your friend each rank a set of n songs and count the number of pairs of songs (i, j) for which you prefer i to j but your friend prefers j to i. When the count is low, the preferences are similar.

More generally, given an array of integers, a pair of elements a(i) and a(j) are inverted if i < j and a(i) > a(j). For example, the array a() has 1 inversion and the array b() has 4 inversions.

inversions.png
(wow, that's big)

Write a program Inversions.java that implements the following API:
Code:
public class Inversions {

  // return the number of inversion in the permutation a()
  public static long count(int[] a) {
  }

  // return a permutation of length n with exactly k inversions
  public static int() generate(int n, int k) {
  }

  // takes an integer n and a long k as command-line arguments,
  // and prints a permutation of length n with exactly k inversions
  public static void main(String[] args) {
  }
}

Here is some more information about the required behavior:
  • Permutations. A permutation of length n is an integer array of length n that contains each of the n integers 0, 1, ..., n–1 exactly once.
  • Output format. The main() method should print the permutation of length n to standard output as a sequence of n integers, separated by whitespace, all on one line.
  • Performance. The count() method should take time proportional to n2 in the worst case. The generate() method should take time proportional to n in the worst case.
  • Corner cases. You may assume that the arguments to generate() satisfy n ≥ 0 and 0 ≤ k ≤ 1/2 * n * (n−1); this guarantees the existence of a permutation of length n with exactly k inversions.

Here are a few sample executions:

Code:
~/Desktop/performance> java-introcs Inversions 10 0
0 1 2 3 4 5 6 7 8 9

~/Desktop/performance> java-introcs Inversions 10 1
0 1 2 3 4 5 6 7 9 8

~/Desktop/performance> java-introcs Inversions 10 45
9 8 7 6 5 4 3 2 1 0

~/Desktop/performance> java-introcs Inversions 10 20
9 8 0 1 2 3 7 4 5 6

I've got everything but generate() working. (I've figured out a really bad way (quad-nested loops) to do the counting and I'm working on making it better.) My first attempt was simply just randomly swapping things k times, but that didn't solve the problem (obviously), so when I went to figure out why, I saw that my implementation was completely wrong and then I realized I didn't even know how to approach solving that part of the problem since it would grow so fast. I did realize that I could generate ALL the permutations of n things then use count() to find one that met the spec, but it would be super, duper slow.

I did write some code to futz around with swapping various things so I could "see" how they affected the outcome. In doing so, I found that the numbers coming out of "perfect swapping" (i.e., reversing things) seemed to follow numbers in Pascal's triangle. But that gave me no further insight other than to realize that perhaps the solution might need some recursion.

If anyone could give me a nudge in the right direction, I'd appreciate it.
 

rain shadow

Ars Tribunus Angusticlavius
6,679
Subscriptor++
Following the example a bit, start with the numbers in sequence 0, 1, 2, 3, 4, 5, 6.

Then chip away at the desired count by repeatedly moving the largest, rightmost number to the left (but not in front of larger numbers) or the amount necessary to satisfy the required total. Stop when you have the desired number of inversions.

Say for example you want 13 inversions.

Move the 6 to the front, so you have 6, 0, 1, 2, 3, 4, 5
That gives you 6 inversions.

Then, move the 5 to just after the six, so you have 6, 5, 0, 1, 2, 3, 4
Now you have 6 + 5 inversions, for 11.

You need two more, so move the 4 but instead of putting it it after the 5, only move it two positions over and you get 6, 5, 0, 1, 4, 2, 3.

If I didn't miss something obvious, that's 13 inversions.

I tend to do things like this in place, just shuffling things around with bulk copies.

You could also recurse and create a new array at each level, taking heads and tails of the previous level's array and splicing them together around the move and returning the "final" array back up the stack. I don't think java is sophisticated enough to compile that into dynamic operations, but it is more in the spirit of it.

The next level is to just write out the array left to right knowing what the pattern is, without having to shuffle anything around.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
Following the example a bit, start with the numbers in sequence 0, 1, 2, 3, 4, 5, 6.

Then chip away at the desired count by repeatedly moving the largest, rightmost number to the left (but not in front of larger numbers) or the amount necessary to satisfy the required total. Stop when you have the desired number of inversions.

Say for example you want 13 inversions.

Move the 6 to the front, so you have 6, 0, 1, 2, 3, 4, 5
That gives you 6 inversions.

Then, move the 5 to just after the six, so you have 6, 5, 0, 1, 2, 3, 4
Now you have 6 + 5 inversions, for 11.

You need two more, so move the 4 but instead of putting it it after the 5, only move it two positions over and you get 6, 5, 0, 1, 4, 2, 3.

If I didn't miss something obvious, that's 13 inversions.

I tend to do things like this in place, just shuffling things around with bulk copies.

You could also recurse and create a new array at each level, taking heads and tails of the previous level's array and splicing them together around the move and returning the "final" array back up the stack. I don't think java is sophisticated enough to compile that into dynamic operations, but it is more in the spirit of it.

The next level is to just write out the array left to right knowing what the pattern is, without having to shuffle anything around.

That doesn't meet the worst case performance requirements.
 

rain shadow

Ars Tribunus Angusticlavius
6,679
Subscriptor++
Here's a generate() that doesn't do any O(n^2) shuffling, it just mindlessly prints out the values in the array from left to right in linear time.
C not java, sorry.

Code:
void generate(int n, int k)
{
  int need = k;
  int upper_value = n-1;
  int lower_value = 0;
  int i;

  for (i = 0; i < n; i++)
  {
    if (need >= upper_value - lower_value)
    {
      printf("%d ", upper_value);
      need = need - upper_value;
      upper_value--;
    }
    else
    {
      printf("%d ", lower_value);
      lower_value++;
    }
  }

  if (need > 0)
    printf("Unable to make %d inversions in array of length %d\n", k, n);

  printf("\n");
}
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
Here's a generate() that doesn't do any O(n^2) shuffling, it just mindlessly prints out the values in the array from left to right in linear time.
C not java, sorry.

Code:
void generate(int n, int k)
{
  int need = k;
  int upper_value = n-1;
  int lower_value = 0;
  int i;

  for (i = 0; i < n; i++)
  {
    if (need >= upper_value - lower_value)
    {
      printf("%d ", upper_value);
      need = need - upper_value;
      upper_value--;
    }
    else
    {
      printf("%d ", lower_value);
      lower_value++;
    }
  }

  if (need > 0)
    printf("Unable to make %d inversions in array of length %d\n", k, n);

  printf("\n");
}

As I said, build it one element at a time noting how many inversions that element introduces.
 

rain shadow

Ars Tribunus Angusticlavius
6,679
Subscriptor++
Here's a generate() that doesn't do any O(n^2) shuffling, it just mindlessly prints out the values in the array from left to right in linear time.
As I said, build it one element at a time noting how many inversions that element introduces.
Let us agree to disdisagree.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
Here's a generate() that doesn't do any O(n^2) shuffling, it just mindlessly prints out the values in the array from left to right in linear time.
As I said, build it one element at a time noting how many inversions that element introduces.
Let us agree to disdisagree.

You are printing the values out one at a time to satisfy the constraints by noting how many inversions putting the highest value out will introduce. Hell, with a little jiggering, you could even use a similar approach to generate permutations with an appropriate number of random inversions.