All strings with length of the longest string - javascript

Hei, I have this function:
function frame(string) {
var words = string.split(" ");
var longestWord = 0;
var y = "*";
//Find the longest word from the string
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord) {
longestWord = words[i].length;
}
}
console.log(y.repeat(longestWord + 4));
for (var i = 0; i < words.length; i++) {
console.log(y + " " + words[i] + " " + y);
//words[i].length = longestWord;
}
console.log(y.repeat(longestWord + 4));
}
I want that all the string has the same length as the longest string. The rest is working good. The code that is commented out is the one i tried last but is not working.
Apparently, the logic is not totally correct, but what I am missing?
Thank you

Strings are immutable in JS, you can't just overwrite the length attribute ;)
Do you mean, that you need padding after the word up to the length of the longest word? If I understood it correctly, then try something like this:
console.log(y + " " + words[i].padEnd(longestWord, " ") + " " + y);
This looks like the easiest way, but consult Can I use, if all your browsers are covered.

I would be tempted to get rid of some of the for loops to help readability. You can use Math.max and map to find the longest word and padEnd to fix the length:
function frame(string, y = '*') {
var words = string.split(" ");
let longestlength = Math.max(...words.map(w => w.length))
let header = y.repeat(longestlength + 4)
return [
header,
...words.map(word => `${y} ${word.padEnd(longestlength, ' ')} ${y}`),
header
]
}
console.log(frame("hello the word javascript is long").join('\n'))

Calculate the space left to fill and repeat it as below.
function frame(string) {
var words = string.split(" ");
var longestWord = 0;
var y = "*";
//Find the longest word from the string
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord) {
longestWord = words[i].length;
}
}
console.log(y.repeat(longestWord + 4));
for (var i = 0; i < words.length; i++) {
spaceLeft = longestWord - words[i].length;
console.log(y + " " + words[i] + " ".repeat(spaceLeft) + " " + y);
//words[i].length = longestWord;
}
console.log(y.repeat(longestWord + 4));
}
frame('skfj dslfska sadflkdsflkdsnf ldsknflskdnaf dslkf')

The first loop for finding the max length of word seems right in second loop you can use if statement
All you have to do is that
First define an array
let a=[]
In second loop in the commented part write
if(word[I].length == longestlength){a.push(word[I])}
After that you get array containing word whose length is equal to max length
Hope it helps

function frame(string) {
var words = string.split(" ");
var longestWord = 0;
var y = "*";
//Find the longest word from the string
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord) {
longestWord = words[i].length;
}
}
console.log(y.repeat(longestWord));
for (var i = 0; i < words.length; i++) {
console.log(words[i] + y.repeat(longestWord - words[i].length));
//words[i].length = longestWord;
}
}
frame('Lorem ipsum dolor sit amet, consectetur adipiscing elit')
maybe something like this, now every word has same length as the longest one, empty space is filled with *

See comments inline:
function frame(string) {
var words = string.split(" ");
var longestWord = "";
var y = "*";
//Find the longest word from the string
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord.length) {
longestWord = words[i];
}
}
console.log("Longest word is: " + longestWord)
console.log(y.repeat(longestWord.length + 4));
for (var i = 0; i < words.length; i++) {
// Get the difference between the word and the longest word
var diff = longestWord.length - words[i].length;
// Pad the words with the right amount of spaces to make up the difference
console.log(y + " " + words[i] + " ".repeat(diff) + y);
}
console.log(y.repeat(longestWord.length + 4));
}
frame("The quick brown fox jumped over the lazy dog.");

Related

How to return an error with JavaScript when someone enter just space on name field in a array? [duplicate]

This question already has answers here:
How to detect string which contains only spaces?
(10 answers)
Closed 2 years ago.
Here is a code for finding the largest word from an array. But When I input some space (" ") like this I get the blank one as largest. But I want if anyone entered some space only it will return an error.
Can anyone tell me how to do that?
function megaFriend(str) {
var wordLength = 0;
var biggestWord;
for (var i = 0; i < str.length; i++) {
if (str[i].length > wordLength) {
var wordLength = str[i].length;
biggestWord = str[i];
}
}
return biggestWord;
}
console.log(megaFriend(['Nahid', 'Hassan', 'Ahugoggghs', ' ']));
you can use str.replaceAll() method
let spaceFreeElement = str[i].replaceAll(" ", "");
or regex
let spaceFreeElement = str[i].replace(/\s/g, "")
Use a regular expression to test if a word is just spaces, and report an error.
function megaFriend(str) {
var wordLength = 0;
var biggestWord;
for (var i = 0; i < str.length; i++) {
if (str[i].match(/^\s+$/)) {
alert("Spaces entered");
return false;
}
if (str[i].length > wordLength) {
var wordLength = str[i].length;
biggestWord = str[i];
}
}
return biggestWord;
}
console.log(megaFriend(['Nahid', 'Hassan', 'Ahugoggghs', ' ']));
An easy solution is to String.trim() the words when you check the length:
function megaFriend(str) {
var wordLength = 0;
var biggestWord;
for (var i = 0; i < str.length; i++) {
if (str[i].trim().length > wordLength) {
var wordLength = str[i].length;
biggestWord = str[i];
}
}
return biggestWord;
}
console.log(megaFriend(['Nahid', 'Hassan', 'Ahugoggghs', ' ']));
You can also trim and throw an error if the string's length is 0 after trimming:
function megaFriend(str) {
var wordLength = 0;
var biggestWord;
for (var i = 0; i < str.length; i++) {
if(str[i].trim().length === 0 && str[i].length > 0) {
throw new Error(`illegal string - index ${i}`);
}
if (str[i].length > wordLength) {
var wordLength = str[i].length;
biggestWord = str[i];
}
}
return biggestWord;
}
console.log(megaFriend(['Nahid', 'Hassan', 'Ahugoggghs', ' ']));

Square text problem looking to loop solution

So I was tasked to take a string as an input and scramble it into a square code, i.e "If man was meant to stay on the ground god would have given us roots" returns imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau, where each letter in the new string comes from sorting the string into a column and the string is the vertical column of the square. i.e:
ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots
I have a solution but it is clunky and if the square if bigger than 8 x 8 my solution breaks down. Looking to simplify just don't have the logic for it yet.
My intuition tells me there is a way I can loop this but I just can't see the method.
const squareCode = function(message) {
let newString = ""
let string = message.replace(/ /g, "");
let root =Math.ceil(Math.sqrt(string.length))
root = Math.round(root)
for (let i = 0; i < string.length; i ++){
if (i % root == 0 || i == 0){
newString += string[i]
}
} newString += " "
for (let i = 0; i < string.length; i ++){
if (i % root == 1 ){
newString += string[i]
}
} newString += " "
for (let i = 0; i < string.length; i ++){
if (i % root ==2){
newString += string[i]
}
} newString += " "
for (let i =0; i < string.length; i ++){
if ( i % root ==3){
newString += string[i]
}
} newString += " "
for (let i =0; i < string.length; i ++){
if ( i % root ==4){
newString += string[i]
}
} newString += " "
for (let i =0; i < string.length; i ++){
if ( i % root ==5){
newString += string[i]
}
} newString += " "
for (let i =0; i < string.length; i ++){
if ( i % root ==6){
newString += string[i]
}
} newString += " "
for (let i =0; i < string.length; i ++){
if ( i % root ==7){
newString += string[i]
}
} newString += " "
return newString
}
console.log(squareCode("chill out"));
console.log(squareCode("feed the dog"));
console.log(squareCode("have a nice day"));
console.log(squareCode("if man was meant to stay on the ground god would have given us roots"));
//my output
//clu hlt io
//fto ehg ee dd
//hae and via ecy
//imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
I'm getting what I want i'd just prefer to do it in less than 50 lines of code.
One way to do it using Array#reduce
const squareCode = message => {
let string = message.replace(/\s+/g, "").split('');
let length = Math.ceil(Math.sqrt(string.length));
return string.reduce((acc, l, i) => (acc[i%length] += l, acc), new Array(length).fill('')).join(' ');
};
console.log(squareCode("chill out"));
console.log(squareCode("feed the dog"));
console.log(squareCode("have a nice day"));
console.log(squareCode("if man was meant to stay on the ground god would have given us roots"));
If the quest is to do it in as few lines of code as possible, regardless of readability
const squareCode = m => m.replace(/\s+/g, "").split('').reduce((a, l, i) => (a[i%Math.ceil(Math.sqrt(m.replace(/\s+/g, "").split('').length))] += l, a), new Array(Math.ceil(Math.sqrt(m.replace(/\s+/g, "").split('').length))).fill('')).join(' ');
console.log(squareCode("chill out"));
console.log(squareCode("feed the dog"));
console.log(squareCode("have a nice day"));
console.log(squareCode("if man was meant to stay on the ground god would have given us roots"));

How can I numerically sort an array in Javascript when the number is the first part of each entry?

I am creating a list of words from a String. I then split that string into individual words, gather a count of how many times each word is repeated, and display it. Everything there works perfectly. However, the result displays the words and counts in no specific order. I will want to display them with the highest number first. I have generated the following code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="analyze()">Analyze</button>
<p id="displayText"></p>
<script>
function analyze() {
var str = "This this is is is is is is is is is is is is is is is just just a test test test";
var res = str.split(" ");
document.getElementById("displayText").innerHTML = res;
document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>";
document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>";
var words = [];
var wordsWithCount = [];
for (i = 0; i < res.length; i++) {
words.push(res[i]);
document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>";
}
var current = null;
var cnt = 0;
for (var i = 0; i < words.length; i++) {
if (words[i] != current) {
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
current = words[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
wordsWithCount.sort();
document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>";
for (i = 0; i < wordsWithCount.length; i++) {
document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>";
}
}
</script>
</body>
</html>
This is the last bit of the output. As you can see, it's being sorted, but only by first digit. Thus, 15 is displayed before 2. Any thoughts?
The list of SORTED words:
1 - This
1 - a
1 - this
15 - is
2 - just
3 - test
I will most likely need to break this into two arrays at some point, because I will want the user to be able to copy and paste all of the words, without the numbers. However, I assume that will need to be the last step, because if I break the frequency of each word into it's own array of numbers, and keep the words in their own array, then the sort function will sort one array, and the other array will not follow.
Using a parseInt() method and the solution found here (How to sort an array of integers correctly) to the mix it works!
replace wordsWithCount.sort(); with:
function sortNumber(a,b) {
return parseInt(a) - parseInt(b);
}
wordsWithCount.sort(sortNumber);
Live here: https://www.w3schools.com/code/tryit.asp?filename=FFGXRIN0VZWO
Do it using Intl.Collator. Like this:
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var test = ['1 - this', '3 - this', '14 - this'];
test.sort(collator.compare);
Outputs ["1 - this", "3 - this", "14 - this"]
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var test = ['1 - this', '3 - this', '14 - this'];
console.log(test.sort(collator.compare));
You can just add a custom compare function to pass into your wordsWithCount.sort() call. Here I declared a function called compareWordCount and used the sugfested method by #Pointy; using parseInt to ignore all non integer parts appended to array value. Take a look at this working snippet:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="analyze()">Analyze</button>
<p id="displayText"></p>
<script>
function compareWordCount(a,b) {
if (parseInt(a) < parseInt(b))
return -1;
return 1;
}
function analyze() {
var str = "This this is is is is is is is is is is is is is is is just just a test test test";
var res = str.split(" ");
document.getElementById("displayText").innerHTML = res;
document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>";
document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>";
var words = [];
var wordsWithCount = [];
for (i = 0; i < res.length; i++) {
words.push(res[i]);
document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>";
}
var current = null;
var cnt = 0;
for (var i = 0; i < words.length; i++) {
if (words[i] != current) {
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
current = words[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
wordsWithCount.push(cnt + " - " + current);
}
wordsWithCount.sort(compareWordCount);
document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>";
for (i = 0; i < wordsWithCount.length; i++) {
document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>";
}
}
</script>
</body>
</html>

Without using a data structure, display whether each character in a string is unique

Without using a data structure, I need to display whether each character in a string is unique or not.
I wrote the code and it works for paa but it doesn't work for pak.
var String = "paa"
//var String = "pak"
var splittedString = String.split();
for(i = 0; i < splittedString.length; i++) {
if(splittedString[i] === splittedString[i+ 1] ||
splittedString[i+1] === splittedString[i + 2]) {
console.log("not unique string");
} else {
console.log("its an unique string")
}
}
It is clearly stated in the problem don't need to use the data structure. I saw above answers using an array. I try to solve this issue in C#. Let me know if you have any feedback.
public bool IsUnique(string text)
{
if (text.Length > 256) return false;
for (var indx = 0; indx < text.Length; indx++)
{
for (var jndx = indx + 1; jndx < text.Length; jndx++)
{
// compare character
if (text.Substring(indx, 1) == text.Substring(jndx, 1) )
{
return false;
}
}
}
return true;
}
Just to show the needed change in your code, plus nice output as per Emile's request:
var str = "palace";
//var str = "pak";
var splittedString = str.split('');
for (i=0; i<splittedString.length; i++) {
var c = splittedString[i];
var unique = true;
for (j=0; j <splittedString.length; j++) {
if (i==j) continue;
if (c === splittedString[j]) {
unique = false;
break;
}
}
console.log("'" + c + "' is" + (unique ? '': ' not') + " unique character");
}
First you sort the characters in the string and then compare each one to the next.
The program with regex may look like below
var str = "alphabet";
var sstr = str.split('').sort().join('');
var result = /(.)\1/.test(sstr);
console.log(sstr + " has dups: " + result)

Identify palindromes in a sentence

A lot of solutions I found here are giving true or false after checking if a string is a palindrome. I have a function that checks if a string is a palindrome or not:
function palindrome(myString){
/* remove special characters, spaces and make lowercase*/
var removeChar = myString.replace(/[^A-Z0-9]/ig, "").toLowerCase();
/* reverse removeChar for comparison*/
var checkPalindrome = removeChar.split('').reverse().join('');
/* Check to see if myString is a Palindrome*/
if(removeChar === checkPalindrome){
document.write("<div>"+ myString + " is a Palindrome <div>");
}else{
document.write("<div>" + myString + " is not a Palindrome </div>");
}
}
palindrome("Oh who was it I saw, oh who?")
palindrome("Madam")
palindrome("Star Wars")
But this is not quite what I want. It's just checking if the string is a palindrome or not. I want to update the function so that it identifies all of the palindromes in a sentence instead of giving it true or false. So if there's a sentence like this - "Madam and John went out at noon" It will list the palindromes in that sentence - "Madam, noon"
Any help in this would be appreciated!
function findPalindromes(str, min) {
min = min || 3;
var result = [];
var reg = str.toLowerCase();
var reg = reg.replace(/[^a-z]/g, ''); // remove if you want spaces
var rev = reg.split("").reverse().join("");
var l = reg.length;
for (var i = 0; i < l; i++) {
for (var j = i + min; j <= l; j++) {
var regs = reg.substring(i, j);
var revs = rev.substring(l - j, l - i);
if (regs == revs) {
result.push(regs);
}
}
}
return result;
}
var str1 = "Madam and John went out at noon";
console.log(str1, findPalindromes(str1));
var str2 = "\"Amore, Roma\" and \"There's no 'x' in Nixon\" are palindromes.";
console.log(str2, findPalindromes(str2));
function findPalindromes(sentence) {
const words = sentence.replace(/[^\w\s]/gi, '').split(' ');
const palindromes = words.filter(isPalindrome);
return palindromes;
}
function isPalindrome(word) {
if (word.length <= 0) return false;
word = word.toLowerCase();
for (let i = 0; i < word.length / 2; i++) {
if (word[i] !== word[word.length - 1 - i]) return false;
}
return true;
}
https://jsfiddle.net/ewezbz22/1/

Categories

Resources