Win a copy of Head First Android this week in the Android forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

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: 74359
334
  • 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
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic