Javascript, take inputted string and print all possibilities - javascript

I've been searching for ours all over the web, including here for a way to solve this project I have for homework this week. To answer your question, the professor gave us a book that in no way connects with the homework so my textbook has been all but useless. I am very new to Javascript and don't even know where to begin with this project.
Project: "Write a JavaScript function that generates all combinations of an inputted word."
Example: "dog" would print: dog dgo god gdo odg ogd
I kinda wrote out the steps I need the code to make:
Ask user for a string. (i guess using some sort of input box but IDK which to use.)
Pass string to a function.
Function breaks the string into letters.
stores letters in an array.
Finds all combinations of stored array letters.
prints combinations in inner HTML.
Like I said I am very new to JS and so please explain any answers and feel free to ask questions and I'll do my best to answer them quickly.
The code i've tried:
function combo() {
var string = prompt("Please Enter a String", "Dog");
var strArr = string.split("");
var temp = "";
for (var i = 0; i < strArr.length; i++) {
temp = strArr[i];
console.log(temp);
for (var j = i + 1; j < strArr.length; j++) {
temp += strArr[j];
console.log(temp);
}
}
<button onclick="combo()">Click Me!</button>
<p id="demo"></p>
Like I said most of this is just what I could find online because I don't fully understand the concepts.
Edit: does anyone have an example of how I could send the input from the user to the function?

Using the answer found in this CodeReview question, the following will work fine:
function generateAnagrams(word)
{
if (word.length < 2)
{
return [word];
}
var anagrams = [];
var before, focus, after, shortWord, subAnagrams, newEntry;
for (var i = 0; i < word.length; i++)
{
before = word.slice(0, i);
focus = word[i];
after = word.slice(i + 1, word.length + 1);
shortWord = before + after;
subAnagrams = generateAnagrams(shortWord);
for (var j = 0; j < subAnagrams.length; j++)
{
newEntry = focus + subAnagrams[j];
anagrams.push(newEntry);
}
}
return anagrams;
}
document.getElementById('btn_go').onclick = function()
{
var words = generateAnagrams(document.getElementById('input_word').value);
document.getElementById('output').value = words.join("\n");
}
input,
textarea {
display: block;
margin-bottom: 20px;
width:60%;
}
textarea {
height: 200px;
}
<input id="input_word" placeholder="Input your word here" />
<textarea id="output"></textarea>
<button id="btn_go">
Go!
</button>

Related

Create a sentence containing keywords with a specific CSS with JavaScript

I would like to form a sentence. However, in this sentence there are keywords that contain a specific CSS, according to a word dictionary contained in a JSON.
I don't know how to take into account the CSS of dictionary words and the rest of my sentence to display it correctly.
For example, I get a sentence with:
I have a problem with my network cable....
Problem being in my dictionary in a JSON file I want it to get a specific CSS. Problem should appear in red.
I can only display keywords. I don't see how to reconstruct my sentence.
for (let i = 0; i < features.length; i++) {
for (let j = 0; j < newDataLime.length; j++) {
if (features[i] === newDataLime[j].label) {
console.log(newDataLime[j].rgba);
spanCounter ++
// Max 12 span by each line for ver
if(spanCounter == 12){
spanCounter = 0;
}
fieldText.innerHTML = fieldText.innerHTML + `<span class="verbatim-dashboard__text__lime hide" style="background-color: ${newDataLime[j].rgba};">${features[i]}</span>`;
}
}
}
Features is a table that contains all the words in my sentence cut to each space. So it contains for our example ["I", "Have", "Problem" ... etc.]
And the variable newDataLime contains the keywords of the dictionary.
How can I correctly form my sentence?
I hope I have been clear enough. Thank you in advance!
You should try to replace the word in your sentence array, with the stylized word.
And then, when your array is fully computed, you'll be able to put it in any DOM element :
for (let i = 0; i < features.length; i++) {
for (let j = 0; j < newDataLime.length; j++) {
if (features[i] === newDataLime[j].label) {
console.log(newDataLime[j].rgba);
spanCounter++
// Max 12 span by each line for ver
if (spanCounter == 12) {
spanCounter = 0;
}
features[i] = `<span class="verbatim-dashboard__text__lime hide" style="background-color: ${newDataLime[j].rgba};">${features[i]}</span>`;
}
}
}
fieldText.innerHTML = features.join(" ");

Get all text from a Div after a '-' up until the first character

I'm trying to write a function that will find an instance of text within a div and console.log all text that is after the '-' character. After the '-' character there are sometimes spaces and tabs, so I want to remove these up until the first text character. Here's what I have so far (that is not working at all):
var countryData = $(".countries-title").next().text();
//var regex = /(?<= - ).*/g;
let stringArray = countryData.replace(/\t/g, '').split('\r\n');
console.log(stringArray);
Any help is appreciated. Thanks
console.log('here is a - whole bunch of text'.match(/-\s*(.*)$/)[1]) will log out "whole bunch of text". Is that along the lines of what you are looking for? Let me know if you want me to elaborate.
Assuming you want to maintain all hyphens and formatting after the first hyphen and subsequent spaces you could use:
let textAfterHyphen = countryData.replace(/\s*-\s*/, '');
I am not sure if I understood all but here you have my solution:
$(document).ready(function returnString() {
$("#click-target").on("click",function(){
var newString = [];
var resultString = [];
var onlyChar =$(".target").text();
newString = onlyChar.split("");
for(var i = 0; i < newString.length; i++){
if(newString[i] == "-"){
resultString = newString.slice(i+1,newString.length).join("");
}
}
var k = 0;
for(var j = 0; j < resultString.length; j++){
if(resultString.charCodeAt(j) > 64 && resultString.charCodeAt(j) < 91){
k += j;
}
}
console.log(resultString.slice(k,resultString.length));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target">Text- *^^^***Text to display</div>
<button id ="click-target">Click</button>

Javascript Random Name Guesser: Unresponsive Script Issues

This is my first post here and I am having trouble wording a question, so please bear with me as I have been on this issue for hours.
My friend and I have thought of a fun little function that is supposed to guess the user's name (through an <input> tag) in a certain amount of trials using the random number function to access string letters from an alphabet array numbered 0-25. The function is also supposed to give the user the number of trials it took to guess their name.
I keep getting a non-responsive script, (line 33 - The line containing the second "for loop").
var goal = document.getElementById("your_Name").value;
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var goalArray = goal.split("");
var trials = 0;
var guessArray = new Array();
var i;
var n;
for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
while (goalArray != guessArray){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + guessArray + " trials to guess correctly";
Any help or attempt to help would be immensely appreciated!
In case anyone was wondering: This little idea of ours was to test the randomness of Javascript's random function through trials (he made the same program in MatLab, so we are going to compare results of the random functions from both languages).
goalArray != guessArray is always true since they are two separate arrays; even if they contain the same elements.
Since they appear to just be arrays of individual letters in a-z you could compare them with something like goalArray + '' != guessArray, because the toString() of the arrays will compare correctly.
This is how I eventually got it to work (by nesting the while loop and second for loop in another for loop):
var goal = document.getElementById("your_Name").value;
var goalArray = goal.split("");
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var trials = 0;
var guessArray = [];
for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
for (x = 0; x < goalArray.length; x++){
while (goalArray[x] != guessArray[x]){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + trials + " trials to guess correctly";
}
}

show the location of each occurence of the character 'e' in a string

WORKED UP AN ANSWER. SCROLL TO BOTTTOM
I'm having trouble trying to display this character. For the most part, I have the code structure set but I'm having trouble storing the correct values in the arrays. Getting stuck and burned out!
wordString = 'i, always, have, fruit, for, breakfast, consisting, of, a, small, fruit, bowl, with, yogurt, on, top, of, the, fruit, but, if, it, is, doughnuts, I, always, have, two, sometimes, they, have, sprinkles, and, sometimes, not, i, never, have, cereal, or, eggs, this, breakfast, regimen, is, very, healthy, especially, the, doughnuts.';
var wordPosition = [];
var letterAppearance = wordString.match(/e/g);
var positionStart = 0;
for(i = 0; i <= letterAppearance.length; i++) {
positionStart = wordPosition[i];
if(positionStart === 0) {
positionString = wordString.substr(positionStart, wordString.length)
} else {
positionString = wordString.substr(wordPosition[i], wordString.length)
}
wordPosition[i] = positionString.indexOf('e');
}
Thanks for the help ahead of time
EDIT
Okay so I've worked on this a bit more and have something a bit simpler but have not yet gotten it to work. My values are not quite correct other than the 1st couple in the array
var wordPosition = [];
var letterAppearance = wordString.match(/e/g);
var positionStart = 0;
for( i = 0; i <= letterAppearance.length; i++){
wordPosition[i] = wordString.indexOf('e')+ positionStart;
positionStart = wordPosition[i];
}
Heres are the values that I get.
14,28,42,56,70,84,98,112,126,140,154,168,182,196,210,224,238,252,266,280,294,308,322,336,350,364
EDIT ANSWER FOUND
Okay, after working on it some more I've gotten the correct code for the answer. Here it is in the simplest form.
locations = " letter 'e' occurs at locations: ";
for (i = 0; i <= wordString.length; i++){
character = wordString.substr(i,1);
if(character === 'e'){
locations = locations + i.toString() + ",";
}
}
I think that's too complicated to search for just some 'e' positions. You can try this:
for (int i=0; i < /*string lenght*/ ; i++)
if (/*String char at i*/ == 'e')
/*Store position */
Okay, after working on it more, I've found the answer in it's simplest form.
locations = " letter 'e' occurs at locations: ";
for (i = 0; i <= wordString.length; i++){
character = wordString.substr(i,1);
if(character === 'e'){
locations = locations + i.toString() + ",";
}
}
Here is the output.
letter 'e' occurs at locations: 14,31,108,160,171,175,181,188,198,210,214,227,229,236,240,242,251,265,275,279,288,294,302,305,316,
You can try this:
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i+1);
}

Search Box Function Not Eliminating Correct Value

I am trying to make a simple website where the user types input into a search box, and every time a key is press, their input is compared against the first row of a 2 dimensional array which checks for character matches. If the character they input doesn't match anything, I want it to remove that specific bucket of the array. I have attempted to write basic code for this I thought would work, and have it up at the demo site linked. (Sorry I am just using a free host and havn't optimized the equation table at all so bear with it)
http://fakefakebuzz.0fees.net/
As you can see, the function is not eliminating the appropriate table rows. For example, typing "A" should not eliminate the "Average Current Equation" row because the first letter of that is A, which means matches should not = 0.
I have been looking through this code all morning, and cannot find where I went wrong. I also want to stick to vanilla js.
Any help?
Thanks so much.
I just debugged your code, and the function you use is narrowTable. first remove onkeypress from body node
<body onload="printTable()" onkeypress="narrowTable()">
and add onkeyup instead to you input, like this:
<input type="search" name="equationSearch" id="equationSearch"
placeholder="Equation Search" autofocus="" onkeyup="narrowTable()">
because when you use onkeypress the key value hasn't been added to the input box and your input value has no value in your function, which is:
function narrowTable() {
var newTableContent = "";
var matches = 0;
var input = document.getElementById("equationSearch").value;
//input has no value
for (var i = 0; i < tableData.length; i++) {
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
matches = 0;
}
for (var i = 0; i < tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
document.getElementById("table").innerHTML = newTableContent;
}
the other problem your code has is after printing your table, your tableData variable has changed because you have removed some of indexes. you should reset the tableData to its original value or you can do:
function narrowTable() {
//create a copy of your original array and use currenttableData instead
var currenttableData = tableData.slice();
var newTableContent = "";
var matches = 0;
//your code
}
the other problem here is the way you search for your input value:
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
you can easily do this, instead:
if(tableData[i][0].search("input") == -1){
tableData.splice(i, 1);
}
First, to check if a string is a substring of another string, you can use indexOf. It will return -1 if the string is not found in the other string.
Second, you shouldn't alter the array while you are still looping through it, unless you make sure to alter the counter variable (i in this case) appropriately.
var dataToRemove = [],
i;
for (i=0; i<tableData.length; i++) {
if(tableData[i][0].indexOf(input) == -1) {
// add the index to the to-be-removed array
dataToRemove.push(i);
}
// remove them in reverse order, so the indices don't get shifted as the array gets smaller
for(i = dataToRemove.length - 1; i >= 0; i--) {
tableData.splice(i, 1);
}
dataToRemove = [];
for (i=0; i<tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
I haven't tested this code, but it should at least give you a better idea of how to make this work.

Categories

Resources