Hi This is my first time using this website, I did do some research about how to convert lowercase letter to uppercase letter but still filles. The requirement is to check if "even", covert the even digit letter to different type(lower to upper or upper to lower). below is my code:
function question4(str,pos)
{ var newLetter;
var kkk=str;
if (pos='even')
{
for (var i=0;i<str.length;i=i+2)
{
if (str[i].toString()==str[i].toString().toUpperCase())
{
newLetter=str[i].toString().toLowerCase();
kkk[i]=newLetter;
}else
{
newLetter=str[i].toUpperCase();
kkk[i]=newLetter;
}
}
}else if (pos='odd')
for ( i=0;i<str.length;i=i+2)
{
if (str[i]===str[i].toLowerCase())
{
alert('3');
}else if (str[i]===str[i].toUpperCase())
{
alert('4');
}
}
return kkk;
}
the requirement is: Write a function to change the case of all the characters in string based on their position which matches the value of the pos parameter function. function (str, pos [even|odd]). Example ( (‘abCd’, ‘odd’) return Abcd)
Update: now I have make "odd" condition working, but "even "still is not working, can any one take a look why?
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}else result=strr[i];
sum+=result;
}
return sum;
}
To achieve this, you can construct a string by concating char by char:
function question4(strInput, pos) {
let str = ""; // The string to construct
if (!pos || (pos !== "even" && pos !== "odd")) { // Validating pos
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++) // Looping on strInput
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
/* If we want switch odd and we are on even position or if we want switch even and we are on odd position, then we add the original char
*/
str += strInput[i];
}
else {
// In others case, we switch lower to upper and upper to lower
let char = strInput[i];
str += char == char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
}
}
return str;
}
console.log(question4('abCdef', "odd")); // Return "AbcdEf"
Associated bin
EDIT:
After seeing edit, i can see you want to do it without using toLower/UpperCase. As stated in comment i think it is a bad idea in js, but to experiment you can achieve this:
const reverser = {
"a": "a".charCodeAt(0),
"z": "z".charCodeAt(0),
"A": "A".charCodeAt(0),
"Z": "Z".charCodeAt(0),
};
const conversionValueToLower = reverser.a - reverser.A;
const conversionValueToUpper = reverser.A - reverser.a;
function reverseChar(char) {
var code = char.charCodeAt(0);
// If you want to go from upper to lower
if (code >= reverser.A && code <= reverser.Z) {
// Simply add the difference between lower and upper
return String.fromCharCode(code + conversionValueToLower);
} // Same logic here
else if (code >= reverser.a && code <= reverser.z) {
return String.fromCharCode(code + conversionValueToUpper);
}
/**
Or use if you want full digit
if (code <= 90 && code >= 65) {
return String.fromCharCode(code + 32);
}
else if (code >= 97 && code <= 122) {
return String.fromCharCode(code - 32);
}
**/
return char; // Other case return original char
}
function question4(strInput, pos) {
let str = "";
if (!pos || (pos !== "even" && pos !== "odd")) {
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++)
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
str += strInput[i];
}
else {
str += reverseChar(strInput[i]);
}
}
return str;
}
console.log(question4('abCdef', "odd")); // return "AbcdEf"
Associated bin
Another way could be to code utils functions imitating toLower/UpperCase
I corrected your code in your answer aswell, without changing original logic
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
console.log(question4("abCd", "odd")) // return Abcd;
A simple solution for this question
// Function used to invert the letter case
const changeCase = c => {
if (c === c.toUpperCase()) return c.toLowerCase()
return c.toUpperCase()
}
const swapCaseConditional = (str, pos) => {
// Use split method to convert string into array and map the array
return str.split('').map((c, index) => {
if (pos === 'even') {
// if pos and index are even, change the letter case
if (index % 2) return changeCase(c)
return c
}
else {
// if pos and index are odd, change the letter case
if (!(index%2)) return changeCase(c)
return c
}
// Convert to string
}).join('')
}
console.log(swapCaseConditional('abCd', 'odd'))
I worked two nights and finally got it working. although not fully cover all the situations, but almost there.
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
Related
I am trying to insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers, but I am only getting the last result.
I want to print out all the elements in the array.
For example: if num is 4546793 the output should be 454*67-9-3. I Did not count zero as an odd or even number.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i] === 0) {
continue;
}
if (num[i - 1] % 2 == 0 && num[i] % 2 == 0) {
result = num[i - 1] + "*" + num[i];
continue;
}
if (num[i - 1] % 2 == !0 && num[i] % 2 == !0) {
result = num[i - 1] + "-" + num[i];
continue;
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
You do not need to check as if&continue. Inserting given numbers to the result string and only adding "-" when index and previous are odd, and "*" when index and previous are even.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i]%2 ===0) {// even
if(i !== 0 && num[i-1]%2===0){// previous is even either
result+="*"+num[i];
}else{
result+=num[i];
}
}else{// odd
if(i !== 0 && num[i-1]%2===1){// previous is odd either
result+="-"+num[i];
}else{
result+=num[i];
}
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Try this :)
function test(a){
let result=""
for(let i=0; i < a.length; i++){
if(a[i] != 0 && a[i-1] % 2 == 0 && a[i] % 2 == 0){
result = result + '*' + a[i]
}
else if (a[i] != 0 && a[i-1] % 2 != 0 && a[i] % 2 != 0){
result = result + '-' + a[i]
}
else{
result = result + a[i]
}
}
return result
}
console.log(test([4,5,4,6,7,9,3]));
As everyone has identified, the problem is you are not adding to result.
But here is a suggestion to make your code easier to read
// These one line functions make your code easier to read
function IsEven(num){
return num % 2 === 0;
}
function IsOdd(num){
return num % 2 !== 0;
}
function StringChallenge(numArray) {
// return empty string if not an array or empty array
if(!Array.isArray(numArray) || numArray.length === 0) return "";
let result = "" + numArray[0]; // use "" to coerce first element of numArray from number to string
for (let i = 1; i < numArray.length; i++) {
// focus on the conditions to determine the separator you want between each element
separator = "";
if (numArray[i] !== 0) {
if (IsEven(numArray[i]) && IsEven(numArray[i - 1])) {
separator = "*";
} else if (IsOdd(numArray[i]) && IsOdd(numArray[i - 1])){
separator = "-";
}
}
// build the result
result += separator + numArray[i];
}
return result;
}
I will do that this way :
== some advices for 2 cents ==
1 - try to make your code as readable as possible.
2 - use boolean tests rather than calculations to simply do a parity test
3 - ES7 has greatly improved the writing of JS code, so take advantage of it
console.log(StringChallenge([4,5,4,6,7,9,3])); // 454*67-9-3
function StringChallenge( Nums = [] )
{
const
isOdd = x => !!(x & 1) // Boolean test on binary value
, isEven = x => !(x & 1) && x!==0 // zero is not accepted as Even value
;
let result = `${Nums[0]??''}`; // get first number as
// result if Nums.length > 0
for (let i=1; i<Nums.length; i++)
{
if ( isOdd(Nums[i-1]) && isOdd(Nums[i]) ) result += '-';
if ( isEven(Nums[i-1]) && isEven(Nums[i]) ) result += '*';
result += `${Nums[i]}`; // same as Nums[i].toString(10);
}
return result
}
I hope this helps. I tried to keep it as simple as possible.
function StringChallenge(num) {
//start with a string to concatenate, or else interpreter tries to do math
operations
let result = num[0].toString();
function checkOdd(num){ //helper function to check if odd
return num % 2
}
for (let i = 0; i < num.length - 1; i++) {
if (checkOdd(num[i]) && checkOdd(num[i+1])) { //checks if both odd
result += `-${num[i+1]}`; //adds - and next number
} else if (!checkOdd(num[i]) && !checkOdd(num[i+1])) { //checks if both even
result += `*${num[i+1]}`; //adds * and next number
} else { //otherwise
result += num[i+1]; //just add next number
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Use +=. And, change your logic, your code prints out "4*67-99-3".
The zero check was pretty hard for me I hope the variables in my code explain itself. If not, let me know.
function even(num) {
return num % 2 === 0;
}
function odd(num) {
return num % 2 !== 0;
}
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
var currentZero = num[i] === 0
var previousZero = num[i-1] === 0
var bothEven = even(num[i]) && even(num[i-1])
var bothOdd = odd(num[i]) && odd(num[i-1])
var firstNumber = (i === 0)
if (!currentZero) {
if (firstNumber) {
result += num[i]
} else {
if (bothEven && !previousZero) {
result += "*" + num[i]
} else if (bothOdd && !currentZero) {
result += "-" + num[i]
} else {
result += num[i]
}
}
}
}
return result;
}
console.log(StringChallenge([0,4,5,0,4,6,7,9,3]));
I am trying to format a number as follows:
if no decimals in number then return 4 decimal (i.e. 100 would be 100.0000 and 0 would be 0.0000)
If there are decimals just return up to the last non 0 decimal(i.e. 100.000110000 would be 100.00011)
Below is my scrub function of which I load the value to be formatted into domtemp.value
The problem is in the "else if" below when checking for 0 decimals(or a whole number being entered). I never get there because the result always seems to be 0 whether or not I pass in 100 or 100.0011. Any ideas what I might be doing wrong with checking for a whole number?
function scrubAsFound() {
var i;
var length = 4;
for (i = 1; i <= length; i++) {
domtemp = document.querySelector('#equipment_asfound' + i);
// Check for empty values
if (isNaN(domtemp.value) || (!domtemp.value || 0 === domtemp.value.length))
{
domtemp.value = 0.0000;
domtemp.value = Number(domtemp.value).toFixed(4);
}
else if (Number(domtemp.value) % 1 != 0)
{
domtemp.value = Number(domtemp.value).toFixed(4);
}
else
{
domtemp.value = parseFloat(formatAsFound(domtemp.value));
}
}
}
function formatNumber(val) {
let numberVal = Number(val)
if (isNaN(numberVal)) {
numberVal = 0
}
const intVal = parseInt(numberVal)
return intVal + '.' + (numberVal + '').substr((intVal + '').length + 1).padEnd(4, '0')
}
console.log(formatNumber('abc') === '0.0000')
console.log(formatNumber('') === '0.0000')
console.log(formatNumber(0) === '0.0000')
console.log(formatNumber(2) === '2.0000')
console.log(formatNumber(2.1) === '2.1000')
console.log(formatNumber(2.00011) === '2.00011')
Learning JS/programming and running through some basic exercises.
This one is to determine if a word is a palindrome (reads the same forwards as backwards).
My problem is that the function is returning false even when I input a palindrome. From looking at it stepping over, it seems string[i] is giving an integer to compare, instead of the character at that current index.
let input = "hannah";
let firstCharacter = input[0];
let lastIndex = input.length -1;
let lastCharacter = input[lastIndex];
function palTest(string) {
let j = string[lastIndex];
if (string.length % 2 === 0 )
{
for (i = 0; i <= string.length / 2; i++) {
if (string[i] === string[j]) {
j--;
return true;
} else {
return false;
}
}
} else {
let middleCharacter = (string.length + 1) / 2;
for (i = 0; i <= ((string.length + 1) / 2) - 1; i++) {
if (string[i] === string[j] && middleCharacter == "a" || "e" || "i" || "o" || "u" ) {
j--;
return true;
} else {
return false;
}
}
}
}
let x = palTest(input);
console.log(x); // false
console.log(input[0]); // h
console.log(input[1]); // a
console.log(input[2]); // n
console.log(input[3]); // n
console.log(input[4]); // a
console.log(input[5]); // h
Inside the for loop on the first loop, hannah[i] is, I think, 0 instead of "h": so it's comparing 0 to "h" (hannah[j]) and returning false?
You need to decrement lastIndex instead of value at last index
function palTest(string) {
var lastIndex = string.length - 1; //initialize lastIndex here
let j = string[lastIndex];
if (string.length % 2 === 0) {
for (i = 0; i <= string.length / 2; i++) {
if (string[i] === string[lastIndex]) { //compare with lastIndex
lastIndex--; //decrement last index
return true;
} else {
return false;
}
}
} else {
let middleCharacter = (string.length + 1) / 2;
for (i = 0; i <= ((string.length + 1) / 2) - 1; i++) {
if (string[i] === string[lastIndex] && middleCharacter == "a" || "e" || "i" || "o" || "u") {
lastIndex--;
return true;
} else {
return false;
}
}
}
}
console.log( palTest("hannah") );
console.log( palTest("hantnah") );
console.log( palTest("Not a palindrome") );
A less verbose method could be
var input = "hannah";
var fnCheckPal = ( input ) => input == input.split( "" ).reverse().join("");
Demo
var fnCheckPal = (input) => input == input.split("").reverse().join("");
console.log( fnCheckPal( "hannah" ) );
console.log( fnCheckPal( "hantnah" ) );
console.log( fnCheckPal( "hann33ah" ) );
I would suggest simplifying your logic a bit, as you only need one loop, one variable and no global stored things for this. Just loops once, check if the current index equals the same index from the end and if it's not, it's not a palindrome. Even or uneven amount of letters don't even make a difference here:
function testPalindrome( string ){
for( let i = 0; i < string.length / 2; i++ ){
if( string[ i ] !== string[ string.length - 1 - i ] ){
return false;
};
}
return true;
}
console.log( testPalindrome( 'hannah' ) ); // true
console.log( testPalindrome( 'aba' ) ); // true
console.log( testPalindrome( 'stackoverflow' ) ); // false
Some thoughts:
no need to differ of strings with odd or even length, by using an approach with counting from start and from end,
only one loop,
take the index until the middle of the string,
check if unequal then exit function with false,
if end of function is reached, return with true, because the string is a palindrome.
function palTest(string) {
var i, l;
for (i = 0, l = Math.floor(string.length / 2); i < l; i++) {
if (string[i] !== string[string.length - 1 - i]) {
return false;
}
}
return true;
}
console.log(palTest('hannah'));
console.log(palTest('foo'));
BTW, a check with this pattern,
middleCharacter == "a" || "e" || "i" || "o" || "u"
checks only the first part with the comparison and if not true, the next string "e" is taken as truthy value as return value of the condition.
At all, there happens no real check.
I need to decode base36 string to double. The actual double value is 0.3128540377812142. Now when I am converting it to base 36:
(0.3128540377812142).toString(36);
Results are :
Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi
Firefox: 0.b9ginb6s73e
Now my question is:
1) Is there any way to get same base 36 result for all browsers ?
2) How to decode them back to double value ?
For converting from string (up to base 36) to a number you can use this.
String.prototype.toNumber = function(base) {
var resultNumber = 0;
var inMantissa = false;
var mantissaDivisor;
var currentCharCode;
var digitValue;
if (typeof base === "undefined" || base === "" || base === null) {
base = 10;
}
base = parseInt(base);
if (isNaN(base) || base > 36 || base < 2) {
return NaN;
}
for(var i=0; i<this.length; i++) {
currentCharCode = this.charCodeAt(i);
if (currentCharCode === 46 && !inMantissa) {
// we're at the decimal point
inMantissa = true;
mantissaDivisor = 1;
} else {
if (currentCharCode >= 48 && currentCharCode <= 57) {
// 0-9
digitValue = currentCharCode - 48;
} else if (currentCharCode >= 65 && currentCharCode <= 90) {
// A-Z
digitValue = currentCharCode - 55;
} else if (currentCharCode >= 97 && currentCharCode <= 122) {
// a-z
digitValue = currentCharCode - 87;
} else {
return NaN;
}
if (digitValue > base - 1) {
return NaN;
}
if (inMantissa) {
mantissaDivisor *= base;
resultNumber += digitValue/mantissaDivisor;
} else {
resultNumber = (resultNumber * base) + digitValue;
}
}
}
return resultNumber;
}
Here's a fiddle: http://jsfiddle.net/ugshkp4d/25/
i have to convert alphabets to corresponding numbers like i have a data like "DRSG004556722000TU77" and the index for A is 10, B is 11, C is 12 and so on up to Z is 35.
any helping tips??
here is the javascript which return me ascii code but i want to get the above indecies for respective alphabet
var string = DRSG004556722000TU77;
function getColumnName(string) {
return ((string.length - 1) * 26) + (string.charCodeAt(string.length - 1) - 64);
}
document.write( getColumnName(string) );
This may help
var output = [], code, str = 'DRSG004556722000TU77',i;
for(i in str){
code = str.charCodeAt(i);
if(code <= 90 && code >= 65){
// Add conditions " && code <= 122 && code >= 97" to catch lower case letters
output.push([i,code]);
}
}
Now ouput contains all letters codes and their corresponding indexes
var string = 'DRSG004556722000TU77';
function getColumnName(string) {
var recode = new Array(), i, n = string.length;
for(i = 0; i < n; i++) {
recode.push(filter(string.charCodeAt(i)));
}
return recode;
}
function filter(symbol) {
if ((symbol >= 65) && (symbol <= 90)) {
return symbol - 55;
} else if ((symbol >= 48) && (symbol <= 57)) {
return symbol - 48;
}
}
document.write(getColumnName(string));