let n = "jsdfnsgnlewnl";
let l = n.length;
let trgt = Math.floor((l-1)/2);
function firstHalf(anyhting){
let ans = [];
for (i = trgt; i>=0; i--){
ans.push(n[i])
}
return ans;
}
function lastHlaf (anyhting){
let ansx = [];
for (i=l-1; i>=trgt+1; i--){
ansx.push(n[i])
}
return ansx;
}
let answer = firstHalf(n);
let answerx = lastHlaf(n);
let newAnswer = answer.join("");
let newAnswerx = answerx.join("");
console.log(newAnswer+newAnswerx)
in this code the output should be -> snfdsjglnweln
But it's giving --> gsnfdsjlnweln
Can anyone please explain me.
Thank you for example --> //if ithe input is odd like xyzakig //then the middle value should not be changed please help me to understand the issue
Aaaahhh, with your comment concerning odd number of string-length, I think I understood now your question. Hence I edited my initial answer.
Initial string jsdfnsgnlewnl
to devide into 2 parts
We get left half jsdfns
and right half nlewnl
Then invert each block seperately
We get snfdsj
and lnweln
Check if initial string-length is odd
If so, we define the middle element, here g
Then join the 2 strings (or 3 strings if odd)
We get snfdsjglnwelng
Now we get your requested result: snfdsjglnweln
The following code would give you the expected output:
let n = "jsdfnsgnlewnl";
let l = n.length;
let trgt = Math.floor(l/2); // '(l/2) instead of '((l-1)/2)'
let even = Number.isInteger(l/2); // check if 'l' is an even number
function firstHalf(anyhting){
let ans = []; // index 'i' is zero-based:
for (i = trgt-1; i>=0; i--){ // 'trgt-1' instead of 'trgt'
ans.push(n[i])
}
return ans;
}
function lastHalf (anyhting){ // corrected typo: 'lastHalf' instead of 'lastHlaf'
let ansx = [];
for (i=l-1; i>l-1-trgt; i--){ // 'i>l-1-trgt' instead of 'i>=trgt-1'
ansx.push(n[i])
}
return ansx;
}
let answerMiddle = "";
if (!even) answerMiddle = n[trgt]; // define the "letter in the middle" if odd
let answer = firstHalf(n);
let answerx = lastHalf(n);
let newAnswer = answer.join("");
let newAnswerx = answerx.join("");
console.log(newAnswer + answerMiddle + newAnswerx) // add also '+answerMiddle'
I tested for even string-lengths as well - worked. Hope I got it right now.