How to resolve the algorithm Entropy/Narcissist step by step in the Perl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Entropy/Narcissist step by step in the Perl programming language
Table of Contents
Problem Statement
Write a computer program that computes and shows its own entropy.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Entropy/Narcissist step by step in the Perl programming language
Source code in the perl programming language
#!/usr/bin/perl
use strict ;
use warnings ;
use feature 'say' ;
sub log2 {
my $number = shift ;
return log( $number ) / log( 2 ) ;
}
open my $fh , "<" , $ARGV[ 0 ] or die "Can't open $ARGV[ 0 ]$!\n" ;
my %frequencies ;
my $totallength = 0 ;
while ( my $line = <$fh> ) {
chomp $line ;
next if $line =~ /^$/ ;
map { $frequencies{ $_ }++ } split( // , $line ) ;
$totallength += length ( $line ) ;
}
close $fh ;
my $infocontent = 0 ;
for my $letter ( keys %frequencies ) {
my $content = $frequencies{ $letter } / $totallength ;
$infocontent += $content * log2( $content ) ;
}
$infocontent *= -1 ;
say "The information content of the source file is $infocontent !" ;
You may also check:How to resolve the algorithm Loops/Foreach step by step in the WDTE programming language
You may also check:How to resolve the algorithm Synchronous concurrency step by step in the D programming language
You may also check:How to resolve the algorithm Higher-order functions step by step in the Inform 7 programming language
You may also check:How to resolve the algorithm Inverted syntax step by step in the C++ programming language
You may also check:How to resolve the algorithm LZW compression step by step in the PicoLisp programming language