word_freq.f90 in Fortran
A word-frequency table built from index, substring slices, and a hash-mark chart.
! Count word frequencies in a passage and chart the leaders.
program word_freq
implicit none
character(len=*), parameter :: passage = &
"the rain in maine falls mainly on the plain and " // &
"the rain stays on the plain"
character(len=12) :: words(20), current
integer :: counts(20) = 0
integer :: used = 0
integer :: pos, next_space, i
logical :: known
! Walk the passage: cut at each space, tally every word.
pos = 1
do while (pos <= len(passage))
next_space = index(passage(pos:), " ")
if (next_space == 0) then
current = passage(pos:)
pos = len(passage) + 1
else
current = passage(pos:pos + next_space - 2)
pos = pos + next_space
end if
if (len_trim(current) == 0) cycle
known = .false.
do i = 1, used
if (words(i) == current) then
counts(i) = counts(i) + 1
known = .true.
exit
end if
end do
if (.not. known) then
used = used + 1
words(used) = current
counts(used) = 1
end if
end do
print '(i0, a)', used, " distinct words"
print '(a)', "word ct bar"
do i = 1, used
print '(a, 1x, i2, 1x, a)', words(i), counts(i), &
repeat("#", counts(i))
end do
end program word_freq
How it works
- The
do whilewalks the passage, cutting a word at each space withindex. - A linear search bumps known words or claims the next free slot.
repeat("#", counts(i))draws each word's bar in the report loop.
Keywords and builtins used here
charactercycledoelseendexitifimplicitindexintegerlenlen_trimlogicalnonenotparameterprintprogramrepeatthenwhile
The run, in numbers
- Lines
- 47
- Characters to type
- 1084
- Tokens
- 252
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 233 seconds.
Step 1 of 3 in Encore, step 25 of 27 in Language basics.