Match part of a String with a part of another String - javascript

so this is my problem:
i have 2 Strings "myTestTomorrow" and "ThisIsmyTesttoday". I need to get the part which both strings contain, in this case "myTest". How can i do this?

You can do this with two for loops and indexOf, like this
var text1 = "myTestTomorrow", text2 = "ThisIsmyTesttoday";
outer: for (var i = text1.length; i >= 0; i -= 1) {
for (var j = 0; j + i < text1.length; j += 1) {
if (text2.indexOf(text1.substr(j, i)) !== -1) {
console.log("Result is '" + text1.substr(j, i) + "'");
break outer;
}
}
}
Output
Result is 'myTest'

Related

Why the Double mirror pascal star pattern is not printed?

Here is the my javascript code for printing the pattern shown below in the image.
please check the code and solve the error.
<script>
var n = prompt("Enter the number of n you want to print");
//rows = Math.floor(n / 2)
let str = ""
var i, j, k
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
str += "*"
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(j = 1; j <= i; j++){
str += "*"
}
str += "\n"
}
for(i = 1; i <=n + 2; i++){
for(j = n + 2; j > i; j--){
str += "*"
}
for(k = 1; k <= i; k++){
str = " "
}
for(k = 1; k <= i; k++){
str = " "
}
for(j = n + 2; j > i; j--){
str += "*"
}
str += "\n"
}
console.log(str)
</script>
I want Output like this :
but I got just 2 spaces in output
Convert your input to Number:
n = Number(n);
and then change your code as #TomLV mentioned:
var n = prompt("Enter the number of n you want to print");
//rows = Math.floor(n / 2)
n = Number(n);
let str = ""
var i, j, k
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
str += "*"
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(j = 1; j <= i; j++){
str += "*"
}
str += "\n"
}
for(i = 1; i <=n + 2; i++){
for(j = n + 2; j > i; j--){
str += "*"
}
for(k = 1; k <= i; k++){
str += " "
}
for(k = 1; k <= i; k++){
str += " "
}
for(j = n + 2; j > i; j--){
str += "*"
}
str += "\n"
}
console.log(str)
You are setting str equal to " " in both "k loops" in the second "i for loop".
e.g:
for(k = 1; k <= i; k++){
str = " "
}
for(k = 1; k <= i; k++){
str = " "
}
If you update those to += it works.
Some issues:
prompt returns a string, you need to convert it to a number. You can use the unary plus for that.
str = " " occurs at two places where you should have done str += " "
The generated pattern has two spaces in the center line, while you are asked to only have one space there. To make that happen have the k loops make one iteration less, and add str += " " as a separate statement outside of those loops.
The output has an empty line at the very end. This is because the second i loop is making one iteration too many.
Not a problem, but:
Use semi-colons to separate statements. Although JavaScript provides automatic semi-colon insertion, you wouldn't be the first to fall into one of the pitfalls. It is better to take control of this yourself and have the habit of adding the semi-colons.
There really is no need here to declare loop variables at the top. Just declare them at the moment you need them with only the scope they need to have.
I'll assume that the number of lines in the output is supposed to be n*2+1 and that there was no error concerning that aspect.
Corrected code:
// Convert string to number using unary plus:
const n = +prompt("Enter the number of n you want to print");
let str = "";
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= i; j++) {
str += "*";
}
// Reduced the number of iterations here:
for (let k = n; k >= i; k--) {
str += " ";
}
// Add one space for the center column
// that is the only column without asterisks
str += " ";
// Reduced the number of iterations here:
for (let k = n; k >= i; k--) {
str += " ";
}
for (let j = 1; j <= i; j++) {
str += "*";
}
str += "\n";
}
// Reduced number of iterations. i should not become equal to n + 2
for (let i = 1; i <= n + 1; i++) {
for (let j = n + 2; j > i; j--) {
str += "*";
}
// Reduced the number of iterations here:
for (let k = 1; k < i; k++) {
str += " "; // Fixed assignment
}
// Add one space for the center column
// that is the only column without asterisks
str += " ";
// Reduced the number of iterations here:
for (let k = 1; k < i; k++) {
str += " "; // Fixed assignment
}
for (let j = n + 2; j > i; j--) {
str += "*";
}
str += "\n";
}
console.log(str);
Note that JavaScript has functions that can facilitate this proces, like "*".repeat(i) can be used instead of a loop to produce the same string.
So then it becomes:
const n = +prompt("Enter the number of n you want to print");
let str = "";
for (let i = 1; i <= n + 1; i++) {
str += "*".repeat(i) + " ".repeat(2*n + 3 - 2*i) + "*".repeat(i) + "\n";
}
for (let i = n; i >= 1; i--) {
str += "*".repeat(i) + " ".repeat(2*n + 3 - 2*i) + "*".repeat(i) + "\n";
}
console.log(str);
And you could also reuse the results of the first loop to derive the second half of the output by storing the lines in an array. You can then reverse that array to get the second half (without the middle line):
const n = +prompt("Enter the number of n you want to print");
const arr = Array.from({length: n + 1}, (_, i) =>
"*".repeat(i+1) + " ".repeat(2*(n-i)+1) + "*".repeat(i+1)
);
console.log([...arr, ...arr.reverse().slice(1)].join("\n"));

Troubleshooting Algorithm

Im working on an algorithm to return the provided string with the first letter of each word capitalized. While leaving the rest of the word in lower case. Looking for some insight to why this code isn't working. Thanks.
function titleCase(str) {
let result = "";
let words = str.split(" ");
for(let i = 0; i <= words.length; i++){
let word = words[i];
for(let j = 0; j <= word.length; j++){
if(j === 0){
result += word[j].toUpperCase();
} else{
result += word[j].toLowerCase();
}
}
return result += " "
}
return result.slice(0, result.length - 1)
}
There are three errors in your program, that are stopping it from working:
You need to change i <= words.length to i < words.length (or i <= words.length - 1), since indexes start from 0 in javascript like most
programming languages.
You need to change j <= word.length to j < word.length (or j <= word.length - 1), same reason as above.
You need to not return prematurely, and need to change return result += " " to just result += " ".
Also although it does not stop your function from working you could simplify your return line by utilizing trimEnd.
function titleCase(str) {
let result = "";
let words = str.split(" ");
for (let i = 0; i < words.length; i++) {
let word = words[i];
for (let j = 0; j < word.length; j++) {
if (j === 0) {
result += word[j].toUpperCase();
} else {
result += word[j].toLowerCase();
}
}
result += " "
}
return result.trimEnd();
}
console.log(titleCase("The quick brown fox jumps over the lazy dog"));

Reverse the word in a string with the same order in javascript without using the array functions except .length

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);

Quickest way to achieve this sequence?

I'm trying to create a simple algorithm that builds an array with a dynamic length.
Then, it will, one by one, replace an item, and then two, then three and so on until the only items left are the first and last.
like this:
12345
1*345 // it never touches the first
12*45
123*5 // it doesn't ever touch the last item
1**45
12**5
1***5 // done, nowhere else to go
I put together a simple demo to show what I'm trying to do.
var length = 6,
array = [],
log = document.getElementById("log"),
edited,
j,
i;
for (i = 1; i <= length; i++) {
array.push(i);
}
log.innerHTML += array.join(" ") + "<br><br>";
for (i = 1; i < (length - 1); i++) {
edited = array.concat();
for (j = i; j < (length - 1); j++) {
edited[j] = "*";
log.innerHTML += edited.join(" ") + "<br>";
}
log.innerHTML += "<br>";
}
Fiddle
It works fine, the only problem is it's out of order.
Right now it seems to only iterate by number of asterisks, then by index. I need it to do the opposite.
// it does this
12345
1*345
1**45
1***5
12*45
12**5
123*5 // out of order
If someone could help that would be great because I am really at a loss!
This should get it done.
var a = 6, // array length
b = [], // array
log = document.getElementById("log"),
c,
d,
e;
for (c = 1; c <= a; c++) {
b.push(c);
}
log.innerHTML += b.join(" ") + "<br><br>";
//the size of the asterisk chunk
for(i = 1; i < b.length - 1; i ++)
{
//position to start asterisk chunk
for(j = 1; j < b.length - i; j ++)
{
var tempArr = b.concat();
//the position inside of the asterisk chunk
for(k = 0; k < i; k ++)
{
tempArr[k + j] = "*";
}
log.innerHTML += tempArr.join(" ") + "<br>";
}
}
JSFiddle
This seems to work well:
str = "1234567"
len = str.length;
for(var stars = 1; stars < len - 1; stars++) {
for(var pos = 1; pos < len - stars; pos++) {
var s = str.substr(0, pos)
+ new Array(stars + 1).join("*")
+ str.substr(pos + stars);
document.write(s + "<br>");
}
}

Finding the rank of the Given string in list of all possible permutations with Duplicates

I was trying to find the Rank of the given string in the list of permutations and was hoping someone can find the bug.
function permute() {
var W = $('input').val(),
C = [];
for (var i = 0; i < 26; i++) C[i] = 0;
var rank = 1;
for (var i = 0; i < W.length; i++) {
C[W.charCodeAt(i) - 'a'.charCodeAt(0)]++;
}
var repeated= 1;
for (var i = 0; i < C.length; i++) {
if(C[i] > 0) {
repeated *= fact(C[i]);
}
}
if (W !== '') {
for (var i = 0; i < W.length; i++) {
//How many characters which are not used, that come before current character
var count = 0;
for (var j = 0; j < 26; j++) {
if (j == (W.charCodeAt(i) - 'a'.charCodeAt(0))) break;
if (C[j] > 0) count++;
}
C[W.charCodeAt(i) - 'a'.charCodeAt(0)] = 0;
rank += ( count * fact(W.length - i - 1) );
}
rank = rank/ repeated;
}
var pp = 'Rank of :: ' + W + ' -- ' + rank;
$('div').append('<p>' + pp + '</p>');
}
function fact(n) {
if (n == 0 || n == 1) return 1;
else return fact(n - 1) * n;
}
$('button').click(permute);
Check Fiddle
A use case for this might be
bookkeeper is supposed to give a rank of 10743.
Here's the demo:
For each position check how many characters left have duplicates, and use the logic that if you need to permute n things and if 'a' things are similar the number of permutations is n!/a!

Categories