Lily's Homework

  • + 0 comments

    Solution in JS: function getNumberSwaps(arr, arrMap, sortedArr) { let numberOfSwaps = 0; for (let i = 0; i < sortedArr.length; i++) { if (sortedArr[i] !== arr[i]) { const tmp = arr[i]; const idxSource = arrMap[sortedArr[i]];

            arr[i] = arr[idxSource];
            arr[idxSource] = tmp;
    
            arrMap[tmp] = idxSource;
            arrMap[sortedArr[i]] = i;
    
            numberOfSwaps++;
        }
    }
    
    return numberOfSwaps;
    

    }

    function lilysHomework(arr) { const ascArr = arr.toSorted((a, b) => a - b); const descArr = arr.toSorted((a, b) => b - a);

    const arrMap = {};
    arr.forEach((num, idx) => {
        arrMap[num] = idx
    });
    return Math.min(getNumberSwaps([...arr], { ...arrMap }, ascArr), getNumberSwaps(arr, arrMap, descArr));
    

    }

    
    
    
    

    `