Announcement

Collapse
No announcement yet.

Counting letters

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Counting letters

    Hi there,
    in the text I want to count how many times letters are used

    For Example:
    "Hello, I am form Turkey, Please Help me!"

    H: 2
    E: 6
    L: 4
    O: 1
    I: 1

    like that..

  • #2
    Show us what you have managed to get working so far.

    Ulrich

    Comment


    • #3
      Code:
      tamer="Hello, I am form Turkey, Please Help me!"
      tamer = String.Replace(tamer, " ", "", false);
      local bel = {}
      for h = 1,#tamer do
      y =  String.Mid(tamer, h, 1);
      Table.Insert(bel, h, y);
      end
      kiss = ""
      local table = table.concat(bel,"%|%")
      for i = 1, #bel do
      local _,n = string.gsub(table,bel[i],"")
      sline = string.format("%s =%d",bel[i],n)
      local _,d = string.gsub(kiss,sline,"")
        if (d == 0) then
      kiss = kiss .. sline.. "\r\n"
      end
      end
      Dialog.Message("Notice", kiss);

      Comment


      • #4
        Not bad, and it works. Note that you can make this script a little less complicated, and filter out unwanted letters, for example:

        Code:
        tamer [COLOR="#FF0000"]=[/COLOR] [COLOR="#800080"]"Hello, I am from Turkey, Please Help me!"[/COLOR]
        [COLOR="#0000FF"]local[/COLOR] bel [COLOR="#FF0000"]=[/COLOR] [COLOR="#FF0000"]{};[/COLOR]
        [COLOR="#0000FF"]local[/COLOR] kiss [COLOR="#FF0000"]=[/COLOR] [COLOR="#800080"]""[/COLOR][COLOR="#FF0000"];[/COLOR]
        
        [COLOR="#0000FF"]for[/COLOR] h [COLOR="#FF0000"]=[/COLOR] [COLOR="#000000"]1[/COLOR][COLOR="#FF0000"],[/COLOR] [COLOR="#FF0000"]#[/COLOR]tamer [COLOR="#0000FF"]do[/COLOR]
          y [COLOR="#FF0000"]=[/COLOR] [COLOR="#0000FF"]string.upper[/COLOR](String[COLOR="#FF0000"].[/COLOR]Mid(tamer[COLOR="#FF0000"],[/COLOR] h[COLOR="#FF0000"],[/COLOR] [COLOR="#000000"]1[/COLOR]))[COLOR="#FF0000"];[/COLOR]
          [COLOR="#0000FF"]if[/COLOR] (y [COLOR="#FF0000"]>=[/COLOR] [COLOR="#800080"]'A'[/COLOR] [COLOR="#0000FF"]and[/COLOR] y [COLOR="#FF0000"]<=[/COLOR] [COLOR="#800080"]'Z'[/COLOR]) [COLOR="#0000FF"]then[/COLOR]
            [COLOR="#0000FF"]if[/COLOR] (bel[COLOR="#FF0000"][[/COLOR]y[COLOR="#FF0000"]][/COLOR] [COLOR="#FF0000"]~=[/COLOR] [COLOR="#0000FF"]nil[/COLOR]) [COLOR="#0000FF"]then[/COLOR]
              bel[COLOR="#FF0000"][[/COLOR]y[COLOR="#FF0000"]][/COLOR] [COLOR="#FF0000"]=[/COLOR] bel[COLOR="#FF0000"][[/COLOR]y[COLOR="#FF0000"]][/COLOR] + [COLOR="#000000"]1[/COLOR][COLOR="#FF0000"];[/COLOR]
            [COLOR="#0000FF"]else[/COLOR]
              bel[COLOR="#FF0000"][[/COLOR]y[COLOR="#FF0000"]][/COLOR] [COLOR="#FF0000"]=[/COLOR] [COLOR="#000000"]1[/COLOR][COLOR="#FF0000"];[/COLOR]
            [COLOR="#0000FF"]end[/COLOR]
          [COLOR="#0000FF"]end[/COLOR]
        [COLOR="#0000FF"]end[/COLOR]
        
        [COLOR="#0000FF"]for[/COLOR] i[COLOR="#FF0000"],[/COLOR] j [COLOR="#0000FF"]in[/COLOR] [COLOR="#0000FF"]pairs[/COLOR](bel) [COLOR="#0000FF"]do[/COLOR]
          kiss [COLOR="#FF0000"]=[/COLOR] kiss [COLOR="#FF0000"]..[/COLOR] [COLOR="#0000FF"]string.format[/COLOR]([COLOR="#800080"]"%s = %d"[/COLOR][COLOR="#FF0000"],[/COLOR] i[COLOR="#FF0000"],[/COLOR] j) [COLOR="#FF0000"]..[/COLOR] [COLOR="#800080"]"[COLOR="#800080"]\r[/COLOR][COLOR="#800080"]\n[/COLOR]"[/COLOR][COLOR="#FF0000"];[/COLOR]
        [COLOR="#0000FF"]end[/COLOR]
        
        Dialog[COLOR="#FF0000"].[/COLOR]Message([COLOR="#800080"]"Notice"[/COLOR][COLOR="#FF0000"],[/COLOR] kiss)[COLOR="#FF0000"];[/COLOR]
        Ulrich

        Comment


        • #5
          Thank you , but my Arabic language does not deal with
          string.upper
          Thank you

          Comment


          • #6
            thaks

            thanks for answers
            but
            actually, I need to calculate frequency. im preparing cryptology lesson for my students.
            there is a topic about cryptanalysis method. iFor example you find a book (novel) and count all letters how many times used in the novel. for example A letter used 35218 times in novel and E letter used 21345 times. also novel has 325418 letters. 35218 / 3255418 = frequency of A letter. i need to find out all frequency values of each letters. This is my trouble

            Comment


            • #7
              If you are indeed a teacher in the cryptology field, you shouldn't have any troubles putting together an algorithm for this, or understanding how to add a simple division to the results displayed in the samples provided above.

              Ulrich

              Comment


              • #8
                Here's another example to get the frequency of characters with lower/upper- case support.
                Code:
                local function countCharacters(str) 
                  local charCount  = {};
                  local totalCount = 0;
                
                  str:gsub(".", function(c)
                    c = c:lower();
                    charCount[c] = (charCount[c] and charCount[c] + 1 or 1);
                  end);
                
                  for i, v in pairs(charCount)do
                    totalCount = (totalCount + v);
                  end
                
                  return {char = charCount; total = totalCount};
                end;
                
                
                local str = "Hello World!! This is a count test :)";
                local cnt = countCharacters(str);
                print('space  freq: ', 100 * ((cnt.char[' '] or 0) / str:len())); -- % frequency of space character
                print('char e freq: ', 100 * ((cnt.char['e'] or 0) / str:len())); -- % frequency of space character
                print('char t freq: ', 100 * ((cnt.char['t'] or 0) / str:len())); -- % frequency of space character
                Result
                Code:
                space  freq: 	18.918918918919
                char e freq: 	5.4054054054054
                char t freq: 	10.810810810811
                I did something like this before for Project Euler: https://projecteuler.net/index.php?s...problems&id=59
                This was my solution (hence there are some dependencies missing for you)
                Code:
                local etime = require("util.etime").start();
                require "util.permutation";
                
                euler59 = {
                    asciiCodes = function(path)
                        local t = {};
                        local f = io.open(path, "rb");
                        if(f)then
                            for ascii in f:read("*all"):gmatch("([0-9]+)")do
                                t[#t + 1] = tonumber(ascii);
                            end
                            f:close();
                        end
                        
                        return t;
                    end;
                    
                    -- Find the most occurring ascii codes in the list, these are probably
                    -- space characters as these usually occur the most in text. This means
                    -- we can XOR the 3 most occurring characters with 32 (space char) to find
                    -- our key.
                    quickAnalyze = function(tAscii, keyLength)
                        local sort, pairs, chr, xor = table.sort, pairs, string.char, bitwise.XOr;
                        -- Allocate a table using all indices, so Lua will not try to compare with a nil value.
                        local occurrences = (function()
                            local t = {};
                            for i = 0, 255 do
                                t[i] = {
                                    count = 0;
                                    char = i;
                                };
                            end
                            
                            return t;
                        end)();
                        
                        -- Count each character present in the file
                        for i, v in pairs(tAscii)do
                            occurrences[v].count = (occurrences[v].count + 1)
                        end
                        
                        -- Sort the table
                        sort(occurrences, function(a, b)
                            return (a.count > b.count);
                        end);
                        
                        -- Generate possible key bytes from the first 'keyLength' bytes from our analysis.
                        local key = {};
                        for i = 1, keyLength do
                            key[#key + 1] = xor(occurrences[i].char, 32);
                        end
                        
                        return key;
                    end;
                    
                    -- XOR all the tAscii values with tKey.
                    xorContents = function(tAscii, tKey)
                        local pairs, xor = pairs, bitwise.XOr;
                        local keyLength     = #tKey;
                        local keyPosition   = 1;
                        local tXORd         = {};
                        
                        for i, byte in pairs(tAscii)do
                            tXORd[i] = xor(byte, tKey[keyPosition]);
                            
                            keyPosition = ((keyPosition == keyLength) and 1 or (keyPosition + 1));
                        end
                        
                        return tXORd;
                    end;
                    
                    -- Convert an ascii code table to a readable string.
                    ascii2string = function(ascii) 
                        local chr = string.char;
                        local t = {};
                        for i, v in pairs(ascii)do
                            t[#t + 1] = chr(v);
                        end
                        
                        return table.concat(t, "");
                    end;
                    
                    solve1 = function()
                        local result        = 0;
                        local validKey      = "";
                        local asciiCodes    = euler59.asciiCodes("/data/cipher1.txt");
                        local keyAnalytics  = euler59.quickAnalyze(asciiCodes, 3); 
                        
                        -- Yes, I know the key is 'god' but I want to do this the proper way, a 
                        -- one-run solution without using knowledge I gained from previous steps.
                        permutation(keyAnalytics, 3, function(key)
                            local decryptedRaw  = euler59.xorContents(asciiCodes, key);
                            local decryptedStr  = euler59.ascii2string(decryptedRaw);
                            
                            -- Check if we can find common English words.
                            local seemsValid = true;
                            for i, v in pairs{"and", "in", "or", "the"}do
                                if(not decryptedStr:find(v))then
                                    seemsValid = false;
                                    break;
                                end
                            end
                            
                            if(seemsValid)then
                                validKey = euler59.ascii2string(key);
                                for i, v in pairs(decryptedRaw)do
                                    result = (result + v);
                                end
                            end
                        end)
                        
                        return result, validKey;
                    end;
                }
                
                print(etime:execmark("method1", function()
                    local result, validKey = euler59.solve1();
                    print("Sum: ", result);
                    print("Detected key: ", validKey);
                end):durationf("Duration method1: %0.5f seconds (%0.0f ms).", "method1"));
                Bas Groothedde
                Imagine Programming :: Blog

                AMS8 Plugins
                IMXLH Compiler

                Comment

                Working...
                X