Skip to main content
3 of 4
Forgot to update the TIO..
Kevin Cruijssen
  • 136.3k
  • 14
  • 155
  • 394

#Java 10, 250 242 bytes

import java.util.*;n->{for(;;){int i=n+1,r[]=new int[i],d[]=new int[n];for(r[n<2?0:1]=n*n;i-->2;r[i]=(int)(Math.random()*n*n));var S=new HashSet();for(Arrays.sort(r),i=n;i-->0;)S.add(d[i]=r[i+1]-r[i]);if(!S.contains(0)&S.size()==n)return S;}} 

Watch out, Java coming through.. It's 'only' five times as long as the other four answers combined, so not too bad I guess.. rofl.
It does run n=1 through n=25 (combined) in less than 2 seconds though, so I'll probably post a modified version to the speed version of this challenge (that's currently still in the Sandbox) as well.

Try it online.

Explanation:

In pseudo-code we do the following:

  1. Generate an array of size n+1 containing: 0, n squared, and n-1 amount of random integers in the range [0, n squared)
  2. Sort this array
  3. Create a second array of size n containing the forward differences of pairs
    These first three steps will give us an array containing n random integers (in the range [0, n squared) that sum to n squared.
    4a) If not all random values are unique, or any of them is 0: try again from step 1
    4b) Else: return this differences array as result

As for the actual code:

import java.util.*; // Required import for HashSet and Arrays n->{ // Method with int parameter and Set return-type for(;;){ // Loop indefinitely int i=n+1, // Set `i` to `n+1` r[]=new int[i], // Create an array of size `n+1` d[]=new int[n]; // Create another array of size `n` for(r[n<2? // If `n` is 1: 0 // Set the first item in the first array to: : // Else: 1] // Set the second item in the first array to: =n*n; // `n` squared i-->2;) // Loop `i` in the range [`n`, 2]: r[i]= // Set the `i`'th value in the first array to: (int)(Math.random()*n*n); // A random value in the range [0, `n` squared) var S=new HashSet(); // Result-set, starting empty for(Arrays.sort(r), // Sort the first array i=n;i-->0;) // Loop `i` in the range (`n`, 0]: S.add( // Add to the Set, d[i]= // and set the `i`'th value in the second array to: r[i+1]-r[i]); // The `i+1`'th and `i`'th difference of the first array if(!S.contains(0) // If the Set does not contain a 0 &S.size()==n) // and its size is equal to `n`: return S;}} // Return this Set as the result // (Implicit else: continue the infinite loop) 
Kevin Cruijssen
  • 136.3k
  • 14
  • 155
  • 394