Reverse words(not letters) for a string without using .reverse() - javascript

The problem I am working on asks for me to write a function reverseMessage() that takes a string message and reverses the order of the words in place.
The answer I first came up with works but apparently doesn't meet the requirements of this task:
function reverseMessage(string) {
return string.split(" ").reverse().join(" ");
}
For example:
var string = "reversed are string your in words the now"
var results = "now the words in your string are reversed"
New solution:
I would like to split this string into an array and then loop through that array and swap the 1st index with the last index, the 2nd index with second to last index, 3rd index with the 3rd to last index, etc... until I meet in the middle.
I am trying to make the two different functions below work:
function reverseMessage(string) {
var array = string.split(" ");
//loop through array and replace first index with last index, second
index with second to last index, third index with third to last index, etc
for (var i = 0; i < array.length/2; i++) {
for (var j = (array.length-1); j > array.length/2; j--) {
array[i] = array[j];
array[j] = array[i];
messageSplit.join(",");
}
};
function reverseMessage2(string) {
var array = string.split(" ");
var newArray = []
for (var i = 0; i < array.length/2; i++) {
newArray.unshift(array[i]++);
newArray.join(",");
return newArray;
}
};
Am I on the right track?

function reverseMessage(string) {
var array = string.split(" ");
var result="";
for (var i = array.length-1; i >=0; i--) {
result+=array[i]+" ";
}
console.log(result);
};

So in yours reverseMessage function You are trying to swap variable for that you are doing
array[i] = array[j];
array[j] = array[i];
Which is giving array[i]=array[j] so let say array[i]="This" and array[j]="That"so according to yours code array[i] will be "That" and array[j] will also be "That" so you can try something like this:
function reverseMessage(string) {
var array = string.split(" ");
//loop through array and replace first index with last index, second
//index with second to last index, third index with third to last index, etc
for (var i = 0,j=(array.length)-1; i < array.length/2; i++) {
temp=array[i]
array[i] = array[j];
array[j]=array[i]
array[j] = temp; j--;}
console.log(array.join(" "));
}; reverseMessage("find you will pain only go you recordings security the into if");

try this one
function reverseMessage( str ) {
var arrStr = [];
var temp ="";
for(var i = 0 ; i < str.length ; i++)
{
if(str[i] === " ")
{
arrStr.push(temp);
temp="";
}
else
{
temp += str[i];
}
}
if(temp.length >= 0)
{
arrStr.push(temp);
}
var result = "";
for(var x=arrStr.length-1 ; x >=0 ; x--)
{
result += " "+arrStr[x];
}
return result;
}
console.log(reverseMessage("I am here"));

Well, someone's gotta do it:
function rev(s){
var a = s.split(/ /),
l = a.length;
i = l/2 | 0;
while (i--) a.splice(i, 1, a.splice(l-1-i, 1, a[i])[0]);
return a.join(' ');
}
document.write(rev('0 1 2 3 4 5 6 7 8 9'));

Using Array.split(), Array.pop(), Array.push() and String.substr():
var flip = function(str) {
var res = "", sp = " ", arr = str.split(sp);
while (arr.length)
res += arr.pop() + sp;
return res.substr(0, res.length - 1); //remove last space
};
alert(flip("reversed are string your in words the now"));
Using String.lastIndexOf() and String.substr():
var flip = function(str) {
var res = "", i, sp = ' ';
while (str) {
i = str.lastIndexOf(sp);
res += str.substr(i + 1) + sp;
str = str.substr(0, i);
}
return res.substr(0, res.length - 1); //remove last space
};
alert(flip("reversed are string your in words the now"));

What you want to do is split the words message into individual strings reverse them and then add them together, that will reverse them in place. Try
function reverseMessage(message){
var reversedMessage = ''; //A string to hold the reversed message
var words = message.split(' ');
for(var i =0; i< words.length; i++){
reversedMessage += reverse(words[i]) + " ";// add the reversed word to the reversed message, with a space at the end so the words dont touch
}
return reversedMessage
}
//A helper function that reverses a string
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
sources: http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/

with `pop()` ;)
function reverseMessage(string) {
var array = string.split(" ");
var result="";
while (array.length > 0) {
result += array.pop()+" ";
}
console.log(result);
};

Related

Trying to remove duplicate elements with the same values that are next to each other in an array (they have to preserve the original order)

So). This removes all duplicates. But I cann't figure out the logic for removing duplicates that are next to each other only.
For example:
input:('FFNNbbffnnNN');
output:[F, N, b, f, n, N];
var uniqueInOrder = function(iterable){
var newArr =[];
var len = iterable.length;
for(var i = 0; i < len ; i ++){
if( newArr.indexOf(iterable[i]) === -1){
newArr.push(iterable[i])
}
}
return newArr;
}
uniqueInOrder('ffssSnnsS');
Here I tried a little bit.. meh.. begging for tips. Thank you!
var uniqueInOrder = function(iterable){
var newArr =[];
var len = iterable.length;
var first = iterable[0];
for(var i = 0; i < len ; i ++){
if( newArr.indexOf(first) !== newArr.indexOf(first + 1){
newArr.push(iterable[i])
}
}
return newArr;
}
uniqueInOrder('ffssSnnsS');
Better to remove from backward to avoid miss splice when there are more than two duplicate elements after iteration took place:
var nums = [1,2,3,3,4,5,5,6,7,7,7,8];
for (i=nums.length-1; i > 0; i--) {
if(i <= nums.length && nums[i] === nums[i - 1]){
nums.splice(i,1);
}
}
console.log(nums);
Use Array.filter().
var nums = [1,2,3,3,4,5,5,6,7,7,8];
nums.forEach(function(num,index){
// Is the current index < the amount of itmes in the array
// and, if so, is the current item equal to the next item?
if(index < nums.length && num === nums[index + 1]){
nums.splice(index,1); // Remove the current item
}
});
console.log(nums);
I did it like this:
function uniqueInOrder(str) {
const letters = str.split('');
var lastLetter = null;
for (let [index,letter] of Object.entries(letters)) {
if (letter === lastLetter) {
letters[index] = null;
} else {
lastLetter = letter;
}
}
console.log(letters);
return letters.join('');
}
uniqueInOrder('ffssSnnsS');
I use split to turn it into an array. I keep track of the most recent previous letter. If the current letter matches, i null it in the array, otherwise i just update the lastLetter variable.

Skip numbers that include certain number in an array

I'm trying to create a function which takes 3 parameters – start, end and bannedNumber. It should print all the numbers from start to end but skip all multiples of the banned number and any number that has a banned number in it.
Here is my code:
<script>
var arr = [];
var str = "";
var newarr = [];
var str1
function Zumbaniaa(a, b, c) {
for (var i = a; i < b; i++) {
arr.push(i);
}
for (var j = 0; j < arr.length; j++) {
if (arr[j] % c == 0) {
arr.splice(j, 1);
}
}
for (var m = 0; m < arr.length; m++) {
str = arr[m].toString();
str1=str.split("");
if (str1.indexOf(c) >=0) {
arr.splice(m, 1);
}
}
return arr
}
document.write(Zumbaniaa(1, 90, 8))
console.log(str1)
</script>
For some reason the third loop is not working. It's not filtering numbers with 8 at all.
It's simplest to just not push the banned values into the array to begin with. So check if the numbers to be pushed are a multiple of the banned digit, or contain the banned digit before you push:
function filtered_range(start, end, banned) {
let nums = [];
for (let i = start; i <= end; i++) {
if (i % banned != 0 && i.toString().indexOf(banned) == -1) nums.push(i);
}
return nums;
}
console.log(filtered_range(1, 90, 8).join(' '));
Remove this line: str1 = str.split("");. It is causing indexOf() to fail. Call str.indexOf(c) instead. Then reverse the final loop.
What is happening: indexOf() works on strings and arrays. When used on a string, the character being searched for is always parsed first to a string, because strings only contain strings. When used on an array, the character being searched for isn't parsed at all, because arrays can contain strings, numbers, etc.
var arr = [];
var str = "";
var newarr = [];
var str1
function Zumbaniaa(a, b, c) {
for (var i = a; i < b; i++) {
arr.push(i);
}
for (var j = 0; j < arr.length; j++) {
if (arr[j] % c == 0) {
arr.splice(j, 1);
}
}
for (var m = arr.length - 1; m > 0; m--) {
str = arr[m].toString();
//str1 = str.split("");
if (str.indexOf(c) >= 0) {
arr.splice(m, 1);
}
}
return arr
}
Zumbaniaa(1, 90, 8);
console.log(arr);

How to join an array of strings without using .join()?

We're trying to write a function that takes an array of strings and a separator, and joins all the strings separated by such separator.
We are not allowed to use the .join() method.
So far, I'm stuck trying to iterate though all the strings adding a separator between them each time.
I tried something like:
var aName = ['Frank','Vincent','Zappa'];
var join = (arr, separator = " ") => {
for(var i = 0; i < arr.length; i++) {
return arr[i] + separator + arr[i+1];
}
};
join(aName, ' ');
//output: "Frank Vincent"
//expected output: "Frank Vincent Zappa"
Thanks for your help.
You can reduce the array:
function join(arr, separator)
{
return arr.reduce((str, a)=> {return a+separator+str})
}
To fix your current code, try concatenating instead, and return only at the end:
var aName = ['Frank', 'Vincent', 'Zappa'];
var join = (arr, separator = " ") => {
let result = '';
for (var i = 0; i < arr.length; i++) {
if (result) {
result += separator;
}
result += arr[i];
}
return result;
};
console.log(join(aName, ' '));
A very simple method is to append the separator only for the second element onwards:
const arr = ["Frank", "Vincent", "Zappa"];
const join = (arr, sep = " ") => {
if (!arr || !arr.length) return "";
let ret = arr[0];
for (let i = 1; i < arr.length; i++) {
ret += sep + arr[i];
}
return ret;
};
console.log(join(arr));
console.log(join(arr, "-"));
You can use the String constructor
var name = ['Frank', 'Vincent', 'Zappa'];
console.log(String(name).replace(/,/g,' '))
You could check the length of the array first and return an empty string if length is zero.
Otherwise take the first element as start value for the result and iterate from the second element and add the separator and the value of the array.
Proceed until no more elements. Then return the result string.
var join = (array, separator = ' ') => {
if (!array.length) return '';
var result = array[0];
for (var i = 1; i < array.length; i++) {
result += separator + array[i];
}
return result;
},
array = ['Frank', 'Vincent', 'Zappa'];
console.log(join(array, ' '));
The problem with your code is that you use return in a for loop which means that function will stop it's execution and return a value you write in return.
To avoid that you should write something like this:
var name = ['Frank','Vincent','Zappa'];
var join = (arr, separator = " ") => {
var result = '';
for(var i = 0; i < arr.length; i++) {
// adding to result string arr[i] and separator
result += arr[i] + separator;
}
// deleting separator in the end of string
return result.slice(0, -1);
};
join(name, ' ');
To be precise it is not possible to create a string without join() since JavaScript will internally always call join() for arrays. But if you just want to create your own join() function you can iterate through the array, add a separator to your current item and do this until you reached the end where you only add your current item without a separator.
var name = ['Frank', 'Vincent', 'Zappa'];
function join(arr, separator = " ") {
var str = "";
if (arr.length === 0) return str;
for (var i = 0; i < arr.length; i++) {
str += i !== arr.length - 1 ?
arr[i] + separator :
arr[i];
}
return str;
};
console.log(join(name, ' '));
A solution using a curried function in es2015
const joinStrings = glue = ' ' => strings => {
let res = '';
strings.forEach(str => res += glue + str);
return res.replace(glue, '');
}
const joined = joinStrings(', ')(['a', 'b', 'c']);
console.log(joined);
var names = ['Frank','Vincent','Zappa'];
const join = (names, separator) => {
let str = '';
for(let i = 0; i < names.length; i++) {
str += (str ? separator : '') + names[i];
}
return str;
}
console.log(join(names, ' '));
function joinFunction(arr){
let string = ''
for( let char of arr ){
string += char + ' '
}
console.log(string)
}
joinFunction(['Frank','Vincent','Zappa'])

Why do I have to push my string into an array only to join it back again?

So I want to capitalize the starting letter of each word in a string. Here's how I did it:
function LetterCapitalize(str) {
var arr = str.split(" ");
var newArr = [];
for(i = 0; i < arr.length; i++) {
var newStr = arr[i].toString();
newArr.push(newStr.substring(0,1).toUpperCase() + newStr.substring(1,newStr.length));
}
return newArr.join(" ");
}
This code is correct and the first letter of every word in the string was capitalized. However, when I tried to shorten my code like this, it only returned the last word of the string with the first letter capitalized, but nothing else:
function LetterCapitalize(str) {
var arr = str.split(" ");
var newArr = [];
for(i = 0; i < arr.length; i++) {
var newStr = arr[i].toString();
}
return newStr.substring(0,1).toUpperCase() + newStr.substring(1,newStr.length);
}
Basically, what I did was remove the part where I push the new string into a new array, only to join it back into a string.
Problem is in the for loop part code. Here in every iteration the newstr get the value of arr[i].toString(); and the old value i.e arr[i-1].toString(); which is in newStr is overwritten. Hence only the last iteration value is stored in newStr
for(i = 0; i < arr.length; i++) {
var newStr = arr[i].toString();
}
Try this:
function LetterCapitalize(str) {
var arr = str.split(" ");
var newStr = "";
for(i = 0; i < arr.length; i++) {
var temp = arr[i].toString();
newStr = newStr + temp.substring(0,1).toUpperCase() + temp.substring(1,temp.length)+" ";
}
return newStr;
}
alert(LetterCapitalize("hello i am rohit "));
Perhaps you got confused by the return in the MAP functionality:
function LetterCapitalize(str) {
var arr = str.split(" "),
newArr = arr.map(
function(word) {
return word.substring(0,1).toUpperCase() + word.substring(1);
});
return newArr.join(" ");
}
alert(LetterCapitalize("This is a test"))
You may achieve this through replace function without splitting.
function LetterCapitalize(str) {
return str.replace(/(^| )([a-z])/g, function(x,y,z) {
return y+z.toUpperCase()
}
)
}
console.log(LetterCapitalize('foo bar buz'))

Is there any pre-built method for finding all permutations of a given string in JavaScript?

I'm a newbie to the JavaScript world. As the title mentions, I want to know whether there is any pre-built method in JavaScript to find all possible permutations of a given string.
For example, given the input:
the
Desired output:
the
teh
eht
eth
het
hte
//string permutation
function permutation(start, string) {
//base case
if ( string.length == 1 ) {
return [ start + string ];
} else {
var returnResult = [];
for (var i=0; i < string.length; i++) {
var result = permutation (string[i], string.substr(0, i) + string.substr(i+1));
for (var j=0; j<result.length; j++) {
returnResult.push(start + result[j]);
}
}
return returnResult;
}
}
permutation('','123') will return
["123", "132", "213", "231", "312", "321"]
function permutations(str){
if (str.length === 1) {
return str;
}
var permut = [];
for (var i=0; i<str.length; i++){
var s = str[0];
var _new = permutations(str.slice(1, str.length));
for(var j=0; j<_new.length; j++) {
permut.push(s + _new[j]);
}
str = str.substr(1, str.length -1) + s;
}
return permut;
}
permutations('the');
//output returns:[ 'the', 'teh', 'het', 'hte', 'eth', 'eht' ]
No pre-built, but writing such function is possible.. here is one relatively simple way using two functions:
function FindAllPermutations(str, index, buffer) {
if (typeof str == "string")
str = str.split("");
if (typeof index == "undefined")
index = 0;
if (typeof buffer == "undefined")
buffer = [];
if (index >= str.length)
return buffer;
for (var i = index; i < str.length; i++)
buffer.push(ToggleLetters(str, index, i));
return FindAllPermutations(str, index + 1, buffer);
}
function ToggleLetters(str, index1, index2) {
if (index1 != index2) {
var temp = str[index1];
str[index1] = str[index2];
str[index2] = temp;
}
return str.join("");
}
Usage:
var arrAllPermutations = FindAllPermutations("the");
Live test case: http://jsfiddle.net/yahavbr/X79vz/1/
This is just basic implementation, it won't remove duplicates and has no optimization. However for small strings you won't have any problem, add time measure like in the above test case and see what's your reasonable limit.
This is similar but finds all anagrams/permutations from an array of words. I had this question in an interview. Given an array of words ['cat', 'dog', 'tac', 'god', 'act'], return an array with all the anagrams grouped together. Makes sure the anagrams are unique.
var arr = ['cat', 'dog', 'tac', 'god', 'act'];
var allAnagrams = function(arr) {
var anagrams = {};
arr.forEach(function(str) {
var recurse = function(ana, str) {
if (str === '')
anagrams[ana] = 1;
for (var i = 0; i < str.length; i++)
recurse(ana + str[i], str.slice(0, i) + str.slice(i + 1));
};
recurse('', str);
});
return Object.keys(anagrams);
}
console.log(allAnagrams(arr));
//["cat", "cta", "act", "atc", "tca", "tac", "dog", "dgo", "odg", "ogd", "gdo", "god"]
Assuming a large string to search, you could use a regular expression
to examine a set of possibles that first matches the letters and the total number of letters,
and return the matches that use the same letter set as the pattern.
//(case-insensitive)
function lettersets(str, pat){
var A= [], M, tem,
rx= RegExp('\\b(['+pat+']{'+pat.length+'})\\b', 'gi'),
pattern= pat.toLowerCase().split('').sort().join('');
while((M= rx.exec(str))!= null){
tem= M[1].toLowerCase().split('').sort();
if(tem.join('')=== pattern) A.push(M[1]);
};
return A;
}
lettersets(s, 'the').sort();
function swap(a, b, str) {
if (a == b)
str = str;
else {
str = str.split("");
var temp = str[a];
str[a] = str[b];
str[b] = temp;
str = str.join("");
}
}
function anagram(a1, b1, ar) {
if (a1 == b1)
document.write(ar + "<br/>");
else
for (i = a1; i < b1; i++) {
swap(a1, b1, ar);
anagram((a1) ++, b1, ar);
swap(a1, b1, ar);
}
}
Well there isnt any built in function in js(i dont believe it to be in any coding language)......and anyways this is the fully functioning program, it omits any repetitions and also displays the number of permutations.....
var n=0;
var counter=0;
var storarr=new Array();
function swap(a,b,str) { //swaps the terms str[a] and str[b] and returns the final str
str = str.split("");
var temp = str[a];
str[a] = str[b];
str[b] = temp;
return str.join("");
}
function anagram(_a,_b,ar) { //actual function which produces the anagrams
if(_a == _b) {
storarr[n]=ar;
n++;
counter++;
}
else {
for(var i= _a;i<= _b;i++) {
ar=swap(_a,i,ar);
anagram(_a+1,_b,ar);
ar=swap(_a,i,ar);
}
}
}
function factorial(a) { //return a!
var x=1;
for(var i=1;i<=a;i++)
x=x*i;
return x;
}
var strl=prompt("Enter String:","");
var l=strl.length;
anagram(0,l-1,strl);
storarr.sort(); //sorts the storarr alphabetically
var storlen=storarr.length;
var cai=0;
var counterarr = new Array();
strl.split("");
for(var i=0;i<l;i=i+c) { //determines the number of times a term is repeating
var c=1;
for(var j=i+1;j<l;j++) {
if(strl[i]==strl[j])
c++;
}
counterarr[cai]=c;
cai++;
}
var yellow=1;
for(var i=0;i<counterarr.length;i++) { //multiplies the terms of the counter array
yellow=yellow*factorial(counterarr[i]);
}
counter=counter/yellow;
document.write("Count : " + counter + "<br />");
for(var i=0;i<storlen;i=i+yellow) { //prints the non-flagged terms in storarr
document.write(storarr[i] + "<br />");
}
strl.join("");
<pre>
<script>
var count = 0;
var duplicate = false;
function FindAllPermutations(str, index) {
for (var i = index; i < str.length; i++) {
var newstr;
if (index == i) newstr = str;
else newstr = SwapLetters(str, index, i);
if (!duplicate) {
count++;
document.write(newstr + "\n");
if (i == index) duplicate = true;
} else if (i != index) duplicate = false;
FindAllPermutations(newstr, index + 1);
}
}
function SwapLetters(str, index1, index2) {
if (index1 == index2) return str;
str = str.split("");
var temp = str[index1];
str[index1] = str[index2];
str[index2] = temp;
return str.join("");
}
FindAllPermutations("ABCD", 0); // will output all 24 permutations with no duplicates
document.write("Count: " + count);
</script>

Categories