i want to ask how to manipulate char in string depends on giving value
my string
"---x---x---x------x"
when im input a value = 2
char "x" was changed to "o" in 2 times
my expected value is
"---o---o---x------x"
thank you in advance
based on solution here:
var str = "---x---x---x------x"
var n = 0
var N = 2
var newStr = str.replace(/x/g,s => n++<N ? 'o' : s)
const x = "---x---x---x------x";
let input = 2;
let output = [];
for (const dashes of x.split("x")) {
output.push(dashes);
if (input > 0) {
input--;
output.push("o");
} else {
output.push("x");
}
}
output.pop();
output = output.join("");
console.log({ output });
You can just loop over the and replace x with o until value becomes 0(which is falsy value)
let str = "---x---x---x------x";
let value = 2;
while (value--) {
str = str.replace("x", "o");
}
console.log(str);
Related
My problem is that replace only first character from last13 array.
I want replace all character from var last13 to first13
var first13 = first13Letter.map(x=>x).join(',');
var last13 = last13Letter.map(y=>y).join(',');
my code
function rot13(str) {
var first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];
var last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var first13 = first13Letter.map(x=>x).join(',');
var last13 = last13Letter.map(y=>y).join(',');
for(let i=0; i<first13.length; i++){
if(str.indexOf(first13[i]) !== -1){
str = str.replace(first13[i],last13[i])
}else{
str = str.replace(last13[i],first13[i]) // i want to replace all letter from last13 to first13 letter but this replace only first letter.
}
}
return str;
}
console.log(rot13("SERR YBIR?"))
//output:"FRRR LOVR?"
//expect output: "FREE LOVE?"
What is the error in code above?
function rot13(str) {
const first13Letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M"];
const last13Letter = ["N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
return str.split('')
.map(s => last13Letter.indexOf(s) >= 0 ? first13Letter[last13Letter.indexOf(s)] :
first13Letter.indexOf(s) >= 0 ? last13Letter[first13Letter.indexOf(s)] : s)
.join('')
}
console.log(rot13("SERR YBIR?"))
Write a function that returns an integer indicating number of times a group of string "pzmcb" appears in a string in no particualr orther. for example
input string 1 -> "abdpsclmhz"
output 1 -> 1
input string 2 : pzmcbcbpzmpcm
output 2: 2
I have written the code but it is not efficient and cannot handle large input string. I will appreciate it if an efficent way of writing this function can be provided
'use strict';
//pmzcbpmzcbpmz [0 -4] [5 - 9] returns 2
function matchGroup(word) {
let regex = /[pzmcb]/g
let stringArray = word.match(regex);
//console.log(stringArray);
let cloneArray = [...stringArray];
let stored = [];
let searchString = "";
let secondString = "";
let temp = "";
let tempArray = [];
stringArray.forEach(item => {
if (cloneArray.indexOf(item) >= 0 && searchString.indexOf(item) === -1) {
searchString += item;
if (searchString.length === 5) {
stored.push(searchString);
searchString = "";
}
} else if(secondString.indexOf(item) === -1){
secondString += item;
if (secondString.length === 5) {
stored.push(searchString);
secondString = "";
}
}else {
temp += item;
if (temp.length === 5) {
tempArray.push(temp);
temp = "";
}
}
});
return stored.length;
// return integer
}
var paragraph = 'pzmcbpdfbcmz';
let result = matchGroup("abcdefpfklmhgzpzmcbpdfbcmzjklmoplzdsaklmcxheqgexcmpzdhgiwqertyhgdsbnmkjilopazxcsdertijuhgbdmlpoiqarstiguzcmnbgpoimhrwqasfgdhuetiopmngbczxsgreqad");
console.log(result);
I expect that the matchGroup function to return exact integers for large inputs
I'd build up a map of character counts:
function countChars(str) {
const count = {};
for(const char of str) count[char] = (count[char] || 0) + 1;
return count;
}
Now we can easily build up count maps of the string to find and the source:
const toFind = countChars("pzmbc"),
source = countChars("pzmcbpdfbcmz");
Now we can find the smallest relationship of chars to find and chars that are there:
const result = Math.min(
...Object.entries(toFind).map(([char, need]) => Math.floor((source[char] || 0) / need))
);
function countChar(char, string) {
return (string.match(new RegExp(char, "g")) || []).length;
}
function countDistinctSubstring(sub, string) {
firstChars = {};
for (i = 0; i < sub.length; i++) {
if (sub[i] in firstChars)
firstChars[sub[i]]++;
else
firstChars[sub[i]] = 1;
}
return Math.min(...Object.keys(firstChars).map(key => Math.floor(countChar(key, string) / firstChars[key])));
}
> countDistinctSubstring("pzmcb", "abdpsclmhz");
< 1
> countDistinctSubstring("pzmcb", "pzmcbcbpzmpcm");
< 2
> countDistinctSubstring("pzmcbpdfbcmz", "abcdefpfklmhgzpzmcbpdfbcmzjklmoplzdsaklmcxheqgexcmpzdhgiwqertyhgdsbnmkjilopazxcsdertijuhgbdmlpoiqarstiguzcmnbgpoimhrwqasfgdhuetiopmngbczxsgreqad");
< 3
I can't tell for sure, but I think this is what you are looking for. It counts the number of occurrences of each letter in the small string, then finds the minimum ratio of occurrences in the large string to those in the small string for each character. This minimum ratio is the maximum number of distinct times the small string can be composed of letters from the larger one.
Note that this answer was used in making the countChar function.
fs.readFile('./input.txt', (error, data) => {
if(error)
console.log(error);
const input = data.toString();
const dataArray = input.split(/[\n\r ]+/);
const lastItem = dataArray.length;
let accumulator = 0;
let counter = 0;
for(let i=0; i<lastItem-1; i++) {
let tempArray = dataArray[i];
let splitArray = tempArray.split('x');
let a = splitArray[0];//length
let b = splitArray[1];//width
let c = splitArray[2];//height
let d = a<b? (b<c?c:b) : (a<c?c:a);
let output = 0;
if(d === a)
output = (2*b + 2*c + a*b*c);
else if(d === b)
output = (2*a + 2*c + a*b*c);
else
output = (2*b + 2*a + a*b*c);
accumulator += output;
}})
Input:
3x11x24
13x5x19
1x9x27
This is my code and input. And I want to know why I'm getting wrong comparisons to get the 'd' number. I want 'd' to be the biggest of every 3 numbers in input.
And what is really strange for me is when i want to console.log(a < b) first input which should be true ( because 3 is less than 11 ) but gives me false and I cannot assign any good value to 'd' because I don't know what am I doing wrong with my comparisons.(and I'm using node to execute my code if that gives you any clue what is wrong) Please help :(
In your code a,b,c are strings. You're splitting a string, and you get a string as a result. You need to cast to a number.
let a = +splitArray[0];//length
let b = +splitArray[1];//width
let c = +splitArray[2];
Will cast the string into a number and your comparisons will work
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 1));
}
if (/[aeiou]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 26));
}
}
return str;
}
When I call LetterChanges("hello"), it returns 'Ifmmp' which is correct, but when "sent" is passed it returns 'ufOt' instead of 'tfOu'. Why is that?
str.replace() replaces the first occurrence of the match in the string with the replacement. LetterChanges("sent") does the following:
i = 0 : str.replace("s", "t"), now str = "tent"
i = 1 : str.replace("e", "f"), now str = "tfnt"
i = 2 : str.replace("n", "o"), now str = "tfot", then
str.replace("o", "O"), now str = "tfOt"
i = 3 : str.replace("t", "u"), now str = "ufOt"
return str
There are several issues. The main one is that you could inadvertently change the same letter several times.
Let's see what happens to the s in sent. You first change it to t. However, when it comes to changing the final letter, which is also t, you change the first letter again, this time from t to u.
Another, smaller, issue is the handling of the letter z.
Finally, your indexing in the second if is off by one: d becomes D and not E.
You can use String.replace to avoid that:
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode(c.charCodeAt(0)+1);
}).replace(/[aeiou]/g, function(c){
return c.toUpperCase();
});
}
But there is still a bug: LetterChanges('Zebra') will return '[fcsb'. I assume that is not your intention. You will have to handle the shift.
Try this one:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
var temp;
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
//str = str.replace(str[i], alphabet.charAt(index + 1));
temp= alphabet.charAt(index + 1);
index = index+1;
}
else if(str[i] == ' '){
temp = ' ';
}
if (/[aeiou]/.test(temp)) {
temp = alphabet.charAt(index + 26);
}
result += temp;
}
return result;
}
var str = 'bcd12';
str = str.replace(/[a-z]/gi, function(char) { //call replace method
char = String.fromCharCode(char.charCodeAt(0)+1);//increment ascii code of char variable by 1 .FromCharCode() method will convert Unicode values into character
if (char=='{' || char=='[') char = 'a'; //if char values goes to "[" or"{" on incrementing by one as "[ ascii value is 91 just after Z" and "{ ascii value is 123 just after "z" so assign "a" to char variable..
if (/[aeiuo]/.test(char)) char = char.toUpperCase();//convert vowels to uppercase
return char;
});
console.log(str);
Check this code sample. There is no bug in it. Not pretty straight forward but Works like a charm. Cheers!
function LetterChanges(str) {
var temp = str;
var tempArr = temp.split("");//Split the input to convert it to an Array
tempArr.forEach(changeLetter);/*Not many use this but this is the referred way of using loops in javascript*/
str = tempArr.join("");
// code goes here
return str;
}
function changeLetter(ele,index,arr) {
var lowerLetters ="abcdefghijklmnopqrstuvwxyza";
var upperLetters ="ABCDEFGHIJKLMNOPQRSTUVWXYZA";
var lowLetterArr = lowerLetters.split("");
var upLetterArr = upperLetters.split("");
var i =0;
for(i;i<lowLetterArr.length;i++){
if(arr[index] === lowLetterArr[i]){
arr[index] = lowLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
if(arr[index] === upLetterArr[i]){
arr[index] = upLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
}
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LetterChanges(readline());
Javascript:
var validate(s) = s.match ^( 100(?:\.0{1,2})? | 0*?\.\d{1,2} | \d{1,2}(?:\.\d {1,2})? )% $ != null;
var str = value.match(/\/\/%//g);
if(converted==NaN){
alert('Input was not a number');
}
else if(converted != null) {
var fracToDecimal = eval (value);
alert(fracToDecimal);
}
else if(converted = str) {
var percToDecimal = value/100;
alert(percToDecimal);
} }
So you have a string like: 50%? How about:
var percent = "50%";
var result = parseFloat(percent) / 100.0;
If you use parseFloat, it will read the string up until the first non-number character (the %)
var x = '20.1%';
var y = parseFloat(x); // 20.1
Then you can check if it's NaN, and convert it.
if(!isNaN(y)){
y /= 100; // .201
}
Note: You need to use isNaN because NaN === NaN is false (JavaScript is weird).
UPDATE: I see you also have fracToDecimal in there. You don't need eval for that. Just do a simple split.
var frac = '1/2';
var nums = frac.split('/');
var dec = nums[0]/nums[1];
Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100
http://jsfiddle.net/TrCYX/1/
I'm very late, but keeping it as itself if it is a decimal goes like this
let val = "100%"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
val = 1 //or val = "1"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
function convertToDecimal(percent) {
let newarr =[]
for(i=0; i<percent.length; i++) {
const parsed = parseFloat(percent[i]);
if (!Number.isNaN(parsed[i])) {
let newval = parseFloat(percent[i]) / 100;
//return newval;
newarr.push(newval)
} else {
return 0;
}
} return newarr;
}
console.log(convertToDecimal(["33%", "98.1%", "56.44%", "100%"]))