Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Java Index of Coincidence If two strings of equal length are superimposed on

ID: 3837353 • Letter: I

Question

In Java

Index of Coincidence

If two strings of equal length are superimposed on one another, then some letters may match. For example consider the strings

wonderwhowrotethebookonlove and weallliveinayellowsubmarine

Notice that there are three positions that contain the same letter: the 1 st (w) , 14 th (e), and 27 th (e). Of 27 possible positions, matches occur in three positions (11.1%). This percentage is called the index of coincidence for two strings, and it is used to decrypt ciphers like those used by the Germans in World War II.

Write a program that accepts two strings of the same length and determines their index of coincidence. For normal written English, the index of coincidence averages about 6.6%, while for random strings it is 1/26, or around 3.8%.

Explanation / Answer

public class IndexOfCoincidence extends JPanel{

   public static void main(String[] args) {

       System.out.println("IofC "+indexOfCoincidence("wonderwhowrotethebookonlove","weallliveinayellowsubmarine"));
   }
  
   public static double indexOfCoincidence(String str1, String str2){
       double iOfC =0.0;
       if(str1.length() != str2.length()){
           System.out.println("Strings must be of same length");
           return iOfC;
       }
       int count=0;
       for(int i=0; i<str1.length(); i++){
           if(str1.charAt(i)==str2.charAt(i))
               count++;
       }
       iOfC = ((double)count/(double)str1.length())*100.0d;
       return iOfC;
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote