Last active
July 1, 2020 11:15
-
-
Save nick3499/a0683dccb076e631b8da30d87bec9907 to your computer and use it in GitHub Desktop.
Nested For Loops for Numerical Inversions (Naive)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/python3 | |
def count_inversions(a): | |
count = 0 | |
for i in range(0, len(a)): | |
for j in range(i+1, len(a)): | |
if a[i] > a[j]: | |
count += 1 | |
return count | |
print(count_inversions([]), 0) | |
print(count_inversions([1, 2, 3]), 0) | |
print(count_inversions([2, 1, 3]), 1) | |
print(count_inversions([6, 5, 4, 3, 2, 1]), 15) | |
print(count_inversions([6, 5, 4, 3, 3, 3, 3, 2, 1]), 30) | |
print(count_inversions([1, 2, 3, 4]), 0) | |
print(count_inversions([1, 3, 2, 4]), 1) | |
print(count_inversions([4, 1, 2, 3]), 3) | |
print(count_inversions([4, 3, 2, 1]), 6) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/nodejs | |
function countInversions(a) { | |
var count = 0 | |
for (let i=0; i<a.length; ++i) { | |
for (let j=i+1; j<a.length; ++j) { | |
if (a[i] > a[j]) { | |
count++ | |
} | |
} | |
} | |
return count | |
} | |
console.log(countInversions([]), 0) | |
console.log(countInversions([1, 2, 3]), 0) | |
console.log(countInversions([2, 1, 3]), 1) | |
console.log(countInversions([6, 5, 4, 3, 2, 1]), 15) | |
console.log(countInversions([6, 5, 4, 3, 3, 3, 3, 2, 1]), 30) | |
console.log(countInversions([1, 2, 3, 4]), 0) | |
console.log(countInversions([1, 3, 2, 4]), 1) | |
console.log(countInversions([4, 1, 2, 3]), 3) | |
console.log(countInversions([4, 3, 2, 1]), 6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test script in local terminal emulator:
curl
is likewget
-s
option silences extra stats| python3
pipes cURL's output topython3
Also test with local
node
installation.[4, 3, 2, 1]
has six numerical inversions because Y < X in the pairs[4, 3]
,[4, 2]
,[4, 1]
,[3, 2]
,[3, 1]
, and[2, 1]
, so[1, 2, 3, 4]
has no such inversions, since Y > X persists through each iteration.