Letter frequency: Difference between revisions

Content added Content deleted
No edit summary
No edit summary
Line 5,840: Line 5,840:
</pre>
</pre>


=={{header|S-BASIC}}==
Because S-BASIC lacks an EOF function, some extra care is required to avoid reading beyond the end of file. (CP/M text files are by convention terminated with a Ctrl-Z byte, but not all text editors enforce this if the file would otherwise end on a sector boundary.)
<lang S-BASIC>
$constant EOF = 1AH rem Ctrl-Z signals end of file

rem Convert character to upper case
function upcase(ch = char) = char
if ch >= 'a' and ch <= 'z' then
ch = ch - 32
end = ch

rem Convert string to all upper case characters
function allcaps(source = string) = string
var p = integer
for p = 1 to len(source) do
mid(source,p,1) = upcase(mid(source,p,1))
next p
end = source

rem Preserve console channels (#0 and #1)
files d, d, sa(1)

var ch = char
var i = integer
based errcode = integer
base errcode at 103H rem S-BASIC stores run-time error code here
var filename = string
var total = real
dim real freq(26)

input "Name of text file to process: "; filename
filename = allcaps(filename)
open #2; filename
on error goto 7_trap rem In case input file lacks terminating ^Z

rem Initialize letter counts to zero
for i = 1 to 26
freq(i) = 0
next i

rem Process the file
total = 0
input3 #2; ch
while ch <> EOF do
begin
ch = upcase(ch);
if ch >= "A" and ch <= "Z" then
begin
freq(asc(upcase(ch)) - 64) = freq(asc(upcase(ch)) - 64) + 1
total = total + 1
end
input3 #2; ch
end
goto 8_done rem Jump around error trap

7_trap if errcode <> 15 then
begin
print "Runtime error = ";errcode
goto 9_exit
end
rem otherwise fall through on attempted read past EOF (err = 15)
8_done
close #2

rem Report results
print "Letter Count Percent"
for I = 1 to 26
print chr(i+64);" ";
print using " ##,###"; freq(i);
print using " ##.#"; freq(i) / total * 100
next i
9_exit
end
</lang>
{{out}}
Lincoln's Second Inaugural Address
<pre>
Letter Count Percent
A 101 8.8
B 14 1.2
C 31 2.7
D 59 5.1
E 165 14.3
F 27 2.3
G 28 2.4
H 80 7.0
I 68 5.9
J 0 0.0
K 3 0.3
L 42 3.7
M 13 1.1
N 78 6.8
O 93 8.1
P 15 1.3
Q 1 0.1
R 79 6.9
S 44 3.8
T 126 11.0
U 21 1.8
V 23 2.0
W 28 2.4
X 0 0.0
Y 11 1.0
Z 0 0.0
</pre>
=={{header|Scala}}==
=={{header|Scala}}==