docs icon indicating copy to clipboard operation
docs copied to clipboard

Duplicate Permutations Unaddressed

Open Scowluga opened this issue 2 years ago • 1 comments

Issue

In several locations across code.kx.com we deal with finding all permutations. e.x.

  • https://code.kx.com/q/learn/reading/strings/#its-more-fun-to-permute
  • https://code.kx.com/phrases/math/#permutations

In both of these cases, I find that duplicate permutations are just completely unaddressed. If we are dealing with a set, naturally there will be no problem with duplicates. But the phrasebook does not clearly specify that we are dealing with sets, and the reading room puzzle goes further to specify our input is a string (clearly not a set). Furthermore, even if we assume that we are dealing with permutations of a set, we should ensure that the official solutions we provide handle these in a standardized and expected manner.

Clearly this is not the case.

Solutions

We should either:

  1. Clarify that the solutions provided only deal with unique elements, and have undefined behaviour otherwise
  2. Standardize the solutions to remove all duplicates
  3. Standardize the solutions to enumerate all permutations, regardless of duplicates

We can also do any combination of these (e.x. solution (1) for phrasebook and (2) for the reading room problem).

My Contribution

I believe solution 2 is the best option. A list of permutations with duplicates seems redundant and unnecessary. You might as well distinct the output, in which case we should do this in the solutions provided. I don't know if applying distinct is necessarily the best solution here, in fact I have little experience with q, but it seems the most straightforward solution.

Phrasebook

  • Before: {(1 0#x){raze(1 rotate)scan'x,'y}/x}
  • After: {(1 0#x){distinct raze(1 rotate)scan'x,'y}/x}

Reading room cats cradle solution 1

This solution is actually incomplete and incorrect which is a separate issue of its own that caused this entire investigation. I have done the best I can to fix the solution and will provide it as a PR after discussion of this ticket.

  • Before: {x {flip[y]where x=sum y}[s;] s vs til"j"$s xexp s:count x}, incorrect
  • After: {distinct x @ b where all each (til c) in/:b:flip c vs til "j"$c xexp c:count x}

Reading room cats cradle solution 2

  • Before: {(1 0#x) {raze({raze reverse 0 1 _ x}\)each x,'y}/ x}, strongly based off the phrasebook solution
  • After: {(1 0#x) {distinct raze({raze reverse 0 1 _ x}\)each x,'y}/ x}

Scowluga avatar Dec 31 '21 04:12 Scowluga

Good work. I look forward to the PR.

StephenTaylor-Kx avatar Jan 06 '22 13:01 StephenTaylor-Kx