fork download
  1. program shannon
  2. integer, parameter :: LLEN=180, MASCII=127
  3. character(len=LLEN) :: chars
  4. integer(1) :: ic(LLEN)
  5. integer :: cc(0:MASCII)
  6. real ::f(0:MASCII)
  7.  
  8. !equivalence(chars, ic) - does not work with gfortran for some reason
  9.  
  10. READLINE: do
  11. cc = 0
  12. read(*, '(A)', iostat=ios) chars
  13. if (ios .ne. 0) exit
  14.  
  15.  
  16. COUNTCHARS: do i=1,len_trim(chars)
  17. cc(iachar(chars(i:i))) = cc(iachar(chars(i:i))) + 1
  18. end do COUNTCHARS
  19.  
  20. f = real(cc) / len_trim(chars)
  21. f = -1. * f * log(f)
  22.  
  23. entropy = sum(f, mask=cc.gt.0)/log(2.)
  24.  
  25. print *, entropy
  26.  
  27. end do READLINE
  28. end program shannon
Success #stdin #stdout 0s 3924KB
stdin
122333444455555666666777777788888888
563881467447538846567288767728553786
https://w...content-available-to-author-only...t.com/r/dailyprogrammer
int main(int argc, char *argv[])
stdout
   2.79420877    
   2.79420877    
   4.05619860    
   3.86672926