用 JavaScript 製作相互對應的字謎詞
字謎詞陣列
如果我們對該陣列的元素進行隨機排列,可以得到另一個數組,則一個數組是另一個數組的字謎詞。
例如 −
[1, 2, 3] and [2, 1, 3] are anagrams of each other.
假設我們有兩個陣列,arr1 和 arr2,它們是彼此的字謎詞。
我們需要編寫一個 JavaScript 函式,該函式接受這兩個陣列,並返回一個新對映陣列,其長度與 arr1 和 arr2 相同。該對映陣列應該包含 arr1 陣列的元素在 arr2 陣列中的索引。
例如 −
如果兩個輸入陣列是 −
const arr1 = [23, 39, 57, 43, 61]; const arr2 = [61, 23, 43, 57, 39];
則輸出應該為 −
const output = [1, 4, 3, 2, 0];
因為 arr1 中的索引 0 處的專案在 arr2 中的索引 1 處
arr1 中的索引 1 處的專案在 arr2 中的索引 4 處,依此類推
示例
此程式碼為 −
const arr1 = [23, 39, 57, 43, 61]; const arr2 = [61, 23, 43, 57, 39]; const anagramMappings = (arr1 = [], arr2 = []) => { const res = []; for(let i = 0; i < arr1.length; i++) { for(let j = 0; j < arr2.length; j++) { if(arr1[i] == arr2[j]){ res.push(j); }; }; }; return res; }; console.log(anagramMappings(arr1, arr2));
輸出
控制檯的輸出將為 −
[ 1, 4, 3, 2, 0 ]
廣告