• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question about Permutation

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

I am new to JAVA.
I wanna write a Permutation code.
For example, I have [1,2,3]. I want to print 123,132,213,231,312,321

Below is my code:


However, it will print 123,132,312,321,123,132.

Actually, I use the algorithm from "Data Structures with C++ Using STL" by WIlliam Ford and WIlliam Topp. In this book, there is a section "Listing Permutations" described this algorithm.

So, why is it wrong?

Thanks.

[Update: Added code tags (Read UseCodeTags) ]
 
Greenhorn
Posts: 14
Eclipse IDE VI Editor BSD
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You'll have to pass create a copy of the original passed values otherwise you perform the same permutations on the permutated values
which produces the duplicates in your result.

simply create a copy at the passed values as the beginning of your permute method, like


And the result will be:123,132,213,231,312,321
as expected.


 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
Don't MAKE me come back there with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic