How can I convert charCode to the actual letter/digit/symbol that was typed?
I mean if A is typed on a keyboard the result on PHP should be the letter A and not the charCode for A.
var ucode = function(s) {
var len = s.length;
var rs = "";
for ( var i = 0; i < len; i++) {
var k = s.substring(i, i + 1);
rs += "$" + (s.charCodeAt(i) + "1") + ";";
}
return rs;
};
if s is string, you can use String.prototype.slice and change your line of code like something below
var ucode = function(s) {
var len = s.length;
var rs = "";
for ( var i = 0; i < len; i++) {
rs += s.slice(i);
}
return rs;
};
Related
I want reverse the string with the same order. We should not use the Array functions like split(), .reverse() and .join(). but we can use array.length.
Here i am attached my code. How to achieve that thing more efficiently.
var str = "i am javascript";
// result "i ma tpircsavaj"
function reverseString(myStr){
var strlen = myStr.length, result = "", reverseStr = "", reverseStrArr = [];
for(var i = strlen-1; i >= 0; i--){
reverseStr += myStr[i];
}
for(var j = 0; j < strlen; j++){
if(reverseStr[j] == " "){
reverseStrArr.push(result);
result = "";
}else{
result += reverseStr[j];
if(j + 1 == strlen){
reverseStrArr.push(result);
result = "";
}
}
}
for(var k=reverseStrArr.length - 1; k >= 0; k--){
result += reverseStrArr[k] + " "
}
console.log(result);
}
reverseString(str);
Use 2 pointers: i to indicate the current position and j to indicate the start index of the current word. Add the reversed of current word char by char when space.
Don't be fooled by the nested loops, the complexity is the same as yours: O(n) and somehow cleaner for me.
var string = "i love javascript and the whole world!"
var result = ""
var i = j = 0
var l = string.length
while (i++ < l) {
var k = i
if (string[i] === " " || (i === l - 1) && k++) {
while (--k >= j) result += string[k]
j = i + 1
result += " "
}
}
result = result && result.slice(0, -1) || ""
console.log(result)
You could take a loop, collect the characters of a word and reverse the word.
function reverse(string) {
var reversed = '';
while (reversed.length !== string.length) {
reversed = string[reversed.length] + reversed;
}
return reversed;
}
var string = "i am javascript",
temp = '',
result = '',
i = 0;
while (i < string.length) {
if (string[i] === ' ') {
result += (result && ' ') + reverse(temp);
temp = '';
} else {
temp += string[i];
}
i++;
}
if (temp) result += (result && ' ') + reverse(temp);
console.log(result);
An approach from the end.
function reverse(string) {
var reversed = '';
while (reversed.length !== string.length) {
reversed = string[reversed.length] + reversed;
}
return reversed;
}
var string = "i am javascript",
temp = '',
result = '',
i = string.length;
while (i--) {
if (string[i] === ' ') {
result = ' ' + reverse(temp) + result;
temp = '';
} else {
temp = string[i] + temp;
}
}
if (temp) result = reverse(temp) + result;
console.log(result);
function reverseStr(str) {
var ret = "";
for (var i = 0; i < str.length; i++) {
ret = str[i] + ret;
}
return ret;
}
function doIt(str) {
var ret = "", cur = "";
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (c == ' ' || c == '.') {
ret += reverseStr(cur) + c;
cur = "";
} else {
cur += c;
}
}
ret += reverseStr(cur);
return ret;
}
console.log(doIt('Reverse the word in a string with the same order in javascript without using the array functions except .length'));
function reverse(word) {
if (word.length > 1) {
var newWord = '';
for (j = word.length-1; j >= 0; j--) {
newWord += word[j];
}
return newWord + ' ';
} else {
return word + ' ';
}
}
var text = "i am javascript";
var words = text.split(' ');
var result = '';
for (i = 0; i < words.length; i++) {
result += reverse(words[i]);
}
console.log(result);
I have been working on reverse engineering some code for a couple days and I've gotten quite stuck. It's basically just a logic problem that I can't wrap my min around, me and my partner are both stuck on this.
The setup:
function decrypt(s) {
var r = "";
var tmp = s.split("9812265");
s = unescape(tmp[0]);
k = "4849604567466";
var temp, temp2, temp3, tempf;
for( var i = 0; i < s.length; i++) {
temp = parseInt(k.charAt(i%k.length));
temp2 = s.charCodeAt(i);
temp3 = (temp^temp2)-3;
tempf = String.fromCharCode(temp3);
r += tempf;
}
return r;
}
I have this function, and the loop is what we can't reverse. What is meant to happen is to turn HTML into a bunch of characters then escape those characters. I wrote a method that can escape any string, so that part is easy. The loop that preforms the change is just to hard of a logic problem for me.
function encrypt(output)
{
var SecretNumber = "4849604";
var returnValue = "";
for(var n = 0; n < output.length; n++)
{
returnValue += String.fromCharCode(parseInt(SecretNumber.charAt(n%SecretNumber.length))^(output[n].charCodeAt(0))+3);
}
return escapeAny(returnValue) + 9812265 + (escapeAny(SecretNumber));
}
Paired with the function for escaping string mentioned earlier:
function escapeAny(string)
{
var list1 = [];
var list2 = [];
for(i = 16; i < 255; i++)
{
list1[i-16] = ("%" + i.toString(16).toString());
list2[i-16] = (unescape(list1[i-16]));
}
var charAr = string.split('');
var newChat = [];
for(i = 0; i < charAr.length; i++)
{
var currentChar = charAr[i];
var charNumber = list2.indexOf(currentChar);
var ret = list1[charNumber];
newChat[i] = ret;
}
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
return newChat.join().replaceAll(",", "");
}
This solution seems to have worked well.
i have the below Javascript code i need to convert to C#
function obfuscateApiKey(timestamp, key) {
var high = timestamp.substring(timestamp.length - 6);
var low = (parseInt(high) >> 1).toString();
var apiKey = "";
while (low.length < 6) {
low = "0" + low;
}
for (var i = 0; i < high.length; i++) {
apiKey += key.charAt(parseInt(high.charAt(i)));
}
for (var j = 0; j < low.length; j++) {
apiKey += key.charAt(parseInt(low.charAt(j)) + 2);
}
console.log(apiKey)
return apiKey;
}
I have started the conversion below in C# but i am stuck at converting
apiKey += key.charAt(parseInt(high.charAt(i)));
var timestamp = DateTime.Now.ToString();
var high = timestamp.Substring(timestamp.Length - 6);
var low = (Int32.Parse(high) >>1).ToString();
while (low.Length < 6)
{
low = "0" + low;
}
for (var i = 0; i < high.Length; i++)
{
char ch = (int.Parse(high)[i]); //Getting stuck here! < this is incorrect.
}
you got it wrong at (high)[i] try high[i] you are converting char to int and then assign it to char.
var apiKey = "";
var timestamp = DateTime.Now.ToString();
var high = timestamp.Substring(timestamp.Length - 6);
var low = (Int32.Parse(high) >>1).ToString();
while (low.Length < 6)
{
low = "0" + low;
}
for (var i = 0; i < high.Length; i++)
{
apiKey += high[i];
}
and for your comment char ch = low[j] + 2
apiKey += (Convert.ToInt32(low[j]) + 2).ToString();
I need string Double each letter in a string
abc -> aabbcc
i try this
var s = "abc";
for(var i = 0; i < s.length ; i++){
console.log(s+s);
}
o/p
> abcabc
> abcabc
> abcabc
but i need
aabbcc
help me
Use String#split , Array#map and Array#join methods.
var s = "abc";
console.log(
// split the string into individual char array
s.split('').map(function(v) {
// iterate and update
return v + v;
// join the updated array
}).join('')
)
UPDATE : You can even use String#replace method for that.
var s = "abc";
console.log(
// replace each charcter with repetition of it
// inside substituting string you can use $& for getting matched char
s.replace(/./g, '$&$&')
)
You need to reference the specific character at the index within the string with s[i] rather than just s itself.
var s = "abc";
var out = "";
for(var i = 0; i < s.length ; i++){
out = out + (s[i] + s[i]);
}
console.log(out);
I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.
var s = "abcdef";
function makeDoubles(s){
var s1 = "";
for(var i=0; i<s.length; i++){
s1 += s[i]+s[i];
}
return s1;
}
alert(makeDoubles(s));
if you want to make it with a loop, then you have to print s[i]+s[i];
not, s + s.
var s = "abc";
let newS = "";
for (var i = 0; i < s.length; i++) {
newS += s[i] + s[i];
}
console.log(newS);
that works for me, maybe a little bit hardcoded, but I am new too))
good luck
console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.
var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
r+= c+c
}
console.log(r)
var doubleStr = function(str) {
str = str.split('');
var i = 0;
while (i < str.length) {
str.splice(i, 0, str[i]);
i += 2;
}
return str.join('');
};
You can simply use one of these two methods:
const doubleChar = (str) => str.split("").map(c => c + c).join("");
OR
function doubleChar(str) {
var word = '';
for (var i = 0; i < str.length; i++){
word = word + str[i] + str[i];
};
return word;
};
function doubleChar(str) {
let sum = [];
for (let i = 0; i < str.length; i++){
let result = (str[i]+str[i]);
sum = sum + result;
}
return sum;
}
console.log (doubleChar ("Hello"));
I wrote the following function to find the longest palindrome in a string. It works fine but it won't work for words like "noon" or "redder". I fiddled around and changed the first line in the for loop from:
var oddPal = centeredPalindrome(i, i);
to
var oddPal = centeredPalindrome(i-1, i);
and now it works, but I'm not clear on why. My intuition is that if you are checking an odd-length palindrome it will have one extra character in the beginning (I whiteboarded it out and that's the conclusion I came to). Am I on the right track with my reasoning?
var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
UPDATE:
After Paul's awesome answer, I think it makes sense to change both variables for clarity:
var oddPal = centeredPalindrome(i-1, i + 1);
var evenPal = centeredPalindrome(i, i+1);
You have it backwards - if you output the "odd" palindromes (with your fix) you'll find they're actually even-length.
Imagine "noon", starting at the first "o" (left and right). That matches, then you move them both - now you're comparing the first "n" to the second "o". No good. But with the fix, you start out comparing both "o"s, and then move to both "n"s.
Example (with the var oddPal = centeredPalindrome(i-1, i); fix):
var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i + 1);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > 1)
console.log("oddPal: " + oddPal);
if (evenPal.length > 1)
console.log("evenPal: " + evenPal);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
console.log(
longestPalindrome("nan noon is redder")
);
This will be optimal if the largest palindrome is found earlier.
Once its found it will exit both loops.
function isPalindrome(s) {
//var rev = s.replace(/\s/g,"").split('').reverse().join(''); //to remove space
var rev = s.split('').reverse().join('');
return s == rev;
}
function longestPalind(s) {
var maxp_length = 0,
maxp = '';
for (var i = 0; i < s.length; i++) {
var subs = s.substr(i, s.length);
if (subs.length <= maxp_length) break; //Stop Loop for smaller strings
for (var j = subs.length; j >= 0; j--) {
var sub_subs = subs.substr(0, j);
if (sub_subs.length <= maxp_length) break; // Stop loop for smaller strings
if (isPalindrome(sub_subs)) {
maxp_length = sub_subs.length;
maxp = sub_subs;
}
}
}
return maxp;
}
Here is another take on the subject.
Checks to make sure the string provided is not a palindrome. If it is then we are done. ( Best Case )
Worst case 0(n^2)
link to
gist
Use of dynamic programming. Break each problem out into its own method, then take the solutions of each problem and add them together to get the answer.
class Palindrome {
constructor(chars){
this.palindrome = chars;
this.table = new Object();
this.longestPalindrome = null;
this.longestPalindromeLength = 0;
if(!this.isTheStringAPalindrome()){
this.initialSetupOfTableStructure();
}
}
isTheStringAPalindrome(){
const reverse = [...this.palindrome].reverse().join('');
if(this.palindrome === reverse){
this.longestPalindrome = this.palindrome;
this.longestPalindromeLength = this.palindrome.length;
console.log('pal is longest', );
return true;
}
}
initialSetupOfTableStructure(){
for(let i = 0; i < this.palindrome.length; i++){
for(let k = 0; k < this.palindrome.length; k++){
this.table[`${i},${k}`] = false;
}
}
this.setIndividualsAsPalindromes();
}
setIndividualsAsPalindromes(){
for(let i = 0; i < this.palindrome.length; i++){
this.table[`${i},${i}`] = true;
}
this.setDoubleLettersPlaindrome();
}
setDoubleLettersPlaindrome(){
for(let i = 0; i < this.palindrome.length; i++){
const firstSubstring = this.palindrome.substring(i, i + 1);
const secondSubstring = this.palindrome.substring(i+1, i + 2);
if(firstSubstring === secondSubstring){
this.table[`${i},${i + 1}`] = true;
if(this.longestPalindromeLength < 2){
this.longestPalindrome = firstSubstring + secondSubstring;
this.longestPalindromeLength = 2;
}
}
}
this.setAnyPalindromLengthGreaterThan2();
}
setAnyPalindromLengthGreaterThan2(){
for(let k = 3; k <= this.palindrome.length; k++){
for(let i = 0; i <= this.palindrome.length - k; i++){
const j = i + k - 1;
const tableAtIJ = this.table[`${i+1},${j-1}`];
const stringToCompare = this.palindrome.substring(i, j +1);
const firstLetterInstringToCompare = stringToCompare[0];
const lastLetterInstringToCompare = [...stringToCompare].reverse()[0];
if(tableAtIJ && firstLetterInstringToCompare === lastLetterInstringToCompare){
this.table[`${i},${j}`] = true;
if(this.longestPalindromeLength < stringToCompare.length){
this.longestPalindrome = stringToCompare;
this.longestPalindromeLength = stringToCompare.length;
}
}
}
}
}
printLongestPalindrome(){
console.log('Logest Palindrome', this.longestPalindrome);
console.log('from /n', this.palindrome );
}
toString(){
console.log('palindrome', this.palindrome);
console.log(this.table)
}
}
// const palindrome = new Palindrome('lollolkidding');
// const palindrome = new Palindrome('acbaabca');
const palindrome = new Palindrome('acbaabad');
palindrome.printLongestPalindrome();
//palindrome.toString();
function longestPalindrome(str){
var arr = str.split("");
var endArr = [];
for(var i = 0; i < arr.length; i++){
var temp = "";
temp = arr[i];
for(var j = i + 1; j < arr.length; j++){
temp += arr[j];
if(temp.length > 2 && temp === temp.split("").reverse().join("")){
endArr.push(temp);
}
}
}
var count = 0;
var longestPalindrome = "";
for(var i = 0; i < endArr.length; i++){
if(count >= endArr[i].length){
longestPalindrome = endArr[i-1];
}
else{
count = endArr[i].length;
}
}
console.log(endArr);
console.log(longestPalindrome);
return longestPalindrome;
}
longestPalindrome("abracadabra"));
let str = "HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE";
let rev = str.split("").reverse().join("").trim();
let len = str.length;
let a="";
let result = [];
for(let i = 0 ; i < len ; i++){
for(let j = len ; j > i ; j--){
a = rev.slice(i,j);
if(str.includes(a)){
result.push(a);
break;
}
}
}
result.sort((a,b) => { return b.length - a.length})
let logPol = result.find((value)=>{
return value === value.split('').reverse().join('') && value.length > 1
})
console.log(logPol);
function longest_palindrome(s) {
if (s === "") {
return "";
}
let arr = [];
let _s = s.split("");
for (let i = 0; i < _s.length; i++) {
for (let j = 0; j < _s.length; j++) {
let word = _s.slice(0, j + 1).join("");
let rev_word = _s
.slice(0, j + 1)
.reverse()
.join("");
if (word === rev_word) {
arr.push(word);
}
}
_s.splice(0, 1);
}
let _arr = arr.sort((a, b) => a.length - b.length);
for (let i = 0; i < _arr.length; i++) {
if (_arr[arr.length - 1].length === _arr[i].length) {
return _arr[i];
}
}
}
longest_palindrome('bbaaacc')
//This code will give you the first longest palindrome substring into the string
var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i + 1);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > 1)
console.log("oddPal: " + oddPal);
if (evenPal.length > 1)
console.log("evenPal: " + evenPal);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
console.log(longestPalindrome("n"));
This will give wrong output so this condition need to be taken care where there is only one character.
public string LongestPalindrome(string s) {
return LongestPalindromeSol(s, 0, s.Length-1);
}
public static string LongestPalindromeSol(string s1, int start, int end)
{
if (start > end)
{
return string.Empty;
}
if (start == end)
{
char ch = s1[start];
string s = string.Empty;
var res = s.Insert(0, ch.ToString());
return res;
}
if (s1[start] == s1[end])
{
char ch = s1[start];
var res = LongestPalindromeSol(s1, start + 1, end - 1);
res = res.Insert(0, ch.ToString());
res = res.Insert(res.Length, ch.ToString());
return res;
}
else
{
var str1 = LongestPalindromeSol(s1, start, end - 1);
var str2 = LongestPalindromeSol(s1, start, end - 1);
if (str1.Length > str2.Length)
{
return str1;
}
else
{
return str2;
}
}
}
This is in JS ES6. much simpler and works for almost all words .. Ive tried radar, redder, noon etc.
const findPalindrome = (input) => {
let temp = input.split('')
let rev = temp.reverse().join('')
if(input == rev){
console.log('Palindrome', input.length)
}
}
//i/p : redder
// "Palindrome" 6