Use a loop for slicing - javascript

I'm trying to make a program where if you write in a word, let's say "Hello". And then you press the print button the outcome would be this:
"H"
"He"
"Hel"
"Hell"
"Hello".
Should i use a loop for this? My code so far is this:
function printit()
{
var temptext = document.getElementById("mytext").value;
temptext = temptext.slice(1,2);
document.getElementById("translated").innerHTML=temptext;
}
Anyone got any suggestions on how to solve this?

Here's how this would work with a loop.
Loop over the characters
Use the loop counter (i) to progressively slice the required chunk off your text.
Make sure you slice(0, i + 1), so you don't slice(0, 0) on the 1st iteration
function print() {
var text = document.querySelector("#text").value
for(var i = 0; i < text.length; i++) {
console.log(text.slice(0, i + 1))
}
}
<input id="text" value="Hello"/>
<button onclick="print()">Print</button>

You can use .map() with a scoped variable, to return an array of the words you need
function toSplicedWordArray(what) {
var before='';
return what.split('').map(function(item) {before+=item;return before;});
}
console.log(toSplicedWordArray('hello'));

try this:
let word = 'Good';
for (let i = 1; i <= word.length; i++) {
console.log(word.substring(0, i));
}

function printinit() {
var tempText = document.getElementById("mytext").value;
var slicedText = "";
for (var i = 0; i < tempText.length; i++) {
slicedText = tempText.slice(0, i) + " ";
}
document.getElementById("translated").innerHTML = temptext;
}

Related

Duplicate a character depending on its position in a string

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

JavaScript Permutation Issuse

I am working on permutation str using recursive, but it can not get out of the for loop.
Can anyone help for this code?
Thank you in advance.
var permutations = [];
var words = [];
function getPerms(str) {
if(str.length == 0) {
permutations.push("");
return permutations;
}
var first = str.charAt(0);//get the first char
var reminder = str.slice(1);//remove the first char
words = getPerms(reminder);
for(var i = 0; i < words.length; i++) {
for(var j = 0; j <= words[i].length; j++) {
var s = insertCharAt(words[i], first, j);
permutations.push(s);
}
}
return permutations;
}
function insertCharAt(word, c, i) {
var start = word.slice(0, i);
var end = word.slice(i);
var result = start + c + end;
return result;
}
console.log(getPerms("abc"));
Your code is fine, except for one issue:
The variables permutations should not be a global variable. You can clearly see this is wrong, by looking at permutations.push(""). This is fine as a temporary result in the deepest level of recursion, but obviously this should not be present in the final result. Yet, because permutations is global, and you never remove anything from it, permutations will keep this "".
The problem gets worse because words gets the permutations reference from the recursive call, and so they point to the very same array! So not only are all previous results iterated, but with an extra character add to them they are pushed again into permutations, which is the same array as words giving you an endless loop: you add to the array you are iterating, and so never get to the end.
The solution is simple:
Make permutations a variable local to the getPerms function. And why not do the same for words when you are at it.
function getPerms(str, depth=0) {
var words = [];
var permutations = [];
if(str.length == 0) {
permutations.push("");
return permutations;
}
var first = str.charAt(0);//get the first char
var reminder = str.slice(1);//remove the first char
words = getPerms(reminder, depth+1);
for(var i = 0; i < words.length; i++) {
for(var j = 0; j <= words[i].length; j++) {
var s = insertCharAt(words[i], first, j);
permutations.push(s);
}
}
return permutations;
}
function insertCharAt(word, c, i) {
var start = word.slice(0, i);
var end = word.slice(i);
var result = start + c + end;
return result;
}
console.log(getPerms("abc"));
Be sure to check these solutions offered for this problem.
The problem is probably at the last call you return permutations and then assign it to words (what you did here is like words = permutation), but this is not an assignement by copy, but by reference (because words and permutations belongs to the same scope + they are array), so from the last call they are the same object (and when the code unstack previous call, they are now the same object). To illustrate, execute the following code. You will see, when you modify words you modify permutations:
var permutations = [];
var words = [];
function getPerms(str) {
if(str.length == 0) {
permutations.push("");
return permutations;
}
var first = str.charAt(0);//get the first char
var reminder = str.slice(1);//remove the first char
words = getPerms(reminder);
words.push("foo");
console.log( permutations);
return permutations;
}
function insertCharAt(word, c, i) {
var start = word.slice(0, i);
var end = word.slice(i);
var result = start + c + end;
return result;
}
console.log(getPerms("abc"));
In your code, you loop on words and modify permutation in the same time (so, based on the previous explanation, it is like modifying words and loop on words in the same time), it is this things which create the infinite loop.
I did not check if your algo works, I am just pointing code's problem.
So I think what you want is:
function getPerms(str) {
var permutations = [];
var words = [];
if(str.length == 0) {
permutations.push("");
return permutations;
}
var first = str.charAt(0);//get the first char
var reminder = str.slice(1);//remove the first char
words = getPerms(reminder);
for(var i = 0; i < words.length; i++) {
for(var j = 0; j <= words[i].length; j++) {
var s = insertCharAt(words[i], first, j);
permutations.push(s);
}
}
return permutations;
}
function insertCharAt(word, c, i) {
var start = word.slice(0, i);
var end = word.slice(i);
var result = start + c + end;
return result;
}
console.log(getPerms("abc"));

