Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculate Character Frequency in Message using Perl
    primarykey
    data
    text
    <p>I am writing a Perl Script to find out the frequency of occurrence of characters in a message. Here is the logic I am following:</p> <ul> <li>Read one char at a time from the message using getc() and store it into an array.</li> <li>Run a for loop starting from index 0 to the length of this array.</li> <li>This loop will read each char of the array and assign it to a temp variable.</li> <li>Run another for loop nested in the above, which will run from the index of the character being tested till the length of the array. </li> <li>Using a string comparison between this character and the current array indexed char, a counter is incremented if they are equal.</li> <li>After completion of inner For Loop, I am printing the frequency of the char for debug purposes.</li> </ul> <p>Question: I don't want the program to recompute the frequency of a character if it's already been calculated. For instance, if character "a" occurs 3 times, for the first run, it calculates the correct frequency. However, at the next occurrence of "a", since loop runs from that index till the end, the frequency is (actual freq -1). Similary for the third occurrence, frequency is (actual freq -2).</p> <p>To solve this. I used another temp array to which I would push the char whose frequency is already evaluated.</p> <p>And then at the next run of for loop, before entering the inner for loop, I compare the current char with the array of evaluated chars and set a flag. Based on that flag, the inner for loop runs.</p> <p>This is not working for me. Still the same results.</p> <p>Here's the code I have written to accomplish the above:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; my $input=$ARGV[0]; my ($c,$ch,$flag,$s,@arr,@temp); open(INPUT,"&lt;$input"); while(defined($c = getc(INPUT))) { push(@arr,$c); } close(INPUT); my $length=$#arr+1; for(my $i=0;$i&lt;$length;$i++) { $count=0; $flag=0; $ch=$arr[$i]; foreach $s (@temp) { if($ch eq $s) { $flag = 1; } } if($flag == 0) { for(my $k=$i;$k&lt;$length;$k++) { if($ch eq $arr[$k]) { $count = $count+1; } } push(@temp,$ch); print "The character \"".$ch."\" appears ".$count." number of times in the message"."\n"; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload