Is there a way to verify if a word is constructed using characters from separate arrays?

I am currently developing a word game using Vue.

The concept is simple - the player receives a random string of characters and has to input a word that can be formed from those characters. For example, given "ABEOHSTD", the user could enter "BASE" for a score of 4.

One of the challenges I'm facing is verifying the entered words against an external word list stored in a .txt file (which is another issue I need to address separately). Specifically, I'm struggling with confirming whether the words can actually be created using the provided random string of characters.

I'm unsure how to approach ensuring that each letter can only be used as many times as it appears in the original array, or even how to store and calculate the scores. Right now, my main focus is on getting this initial functionality working correctly.

My current approach involves splitting both the entered word and the random string into arrays of individual characters, then looping through them to check if each character in the entered word is included in the random string array.


splitUserCurrentWord = this.userAttemptedWord.split("");
for (var i = 0; i <= splitUserCurrentWord.length; i++) {
    if (this.randomStringForGame.split("").includes(splitUserCurrentWord[i])) {
        return true;
    } else {
        return false;
    }
}

As it stands, I expect the function to return true only if all the letters in the user inputted word are present in the random string array. However, it seems to only consider the first letter of the array, which is problematic because as long as the first letter matches, it registers as correct regardless of subsequent letters.

You can view the current state of the project on jsfiddle: https://jsfiddle.net/sk4f9d8w/

Answer №1

Your return statement is causing the loop to exit after the first iteration.

An alternative approach is to utilize Array.every to validate all letters and String.includes to confirm if the letter belongs to the specified string

const randomString = "ABEOHSTD";

console.log(isWordValid(randomString, "BASE"));
console.log(isWordValid(randomString, "BASEU"));

function isWordValid(validLetters, attemptedWord) {
  const attemptedWordSplitted = attemptedWord.split("");
  return attemptedWordSplitted.every(attemptedLetter => validLetters.includes(attemptedLetter));
}

If you do not allow the same letter to be used multiple times, an alternate method involves removing the utilized letter from the list of approved letters

const randomString = "ABEOHSTD";

console.log(isWordValid(randomString, "BASE"));
console.log(isWordValid(randomString, "BAASE"));
console.log(isWordValid(randomString, "BASEU"));

function isWordValid(validLetters, attemptedWord) {
  const validLettersSplitted = validLetters.split("");
  const attemptedWordSplitted = attemptedWord.split("");
  return attemptedWordSplitted.every(attemptedLetter => {
    const letterIndex = validLettersSplitted.indexOf(attemptedLetter);
    if(letterIndex > -1){
      validLettersSplitted.splice(letterIndex, 1);
      return true;
    } else {
      return false
    }
  });
}

Answer №2

You're headed in the right direction! It's important to carefully examine each letter in the user word and compare it to the letters in the random word. If a letter matches, remove it from the random word to prevent it from being used again.

let randomWord = "ABEOHSTD";
let userWordThatFail = "BAASE";
let userWord = "BASE";

// Optional: convert both words to uppercase.

// Splitting the words into individual letters for easier processing
let randomLetters = randomWord.split('');
let userLetters = userWord.split('');

let score = 0;

// Iterating through each letter in the user input
userLetters.forEach((letter) => {
  // Check if the letter exists in the random word.
  let indexOfTheCurrentLetter = randomLetters.indexOf(letter);
  // If the letter exists, remove it and increase the score.
  if(indexOfTheCurrentLetter !== -1) {
    randomLetters.splice(indexOfTheCurrentLetter, 1);
    score++;
  }
});

// If the user input contains letters not present in the random word
if(score < userLetters.length) {
  console.log('fail');
} else {
  console.log('win : ' + score);
}

Answer №3

One way to efficiently check for valid characters in a string is by utilizing the Set object in JavaScript.

By creating a reusable function that utilizes the power of Set, we can achieve a linear time-complexity of O(n) where n is the length of the string being tested:

function testFor(validChars) {
  const charSet = new Set(validChars);
  return testString =>
    Array.prototype.every.call(testString, c => charSet.has(c));
}

// Example usage:

const testForABC = testFor("ABC"); //returns a function

console.log(testForABC("AABBCC")); //true
console.log(testForABC("abc")); //false

This approach leverages the constant lookup time of Set, making it a much more efficient solution compared to iterating through characters in a list for each comparison.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering the Art of Modifying HTML with Node.js

Is it possible to manipulate HTML using Node.js? 1. First, I need to retrieve data from a database. 2. Then, I need to modify or add HTML code within Node. In essence, the goal is to fetch data and integrate it into an HTML file. The JavaScript snippet ...

Tips for building a responsive website with JavaScript and media queries:

Looking to ensure my website is responsive, but with specific requirements: Need the navigation bar to transition into a vertical hamburger drop-down menu when screen size is reduced, and it must be coded in JavaScript Planning to implement a mobile-firs ...

What is the best method to retrieve an Element using both its ID and value?

Is there a way to disable specific radio buttons based on both their id and value attributes? I have three radio buttons that need to be disabled. <input id="selectedAnswerIDforQ15" name="selectedAnswerIDforQ15" type="radio" value="78" /> <input ...

Trouble viewing Geojson map on website

I'm having trouble generating a map. I am currently working with one of the geojson files provided by The New York Times ("census_tracts_2010.geojson") from this link ( https://github.com/dwillis/nyc-maps ). If someone could take a look at my code be ...

Although XPath works in Chrome, it is not compatible with Selenium

My current task involves finding an element based on its content that includes single quotes. I have successfully achieved this using vanilla JS as shown below: singleQuotes = document.evaluate("//div[contains(text(), \"'quotes'\")]" ...

How to transform a byte array into a String in Java

Looking for a way to convert a byte array to a string, but encountering an issue where the resulting string has 00 before every digit extracted from the array. The desired output should be: 49443a3c3532333437342e313533373936313835323237382e303e However, ...

How can JavaScript be used to make an AJAX request to a server-side function?

I am diving into the world of AJAX and feeling a bit uncertain about how to structure my AJAX call. $.ajax({ type: "POST", url: "Default.aspx/function", data: '{ searchBy: id }', contentType: "application/json; charset=utf-8" }). ...

In the world of Knockout JS, forget about using e.stopPropagation() because it won't

In my table, I have two actions that can be performed: Click event on the row level and click while checking a checkbox inside that row. However, when the checkbox is checked, I do not want the click event on the row to be triggered. <tbody data-bin ...

Vue's beforeEnter does not function as expected when defined for child routes within routes

Currently, I am working with vue 2.6.10 and have defined my routes in vue's router.js as shown below: Vue.use(Router) const router = new Router({ mode: "history", base: process.env.BASE_URL, routes: [ { path: '/login', ...

A JavaScript popup displaying selectable options and a callback function

Is there a feature in Javascript that is similar to Java's alert builder? I need a button that, when clicked, will display an alert with various options. When an option is selected, it should trigger a callback function passing the chosen option along ...

Why does mapping only give me the last item when I try to map onto an object?

Why does mapping onto an object only give me the last item? Below is the object displayed in the console: 0: {Transport: 2} 1: {Implementation: 9} 2: {Management: 3} When I use ngFor, it only provides the last item const obj = this.assigned_group; // r ...

The Chrome extension does not function properly within Gmail

What is the purpose of this extension? Whenever a keydown event occurs on a textarea, my extension's content script, detector.js, calls a function to manipulate the values of the textarea. Since Gmail uses a div with role='textbox' instead ...

Having trouble extracting values from this JSON array - need help parsing it

I am looking to extract the company names and their values from this JSON data. What is the best approach to achieve this? Below is a snippet of the JSON output: Array ( [version] => 2 [query] => web developer [location] => Hyderab ...

Is it possible for Angular to either remove my object from the scope or combine it with my provider during execution?

I'm trying to figure out how to handle an object called xyzApi in my code. This object is defined outside of my angular code and contains classes and utility methods that I want to make accessible to the rest of my API. This is what it looks like (in ...

Encounter a scope.router.go error when using Vue.js with System.js

During my testing of a Vue.js-System.js app before transitioning to webpack2, I encountered an issue with the routing pattern. In the OPA Memberships component, when clicking on a link, I aim to request a Registration page from the router. To achieve this ...

Tips for extracting information from a JSON file using $routeParams in AngularJS

https://i.stack.imgur.com/NQCpy.png I am currently encountering an issue with retrieving data using $routeparams. Here is a description of my problem: Retrieving the URL to redirect console.log($routeParams); console.log($routeParams.json_url); $.getJS ...

When trying to implement a dark/light theme, CSS variables may not function properly on the body tag

Currently, I am in the process of developing two themes (light and dark) for my React website. I have defined color variables for each theme in the main CSS file as shown below: #light{ --color-bg: #4e4f50; --color-bg-variant: #746c70; --color-primary: #e2 ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

resetting form with submission action

I am working with the following code snippet: <form id="form-lecturerInfo-setup"> ... <input type="submit" value="Submit" /> <input type="reset" value="Reset" /> </form> <script> $('#form-lecturerInfo-se ...

Using Javascript to determine the frequency of a JSON array with ESLINT version 6

I'm struggling to create an algorithm that counts the occurrences while adhering to ESLint's strict standards in JavaScript. Here is my input table: [ { "id": 2, "name": "Health", "color": "0190fe" }, { "id": 3, "name": ...