Skip to content

Commit

Permalink
- Added the Array.sort_by{} method, which sorts an array by a specifi…
Browse files Browse the repository at this point in the history
…c value.

Example:
	[4,3,1,2].sort_by { _ };	    # same as .sort();
	[4,3,1,2].sort_by {|n| -n };        # reverse sorting
	%w(foo fo f).sort_by { .len } 	    # sort array by length

- Added two new Sidef scripts.
  • Loading branch information
trizen committed Oct 25, 2015
1 parent 7bdfafe commit 0687ff3
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 0 deletions.
2 changes: 2 additions & 0 deletions MANIFEST
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,8 @@ scripts/RosettaCode/inheritance_single.sf
scripts/RosettaCode/knapsack_problem_continuous.sf
scripts/RosettaCode/largest_int_from_concatenated_ints.sf
scripts/RosettaCode/last_sunday_of_each_month.sf
scripts/RosettaCode/left_factorials.sf
scripts/RosettaCode/left_factorials_1.sf
scripts/RosettaCode/levenshtein_distance.sf
scripts/RosettaCode/levenshtein_distance_1.sf
scripts/RosettaCode/levenshtein_distance_2.sf
Expand Down
5 changes: 5 additions & 0 deletions lib/Sidef/Types/Array/Array.pm
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,11 @@ package Sidef::Types::Array::Array {
$self->new(sort { $a cmp $b } @{$self});
}
sub sort_by {
my ($self, $code) = @_;
$self->new(map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, $code->run($_)] } @{$self});
}
sub cmp {
my ($self, $arg) = @_;
Expand Down
8 changes: 8 additions & 0 deletions lib/Sidef/Types/Array/Array.pod
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,14 @@ Return the

=cut

=head2 sort_by

Array.sort_by() -> I<Obj>

Return the

=cut

=head2 splice

Array.splice() -> I<Obj>
Expand Down
15 changes: 15 additions & 0 deletions scripts/RosettaCode/left_factorials.sf
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Left_factorials#Sidef
#

func left_fact(k) {
range(0, k-1).map { _! }.sum \\ 0;
}

[range(0, 10), range(20, 50).by(10)].each { |r|
r.each { |i|
printf("!%d = %s\n", i, left_fact(i));
}
}
30 changes: 30 additions & 0 deletions scripts/RosettaCode/left_factorials_1.sf
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Left_factorials#Sidef
#

func left_fact(n) {
static cached = 0;
static factorial = 1;
static leftfact = 0;

if (n < cached) {
cached = 0;
factorial = 1;
leftfact = 0;
}

while (n > cached) {
leftfact += factorial;
factorial *= ++cached;
}

leftfact;
}

[range(0, 10), range(20, 50).by(10)].each { |r|
r.each { |i|
printf("!%d = %s\n", i, left_fact(i));
}
}

0 comments on commit 0687ff3

Please sign in to comment.