I am trying to make a function that will return the last letter of each word in a string, and think I am close, but whenever I invoke the function, I get a series of numbers instead of the letters I am looking for.
This is the code:
function lastLetter(str){
var arr = [];
for(var i = 0; i < str.length; i++){
if(str[i] === " " || str[i] === "."){
arr.push((i) - 1);
}
}
return arr;
}
lastLetter("I love bacon and eggs.");
Any advice would be appreciated. Thanks!!
You push the value i - 1 onto the array. You meant to push str.charAt(i-1):
arr.push(str.charAt(i - 1));
See: String charAt().
Note that your code isn't really defensive. If there is a space or period at the first character in the string, you are referencing the character at position -1, which is not valid. You could solve this by looping from 1 instead of 0. In that case you would still get a space in the result if the string starts with two spaces, but at least you won't get an error. A slightly better version of the algorithm would test if i-1 is a valid index, and if there is a character at that position that is not a space or a period.
Below is a possible solution, which I think solves those cases, while still retaining the structure of the code as you set it up.
function lastLetter(str){
var arr = [];
for(var i = 1; i < str.length; i++){
var p = str.charAt(i-1);
var c = str.charAt(i);
if ( (c === " " || c === ".") &&
!(p === " " || p === ".") ) {
arr.push(p);
}
}
return arr;
}
console.log(lastLetter("... Do you love bacon and eggs..."));
Try:
arr.push(str[i - 1]);
This will have problems with multi-byte characters, however.
You're pushing the integer value i-1 rather than the character str[i-1].
You are pushing the index into your array. You still need to access i-1 of your string
`
` function lastLetter(str){
var arr = [];
for(var i = 0; i < str.length; i++){
if(str[i] === " " || str[i] === "."){
arr.push(str[(i) - 1]);
}
}
return arr;
}
lastLetter("I love bacon and eggs.");
Solution and Improved version below:
use arr.push(str.charAt(i - 1)) instead of arr.push((i) - 1)
(You where saving the position of the last letter, but not it's value - charAt(position) does give you the latter at the given position
charAt(): http://www.w3schools.com/jsref/jsref_charat.asp
Demo:
function lastLetter(str){
var arr = [];
for(var i = 0; i < str.length; i++){
if(str[i] === " " || str[i] === "."){
arr.push(str.charAt(i - 1));
}
}
return arr;
}
document.body.innerHTML = lastLetter("I love bacon and eggs.");
Improved Version:
function lastLetter(str) {
var arr = [];
var words = str.split(/[\s\.?!:]+/)
for (var i = 0; i < words.length; ++i) {
if (words[i].length > 0) {
var lastLetter = words[i].charAt(words[i].length - 1)
arr.push(lastLetter);
}
}
return arr;
}
document.body.innerHTML = lastLetter("... Is this: correct?! I love bacon and eggs.");
Related
I would like to duplicate every single letter in my string and uppercasing the first letter.
Like this case:
accum("abcd") -> "A-Bb-Ccc-Dddd".
However, it alters the first letter of the string. I think I should add another iterator called "j". But I don't know how to do it.
Precisely, the only task remaining in my code is to move on to the next letter while saving the changes made for the first letter.
function accum(s) {
var i = 0;
while ( i<s.length){
for (var j =i; j<i ; j++) {
s=s[j].toUpperCase()+s[j].repeat(j)+"-";
i+=1;
}
}
return s.slice(0,s.length-1);
}
Try this:
function accum(s) {
let newString = '';
for(let i = 0; i < s.length; i++) {
newString += s[i].toUpperCase() + s[i].repeat(i) + "-";
}
return newString.slice(0, newString.length - 1);
}
I guess you don't need two repetition loops at all (either you can keep the for or the while, i kept the for).
Your fundamental mistake was in this line: s=s[j].toUpperCase()+s[j].repeat(j)+"-"; where you replaced s with the new string instead of concatenating it (s += instead of s = ). Which would be wrong anyway because you are replacing the original string. You need another empty string to keep the changes separated from the original one.
Do this:
function accum(s) {
accumStr = '';
for (var i=0; i < s.length; i++) {
for (var j = 0; j <= i; j++) {
accumStr += j !== 0 ? s[i] : s[i].toUpperCase();
}
}
return accumStr;
}
console.log(accum('abcd')) //ABbCccDddd
Try this:
function accum(s) {
let strArr = s.split('');
let res = [];
for (let i in strArr) {
res.push(strArr[i].repeat(parseInt(i)+1));
res[i] = res[i].charAt(0).toUpperCase() + res[i].slice(1);
}
return res.join('-');
}
console.log(accum('abcd'))
try to use reduce method
const accum = (str) => {
return [...str].reduce(
(acc, item, index, arr) =>
acc +
item.toUpperCase() +
item.repeat(index) +
(index < arr.length - 1 ? "-" : ""),
""
);
};
console.log(accum("abcd")); //A-Bb-Ccc-Dddd
Guys i'm trying to write an algorithm where I pass in a large string and let it loop through the string and whatever palindrome it finds, it pushes into array but for some reason my browser is crashing once i put in the while loop and I have no
function arrOfPalindromes(str) {
var palindromeArrays = []
var plength = palindromeArrays.length
// grab first character
// put that in a temp
// continue and look for match
// when match found go up one from temp and down one from index of loop
// if matched continue
// else escape and carry on
// if palendrome push into array
var counter = 0;
for (var i = 0; i < str.length; i++) {
for (var j = 1; j < str.length - 1; j++) {
if (str[i + counter] === str[j - counter]) {
while (str[i + counter] === str[j - counter]) {
console.log(str[j], str[i])
// append the letter to the last index of the array
palindromeArrays[plength] += str[i]
counter++
}
}
}
}
return palindromeArrays
}
var result2 = arrOfPalindromes('asdfmadamasdfbigccbigsdf')
console.log(result2)
Do not mention about the algorithm but the condition
while (str[i + counter] === str[j - counter])
Make your code crash. A little surprise but str[j+counter] when j+counter > str.length return undefined and the same as j-counter <0. There for, your while loop never end because of undefined === undefined.
Returning same sized array to handle nested palis.
ex: abxyxZxyxab => 00030703000 odd numbered nested palis.
ex: asddsa => 003000 even numbered pali.
ex: asdttqwe => 00020000 i dont know if this is a pali but here we go
smallest pali is 2 char wide so i start at index:1 and increment till str.len-1
for (var i = 1; i < str.length-1; i++) {
counter=0;
while(str[i]+1-counter == str[i]+counter || str[i]-counter == str[i]+counter) { // always true when counter is 0
// while (even numbered palis || odd numbered palis)
// IF counter is bigger than 0 but we are still here we have found a pali & middle of the pali is i(or i+0.5) &size of the pali is counter*2(or+1)
if(str[i]+1-counter == str[i]+counter){//even sized pali
res[i]=counter*2;
}else{//odd sized pali
res[i]=counter*2+1;
}
counter++;//see if its a bigger pali.
}
}
not super optimized while + if,else checks same stuff. These can be somehow merged. Maybe even even and odd can be handled without any checks.
You don't need to use three loops. You can do it with two for loops where one starts from the beginning and other one is from the end of the string.
Here we use array reverse() method to match palindromes.
Also I added additional minLength parameter and duplication removal logic to make it more nice.
function findPalindromes(str, minLength) {
var palindromes = [];
var _strLength = str.length;
for (var i = 0; i < _strLength; i++) {
for (var j = _strLength - 1; j >= 0; j--) {
if (str[i] == str[j]) {
var word = str.substring(i, j + 1);
//Check if the word is a palindrome
if (word === word.split("").reverse().join("")) {
//Add minimum length validation and remove duplicates
if(word.length >= minLength && palindromes.indexOf(word) === -1){
palindromes.push(word);
}
}
}
}
}
return palindromes;
}
var result = findPalindromes('asdfmadamasdfbigccbigsdf', 2)
console.log(result)
Okay so palindrome is a word that is the same spelled backwards. What if we want to take a phrase that is also the same backwards? So kook is one. race car is another one.
So I made one that doesn't account for spaces.
function isPal(string){
var l = string.length;
for (var i = 0; i < (l/2); ++i) {
if (string.charAt(i) != string.charAt(l - i - 1)){
return false;
}
}
return true;
}
This one works fine for words.
Now I'm thinking, push the string into an array, and split up each character into it's own string, then remove any spaces, and then run if (string.charAt(i) != string.charAt(string.length - i - 1)). So here's what I wrote but failed at..
function isPalindrome(string){
var arr = [];
arr.push(string.split(''));
for (i = 0; i < arr.length; i++){
if (arr[i] === ' '){
arr.splice(i, 1);
if I return arr, it still gives me the string with the space in it. How do I accomplish this? Thanks!
EDIT: Used the solution but still getting false on 'race car'
Here's what I got:
function isPalindrome(string){
var arr = string.split('');
for (i = 0; i < arr.length; i++){
if (arr[i] === ' '){
arr.splice(i, 1);
} else if (arr[i] != arr[arr.length - i - 1]){
return false;
}
}
return true;
}
where's my error?
Your problem is in the following line:
arr.push(string.split(''));
string.split('') returns an array. So, arr is actually an array with one entry it in (another array that contains your characters). Replace:
var arr = [];
arr.push(string.split(''));
with
var arr = string.split('');
and it should work as expected
Just check check the string without spaces:
function isPal(string){
string = string.split(" ").join(""); // remove all spaces
var l = string.length;
for (var i = 0; i < (l/2); ++i) {
if (string.charAt(i) != string.charAt(l - i - 1)){
return false;
}
}
return true;
}
isPal("a man a plan a canal panama"); // true
It seems much easier to just split into an array, reverse and join again to check if a word is a palindrome. If you want to ignore spaces, just remove all instances of spaces:
let word = 'race car';
let isPalindrome = (word) => {
let nospaces = word.replace(/\s/g, '');
return [...nospaces].reverse().join('') === nospaces;
}
Or non-es6:
var word = 'race car';
var isPalindrome = function(word) {
var nospaces = word.replace(/\s/g, '');
return nospaces.split('').reverse().join('') === nospaces;
}
this is the code i came up with:
var alpha = "abcdefghijklmnopqrstuvwxyz".split('');
// console.log(alpha);
// console.log(alpha.length);
for(i=0; i < alpha.length + 1; i++){
if (alpha.indexOf('a', +1) % 2 === 0){
console.log(indexOf('a'));
} else {
console.log("didn't work");
}
};
A simple loop with a step:
for (var i = 0; i < alpha.length; i+=2) {
alpha[i] = alpha[i].toUpperCase();
}
alpha.join(''); // AbCdEfGhIjKlMnOpQrStUvWxYz
If aBcDeFgHiJkLmNoPqRsTuVwXyZ is what you want to achieve, than you can do something like this:
var alpha = 'abcdefghijklmnopqrstuvwxyz';
var result = '';
for (var i = 0; i < alpha.length; i++) {
if ((i + 1) % 2 === 0){
result += alpha[i].toUpperCase();
} else {
result += alpha[i];
}
}
console.log(result);
You can map your array and upper case every second character:
var alpha = "abcdefghijklmnopqrstuvwxyz".split('').map(function(ch, i) {
return i % 2 ? ch.toUpperCase() : ch;
});
console.log(alpha);
The issue with strings is that you can't edit them, once created they stay the same. Most actions on them create a new string.
To avoid doing this lots of times, we do the following
var alpha = 'abcdefghijklmnopqrstuvwxyz'.split('');
Convert the string into an an array
for (var i = 0; i< alpha.length; i++) {
if(i % 2 == 0) {
go down the array, and for every other entry (i % 2 gives us 0 every other time).
alpha[i] = alpha[i].toUpperCase();
convert it to upper case
}
}
var newString = alpha.join('');
and finally make a new string by joining all the array elements together. We have to provide a null string ie '' because if we didn't provide anything we would join with commas (,)
var alpha = "abcdefghijklmnopqrstuvwxyz".split('');
for(i=0; i < alpha.length; i++){
console.log(alpha[i].toUpperCase());
//If you want to update
alpha[i] = alpha[i].toUpperCase();
};
I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)