3

If I do e.g.

Flatten[Outer[List, Range[3], Range[3]], 1]

I get

{{1, 1}, {1, 2}, {1, 3}, 
 {2, 1}, {2, 2}, {2, 3}, 
 {3, 1}, {3, 2}, {3, 3}}

but I want to get distinct pairs, i.e.

{{1, 1}, {1, 2}, {1, 3}, 
 {2, 2}, {2, 3}, 
 {3, 3}}

How can I do this?

bmf
  • 15,157
  • 2
  • 26
  • 63
user236343
  • 429
  • 2
  • 5
  • 2
    https://mathematica.stackexchange.com/questions/265431/is-there-a-function-to-generate-subsets-allowing-duplicates/265435#265435 – cvgmt Apr 16 '22 at 23:36

5 Answers5

4

Edit: many thanks to @JasonB. for the comment. It has been incorporated below

You first command can be written more simply as:

Tuples[Range@3, 2]

You can check their equivalence either by using SameQ

SameQ[Tuples[Range@3, 2], Flatten[Outer[List, Range[3], Range[3]], 1]]

or the undocumented function

LinearAlgebra`Private`ZeroArrayQ[
 Tuples[Range@3, 2] - Flatten[Outer[List, Range[3], Range[3]], 1]]

both of which yield

true

To delete the values you don't want to see

Tuples[Range@3, 2] // DeleteDuplicatesBy[Sort]

And we check against the result you quoted in two ways. One is

SameQ[(Tuples[Range@3, 2] // 
    DeleteDuplicatesBy[Sort]) - {{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 
    3}, {3, 3}}]

and the other

LinearAlgebra`Private`ZeroArrayQ[(Tuples[Range@3, 2] // 
    DeleteDuplicatesBy[Sort]) - {{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 
    3}, {3, 3}}]

both of which yield

true

bmf
  • 15,157
  • 2
  • 26
  • 63
  • The answer is correct - you could show that without using some undocumented private context function. For instance you could use SameQ, as in SameQ[Tuples[Range@3, 2], Flatten[Outer[List, Range[3], Range[3]], 1]] – Jason B. Apr 17 '22 at 11:31
  • 1
    @JasonB. point taken and the answer is updated. Many thanks :) – bmf Apr 17 '22 at 15:02
3
n = 3;
t = Tuples[Range[1, n], {2}] /. {a_, b_} /; a > b -> Nothing

{{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 3}}

Syed
  • 52,495
  • 4
  • 30
  • 85
3

Here are some other ways:

Union[Sort /@ Tuples[Range[3], 2]]

DeleteDuplicates[Sort /@ Tuples[Range[3], 2]]

Union[Tuples[Range[3], 2], SameTest -> ({#1[[1]], #1[[2]]} == {#2[[2]], #2[[1]]} &)]

DeleteDuplicates[ Tuples[Range[3], 2], ({#1[[1]], #1[[2]]} == {#2[[2]], #2[[1]]} &)]

All yield:

{{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 3}}

ubpdqn
  • 60,617
  • 3
  • 59
  • 148
3
Join @@ Table[{i, j}, {i, 3}, {j, i, 3}] 
{{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 3}}
Distribute[{Range@3, Range@3}, List, List, DeleteDuplicatesBy[Sort]@*List] 
{{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 3}}
kglr
  • 394,356
  • 18
  • 477
  • 896
3

The Subsets command is for this:

Subsets[Range[3], {1, 2}] /. {{x_} :> {x, x}}
Alan
  • 13,686
  • 19
  • 38