Traverse the array and exchange elements with adjacent neighbors

I'm facing a challenge with my BIP39 passphrase which consists of 24 words for recovering my cryptocurrency wallet. Unfortunately, the passphrase does not validate due to a checksum error in the last word. All the words in the passphrase are part of the available BIP39 words list, so my initial assumption is that I may have mistakenly switched the order of two adjacent words in the phrase/array.

My approach involves iterating through each word in an array, swapping it with the neighboring word, running a function check(phrase), reverting the swap operation, and moving on to the next word.

Here's an example:

initialPhrase = 'wordOne wordTwo wordThree'
firstAttempt = 'wordTwo wordOne wordThree'
secondAttempt = 'wordOne wordThree wordTwo'

How can I implement this logic using JavaScript assuming all words are stored in an array?

Answer №1

Below is a snippet of code that can be used:

var sentence = originalText.split(' ');

for(var index=0; index < sentence.length - 1; ++index){

sentence[index] = sentence.splice(index+1, 1, sentence[index])[0];

var finalSentence = sentence.join(' '); // your desired text

sentence = originalText.split(' ');

}

Answer №2

This example includes an undo feature:

Here is a JavaScript code snippet that demonstrates a custom validator and an undo functionality:

function validatePhrase(phrase) {
  //custom validation logic
  var phraseStr = phrase.join(' ');
  console.log(phraseStr);
  if (phraseStr == 'wordOne wordTwo wordFour wordThree') {
    console.log('valid!');
    return true;
  }
  return false;
}

function getValidPhraseWithUndo(phrase) {
  for (i=1; i<phrase.length; i++) {
    //swap elements
    phrase[i] = phrase.splice(i-1, 1, phrase[i])[0];

    if (validatePhrase(phrase)) {
      return phrase;
    }

    //undo the swap
    phrase[i] = phrase.splice(i-1, 1, phrase[i])[0];
  }
  return null;
}

var validatedPhrase = getValidPhraseWithUndo(['wordOne', 'wordTwo', 'wordThree', 'wordFour']);

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

PHP variables cannot be updated using JavaScript

Recently, I encountered an issue with a JavaScript function that calls an AJAX. Here is the code snippet: function addSquadronByID(id) { $.ajax ({ type: "POST", url: "server/get_squadron.php", data: { ...

Creating or accessing maps using TypeScript and Cloud Functions in Firebase

In my document, there is a map referred to as "map" with a specific structure: -document -map {id: number} {id2: number2} When the function first executes, only the document exists and I need to create the map with an initial entry. Before ...

What is the general type that the empty array [] represents?

When using int[], string[], T[], this represents a generic array. An array is treated as an object like any other. What is the specific open generic type of []? I presume it is a form of syntactic sugar similar to Array<>, but I have not come across ...

Unable to Add Dependency to Subclassed Object

In my setup, there are three classes that interact with each other. I am utilizing inversify for handling dependency injection. However, I encountered an issue when I injected the class MessageBroker into the derived class Repository and found that the Mes ...

Error in Typescript: 'SyncClient' not found in Twilio

While working on my Ionic app, I encountered an issue every time I attempted to use the twilio-chat library in my project through npm install. The error consistently appeared in the .d.ts files. Here is how I imported it in my provider : import { Client ...

combining two elements from an array using a specific string in a loop through each item

I'm working on merging two array elements with the string "OR" to create a single string of elements. The array is as follows: $myarray = array(2282396, 1801345) Here's the code I've implemented: $bool = ' OR '; foreach($myarray ...

What is the best way to display a Bootstrap alert above all other elements on the page?

I need help with adjusting the placement of my bootstrap alert. Currently, when the input box value is not valid and the button is clicked, the alert shows up below the input box. I would like it to appear in the middle of the page, on top of the text box. ...

Store the current user's authentication information from Firebase in the Redux state using React-Redux

I am facing an issue with persisting the state of my redux store using the currentUser information from Firebase Auth. The problem arises when I try to access auth.currentUser and receive null, which I suspect is due to the asynchronous loading of the curr ...

PHP: Utilizing $_SESSION variables for automatic form filling across various PHP pages

I've spent an hour searching for a solution to the problem below, but I haven't been able to find one that fits my specific issue. However, I have some ideas that I'll share after outlining the problem. Problem: In an html form within a ph ...

Retrieving information from a JSON array in Unity using C#

I have been experimenting with using the OpenWeatherMap API in Unity C# alongside JSONUtility, and I am encountering an issue accessing the "weather" array (specifically the "main" attribute), while being able to access other data such as "timezone" and "n ...

Exploring the features of AngularJS ui-router: ui-sref functionality and utilizing custom

My HTML looks like this: <span ui-sref="{{detailsArt(art.Id)}}" check-val></span> Within my directive check-val, I have the following code: link: function(scp, el, attr) { el.bind('click', function(event) { //some logic with ...

What steps do I need to take to ensure that this Regex pattern only recognizes percentages?

I am attempting to create a specific scenario where I can restrict my string to three digits, followed by a dot and two optional digits after the dot. For example: 100.00 1 10.56 31.5 I've developed a regex pattern that allows me to filter out any ...

Encountering issues with the hyperlink tag '<a>' in an HTML document

I've encountered an issue with the code on my HTML page: <body> <div align="center"> <a href="../index.html"> <img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base"> &l ...

Updating a state array nested inside another array in React

Currently, I am attempting to modify the state object within my react class-based component. The issue at hand is that my state consists of a two-dimensional array structured as follows: this.state = { items: [ { title: 'first depth' ...

What could be causing my bubble sorting function in the second main method to not execute?

I am currently facing an issue with my code. The first part seems to be working fine, however, the bubble sort portion is not executing as expected. I have attempted various modifications such as changing data types to doubles and including a return statem ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

The behavior of the 'typeof null' function in JavaScript is not functioning

I have a collection of objects where each object contains a key and an array as a value. You can see what I mean in this image. Some of the arrays had less than 20 elements, so I wrote some code to pad them with zeros. The result of running my code can be ...

What is the best way to merge IP addresses from an array and retrieve their corresponding ranges?

If I have an array containing these IP addresses: $array_ips = array(); $array_ips[] = "32.16.8.133"; $array_ips[] = "32.16.4.247"; $array_ips[] = "32.16.8.184"; $array_ips[] = "32.16.8.127"; $array_ips[] = "32.16.8.134"; $array_ips[] = "32.16.2.154"; $a ...

Experiencing frequent rerendering in React following the incorporation of socket io functionality

Currently working on a project similar to Omegle, take a look at some of the code below focusing on the useEffect functions. const Messanger =(props)=>{ let socket = props.socket; let intro; const myId = socket.id; const [readOnly,setReadOnly] = useSta ...

Tips for setting up Greasemonkey to automatically click on an unusual link on a particular website

I'm not a master coder by any means; I can handle some scripts but that's about it. Treat me like a total beginner, please! ;-) I want to automatically expand two specific links on a webpage using a GM Script. On a French dating site in the prof ...