Calculate sentences using function in Javascript

I have come across a question about calculating sentences using a form in HTML, but I wanted to work out the function first to see if it would work. Here is my function that I have not been able to get it working in jsfiddle (https://jsfiddle.net/jdloomis/fxt81ynu/2/):
var numSentences = 0;
function calSentences(longString) {
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
}
console.log(calSentences("This is a sentence. My second sentence."));
I have been able to figure out most of the functions and what they do in my book except this one and a word count without using .split, I will post that one in another post if I cannot figure it out.
You were so close with your attempt! All you forgot to do is return the number of sentences with return numSentences:
var numSentences = 0;
function calSentences(longString) {
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
return numSentences;
}
console.log(calSentences("This is a sentence. My second sentence."));
Hope this helps! :)
Your code is correct, but you are not returning anything from your function.
Also, keep var numSentences local to your function, so that it's reset to 0 each time you run your function. Otherwise, you are adding on to the previous calculation each time you run the function.
function calSentences(longString) {
var numSentences = 0;
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
return numSentences;
}
console.log(calSentences("This is a sentence. My second sentence."));

cannot detect error. Where is the infinite loop occurring?

// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count = 0;
var array = person.split(",");
var freq = [];
var words = [];
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i = 0, j = 0;
while (array.length > 0) {
var temp = array[0];
while (j < array.length) {
if (temp == array[j]) {
count = count + 1;
array.splice(j, 1);
//console.log(array);
j = 0;
}
else {
j = j + 1;
}
}
freq[freq.length] = count;
count = 0;
words[words.length] = temp;
}
window.alert(freq + "\n" + words);
The problem is that whenever I run it an infinite loop occurs and no output is shown, I cannot find the error please help if possible. This code is for finding the frequency of the words in a input string with words separated by commas. thank u.
You just need to put var i=0,j=0; inside the while !
while(array.length>0)
{var i=0,j=0;
Working fidddle
You're resetting your loop variable j to 0 on each iteration. This condition if(temp==array[j]) never fails so j is always reset to 0, so while(j<array.length) is always true.
After coming out of the inner While loop, you need to reset j to zero. As the incremental value of j is not allowing it to go again inside the inner loop So array.length is not reducing And we are getting an infinite loop.
// JavaScript Document
var person = prompt("GIVE INPUT", "");
var count=0;
var array = person.split(",");
var freq = new Array();
var words = new Array();
//freq.fill(0);
//words.fill("");
//window.alert(freq[0]);
var i=0,j=0;
while(array.length>0)
{
var temp=array[0];
while(j<array.length)
{
if(temp==array[j])
{
count=count+1;
array.splice(j,1);
//console.log(array);
j=0;
}
else
{
j=j+1;
}
}
freq[freq.length]=count;
count=j=0;
words[words.length]=temp;
}
window.alert(freq+"\n"+words);
It's where for is more useful for consistency. You can replace inner while loop by this for loop:
for(j=a.length-1; j>=0; j--)
if(temp==a[j]) {
count=count+1;
a.splice(j,1);
}
Nevertheless, overall complexity of your counting method can be reduced with data structure like map.
Essential part of your script can be reduced to this:
var counter = new Map();
for (i in array)
counter.set(array[i], (counter.get(array[i])||0)+1);
var freq = Array.from(counter.values());
var words = Array.from(counter.keys());

Print range using for-loop JavaScript

I need to print a range of numbers in a range using a function and a for-loop.
Again I'm stuck on the return value. I believe my code is sufficient for the task but if you have a better idea I'm all ears.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i < rangeStop; i++) {
text += i + ',';
}
return text;
var result = text;
}
printRange(20, 47);
The 'result' is ought to print the numbers 20,21,22...,46,47 but of course it doesn't...
Any help is appreciated.
Regards, Thomas
There are two things you need to fix - your code doesn't print rangeStop, but it does include a trailing comma.
You can fix the former by changing your loop end condition to use <=, and String.prototype.slice can do the latter.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i <= rangeStop; i++) {
text += i + ',';
}
return text.slice(0, -1);
}
document.write(printRange(20, 47));
function printAllNum(rangeStart, rangeEnd){
for(let i = rangeStart; i <= rangeEnd; i++) {
document.write(i + " ")}
}
printAllNum(1,20);

Categories