The theme of this time is aggregation by reduce
Ruby
For example, the character string 1251251252525
is converted to 25
-> ʻato make it easier to count characters. =>
1a1a1aaa The number of consecutive ʻa
s is (1, 1, 3), so add up the combinations for each.
bit.rb
s = gets.chomp
s.gsub!(/25/, 'a')
p = []
c = 0
0.upto(s.size - 1) do |i|
if s[i] == 'a'
c += 1
elsif c > 0
p.push(c)
c = 0
end
p.push(c) if i == s.size - 1 && c > 0
end
sum = 0
0.upto(p.size - 1) do |i|
sum += (1..p[i]).reduce{|a, b| a + b}
end
puts sum
reduce.rb
sum += (1..p[i]).reduce{|a, b| a + b}
sum += (1..p[i]).reduce(&:+)
sum += (1..p[i]).inject(:+)
sum += (1..p[i]).sum
The reduce part can be either inject or sum (ruby 2.4 or later).
** Addition **
Added reduce (&: +)
from the comments.
Perl
perl.pl
use v5.18; # strict say state
use List::Util qw/reduce/;
chomp (my $s = <STDIN>);
$s =~ s/25/a/g;
my $c = 0;
my @p;
for my $i (0..length($s)-1) {
if (substr($s, $i, 1) eq 'a') {
$c++;
} elsif ($c > 0) {
push @p, $c;
$c = 0;
}
if ($i == length($s)-1 && $c > 0) {
push @p, $c;
}
}
my $sum = 0;
for my $i (0..$#p) {
$sum += reduce {$a + $b} 1..$p[$i];
}
say $sum;
reduce.pl
use List::Util qw/reduce sum/;
$sum += reduce {$a + $b} 1..$p[$i];
$sum += sum(1..$p[$i]);
The reduce part can also be sum. Java
java.java
import java.util.*;
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
sc.close();
s = s.replace("25", "a");
List<Integer> p = new ArrayList<>();
int c = 0;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i + 1).equals("a")) {
c++;
} else if (c > 0) {
p.add(c);
c = 0;
}
if (i == s.length() - 1 && c > 0) {
p.add(c);
}
}
int sum = 0;
for (int i = 0; i < p.size(); i++) {
sum += IntStream.rangeClosed(1, p.get(i)).reduce(0, (a, b) -> a + b);
}
System.out.println(sum);
}
}
reduce.java
sum += IntStream.rangeClosed(1, p.get(i)).reduce(0, (a, b) -> a + b);
sum += IntStream.rangeClosed(1, p.get(i)).sum();
The reduce part can also be sum.
Ruby | Perl | Java | |
---|---|---|---|
Code length | 284 Byte | 411 Byte | 847 Byte |
Execution time | 34 ms | 28 ms | 284 ms |
memory | 4092 KB | 2816 KB | 33228 KB |
Referenced site
Recommended Posts