This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
FunctionProject/api/assets/functions/main/heapAlgorithm.js

65 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2020-08-03 12:04:07 +02:00
const errorHandling = require('../../utils/errorHandling')
const { requiredFields } = require('../../config/errors')
const formatNumberResult = require('../secondary/formatNumberResult')
2020-08-03 12:04:07 +02:00
/**
* @description Retourne un tableau contenant toutes les possibilités d'anagramme d'un mot.
* @param {String} string - La chaîne de caractère à permuter
* @returns {Array}
* @examples heapAlgorithm('abc') ["abc", "acb", "bac", "bca", "cab", "cba"]
*/
2020-08-03 12:04:07 +02:00
function heapAlgorithm (string) {
const results = []
2020-08-03 12:04:07 +02:00
if (string.length === 1) {
results.push(string)
return results
}
2020-08-03 12:04:07 +02:00
for (let indexString = 0; indexString < string.length; indexString++) {
const firstChar = string[indexString]
2020-08-03 14:14:45 +02:00
const charsLeft =
string.substring(0, indexString) + string.substring(indexString + 1)
2020-08-03 12:04:07 +02:00
const innerPermutations = heapAlgorithm(charsLeft)
2020-08-03 14:14:45 +02:00
for (
let indexPermutation = 0;
indexPermutation < innerPermutations.length;
indexPermutation++
) {
2020-08-03 12:04:07 +02:00
results.push(firstChar + innerPermutations[indexPermutation])
}
2020-08-03 12:04:07 +02:00
}
return results
}
/* OUTPUTS */
2020-08-03 12:04:07 +02:00
module.exports = ({ res, next }, argsObject) => {
const { string } = argsObject
2020-08-03 12:04:07 +02:00
// S'il n'y a pas les champs obligatoire
2020-08-03 14:14:45 +02:00
if (!string) {
2020-08-03 12:04:07 +02:00
return errorHandling(next, requiredFields)
}
// Si la chaîne de caractère dépasse LIMIT_CHARACTERS caractères
const LIMIT_CHARACTERS = 7
if (string.length > LIMIT_CHARACTERS) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec un mot dépassant ${LIMIT_CHARACTERS} caractères.`,
statusCode: 400
})
2020-08-03 12:04:07 +02:00
}
2020-08-03 12:04:07 +02:00
const result = heapAlgorithm(string)
2020-08-03 14:14:45 +02:00
let resultHTML = `<p>Il y a ${formatNumberResult(
result.length
)} possibilités d'anagramme pour le mot "${string}" qui contient ${
string.length
} caractères, la liste : <br/><br/>`
result.forEach(string => {
2020-08-03 12:04:07 +02:00
resultHTML += string + '<br/>'
})
resultHTML += '</p>'
return res.status(200).json({ result, resultHTML })
}