« CONTACT « TUTOS

Algorithms Javascript


Alphabetic Shift(décalage) :

Each alphabetic letter transform by +1 next letter

	function alphabeticShift(inputString){
		let alphabet = ["a","b","c","d","e","f","g","h","i","k","l",
"m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; inputString = split(inputString); var indexVal; for (var i = 0; i < inputString.length; i++) { if ( inputString[i] != "z") { indexVal = alphabet.indexOf(inputString[i])+1; } inputString[i] = alphabet[indexVal]; } return indexVal } document.write("crazy"); document.write(alphabeticShift("crazy"));

Results :




Check Palindrome :

If one letter has 2 letter identic around

	 function checkPalindrome(inputString) {
		 return inputString ===
		 inputString.split("").reverse().join("");
		}

	document.write("aabaa");
	document.write(checkPalindrome("aabaa"));
	

Results :




Array Replace Elements :

Replace all the occurences of elemToReplace with substitutionElem

	 function arrayReplace(inputArray, elemToReplace, substitutionElem) {

		 inputArray.forEach(function (element, index){

			if(element === elemToReplace){
				inputArray[index] = substitionElem;
			}
		});
		return inputArray;
	}
	var inputArray = [1,2,3];
	var elemToReplace = 1;
	var substitionElem = 3;
	document.write(inputArray);

	var result = arrayReplace(inputArray,elemToReplace, substitionElem);
	document.write(JSON.stringify(result,null, 4));
  	document.write(result);

Results :




Deposit Profit

Calcul how many years need to the threshold(seuil) at 170
it start with 100 deposit and 20% rate by Year

	function depositProfit(deposit, rate, threshold){
		let years = 0;
		while ( threshold > deposit) {
			deposit += deposit*(rate/100);
			year++;
			}
		return year
		}

		document.write(depositProfit(100,20,170));

Results :




even Digits Only

Check if all digits of the given integer are even(pair)
%2 === 0

	function evenDigitsOnly(n) {
		n = n.toString().split("");

		return n.every(function (element) {
			return parseInt(element) % 2 === 0; });
		}
// ESC6 :
// return n.every( (element)=>{ return parseInt(element)%2===0 } );

		document.write(evenDigitsOnly(248622));
		document.write(evenDigitsOnly(642386));

Results :




Palindrome Rearranging

Given a string, find out if it's characters can be rearranged to form a palindrome

	function palindromeRearranging(inputString){
	 var charArray = inputString.split("");
	 var letterObject = {};

	 for(var i = 0; i < charArray.length;i++){
			if(!letterObject.hasOwnProperty(charArray[i])){
				letterObject[charArray[i]] = 1;
			}else{
				letterObject[charArray[i]]++;

			}
	 }
	 var oddCount = 0;
	 for(val in letterObject){
		 if(letterObject[val] % 2 != 0){
			 oddCount++;
		 }
	 }
	 // ternaire
	return oddCount > 1 ? false :true;
	}

 document.write( palindromeRearranging("aabb") );
 document.write( palindromeRearranging("abcd") );

Results :

« CONTACT

Cette page a été vue  610 fois !