in reply to Re^2: Next permutation
in thread Next permutation

How is what you want to do different than a Bubble Sort where you stop on the first swap? A bubble sort moves the highest element up by one position for each pass (here a digit). What do you want to happen if the highest number is already first in the order?

Update:
Probably a better way to get the index of max value...But is this what you want?
Code should run fairly quickly albeit a bit wordy for Perl.

#!/usr/bin/perl use strict; use warnings; my @array = split '', "117"; print @array, "\n"; print @array,"\n" while rot_max_left(\@array); @array = split '', "1234"; print "\n",@array,"\n"; print @array,"\n" while rot_max_left(\@array); sub rot_max_left { my $array_ref = shift; my $maxi=0; return 0 unless ($maxi = get_index_of_max($array_ref)); ($array_ref->[$maxi-1],$array_ref->[$maxi]) = ($array_ref->[$maxi] +,$array_ref->[$maxi-1]); return $maxi; } sub get_index_of_max { my $array_ref = shift; my $maxi = 0; foreach (my $i=1;$i<@$array_ref;$i++) { $maxi = $i if ($array_ref->[$i] > $array_ref->[$maxi]) } return $maxi; } __END__ 117 171 711 1234 1243 1423 4123

Replies are listed 'Best First'.
Re^4: Next permutation
by aartist (Pilgrim) on Feb 25, 2019 at 20:41 UTC
    If you hit the highest digit as the first digit, then:
    1. Sorting of remaining digits.
    2. if you cannot sort any further, (ie.. it is already in reverse order) than sort from the beginning position. ( to return to the original number. 321 -> 123)
      If you want to learn Perl, I would like to see your attempt at this extra behaviour. Then I and the group can help you with that. The general approach here is "post a question", "get some info", "learn and experiment", "post another question based upon what you've learned and your experimentation".

      I've given you a start although I probably should have named rot_max_left() as shift_max_left(). I encourage you to give this a go yourself and post your code.