Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Sorts/PatienceSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Patience Sort is a sorting algorithm inspired by, and named after, the card game patience.
* more information: https://en.wikipedia.org/wiki/Patience_sorting
*/

export function patienceSort (items) {
const piles = []

for (let i = 0; i < items.length; i++) {
const num = items[i]
const destinationPileIndex = piles.findIndex(
(pile) => num >= pile[pile.length - 1]
)
if (destinationPileIndex === -1) {
piles.push([num])
} else {
piles[destinationPileIndex].push(num)
}
}

for (let i = 0; i < items.length; i++) {
let destinationPileIndex = 0
for (let p = 1; p < piles.length; p++) {
const pile = piles[p]
if (pile[0] < piles[destinationPileIndex][0]) {
destinationPileIndex = p
}
}
const distPile = piles[destinationPileIndex]
items[i] = distPile.shift()
if (distPile.length === 0) {
piles.splice(destinationPileIndex, 1)
}
}

return items
}
25 changes: 25 additions & 0 deletions Sorts/test/PatienceSort.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { patienceSort } from '../PatienceSort'

test('The PatienceSort of the array [5, 4, 3, 2, 1] is [1, 2, 3, 4, 5]', () => {
Copy link
Collaborator

@appgurueu appgurueu Oct 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use each: https://github.com/TheAlgorithms/TypeScript/blob/master/CONTRIBUTING.md#writing-good-tests
(side note: eventually the tests for all sorting algorithms should be consolidated as I have done in the Lua repo)

const arr = [5, 4, 3, 2, 1]
const res = patienceSort(arr)
expect(res).toEqual([1, 2, 3, 4, 5])
})

test('The PatienceSort of the array [] is []', () => {
const arr = []
const res = patienceSort(arr)
expect(res).toEqual([])
})

test('The PatienceSort of the array [15, 24, 31, 42, 11] is [11, 15, 24, 31, 42]', () => {
const arr = [15, 24, 31, 42, 11]
const res = patienceSort(arr)
expect(res).toEqual([11, 15, 24, 31, 42])
})

test('The PatienceSort of the array [121, 190, 169] is [121, 169, 190]', () => {
const arr = [121, 190, 169]
const res = patienceSort(arr)
expect(res).toEqual([121, 169, 190])
})