📜  反转移动到前面的变换

📅  最后修改于: 2022-05-13 01:57:06.051000             🧑  作者: Mango

反转移动到前面的变换

先决条件:移至前端数据转换算法

MTF变换逆的主要思想:

1. MTF Transform 的逆计算就是撤消 MTF Transform 并恢复原始字符串。我们有“input_arr” ,它是 MTF 变换和“n” ,它是“input_arr”中的元素数。

2. 我们的任务是维护一个有序的字符列表(在我们的示例中为 a 到 z),并一次从“input_arr”中读取“ith”元素。

3.然后,将该元素作为索引j ,打印列表中的“第 j 个”字符。

Illustration for "[15 1 14 1 14 1]"
List initially contains English alphabets in order.
We move characters at indexes depicted by input 
to front of the list one by one.

input arr chars   output str  list
15                p           abcdefghijklmnopqrstuvwxyz
1                 pa          pabcdefghijklmnoqrstuvwxyz
14                pan         apbcdefghijklmnoqrstuvwxyz
1                 pana        napbcdefghijklmoqrstuvwxyz
14                panam       anpbcdefghijklmoqrstuvwxyz
1                 panama      manpbcdefghijkloqrstuvwxyz

例子:

Input : arr[] = {15, 1, 14, 1, 14, 1}
Output : panama

Input : arr[] = {6, 5, 0, 10, 18, 8, 15, 18, 
                6, 6, 0, 6, 6};
Output : geeksforgeeks

以下是上面解释的想法代码:

// C program to find Inverse of Move to Front
// Transform of a given string
#include
#include
#include
  
// Takes index of printed character as argument
// to bring that character to the front of the list
void moveToFront(int index, char *list)
{
    char record[27];
    strcpy(record, list);
  
    // Characters pushed one position right
    // in the list up until index
    strncpy(list+1, record, index);
  
    // Character at index stored at 0th position
    list[0] = record[index];
}
  
// Move to Front Decoding
void mtfDecode(int arr[], int n)
{
    // Maintains an ordered list of legal symbols
    char list[] = "abcdefghijklmnopqrstuvwxyz";
  
    int i;
    printf("\nInverse of Move to Front Transform: ");
    for (i = 0; i < n; i++)
    {
        // Printing characters of Inverse MTF as output
        printf("%c", list[arr[i]]);
  
        // Moves the printed character to the front 
        // of the list
        moveToFront(arr[i], list);
    }
}
  
// Driver program to test functions above
int main()
{
    // MTF transform and number of elements in it.
    int arr[] = {15, 1, 14, 1, 14, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
  
    // Computes Inverse of Move to Front transform
    // of given text
    mtfDecode(arr, n);
  
    return 0;
}

输出:

Inverse of Move to Front Transform: panama

时间复杂度: O(n^2)

练习:在一个程序中同时实现MTF编码和解码,并检查原始消息是否恢复。

资源:
http://www.cs.princeton.edu/courses/archive/fall07/cos226/assignments/burrows.html