Home > Back-end >  How to shuffle middle letters in between specific indexes of a word?
How to shuffle middle letters in between specific indexes of a word?

Time:04-20

Here what I have so far

mounted() {
  const randomVariants = [...Array(3)].map(() =>
    this.baseWord
      .split('')
      .sort(() => 0.5 - Math.random())
      .join('')
  )
  const variantsWithoutInitialWord = randomVariants.filter(
    (word) => word !== this.baseWord // !== this.baseWord , it  removes if baseWord  present
  )
  this.result = [...new Set(variantsWithoutInitialWord)] // removing duplicates
},

I need multiple value from one string value. like "orange", and generate multiple like:

  • "ornage"
  • "oregn"
  • "ograne"

The fist two characters & last one will be same. It will change only others characters & I also need the one original value. lik "xy.........z" only the x, y and z are static while the other inner characters will be randomly shuffled.

CodePudding user response:

This should work well

<template>
  <div>
    <p>
      The idea is to have a string, with it's first 2 indexes and last one
      untouched while all the others indexes are shuffled
    </p>
    <pre>combination found for string '{{ baseWord }}'</pre>
    <pre>actual list: {{ results }}</pre>
  </div>
</template>

<script>
const shuffledMiddleLetters = (array) =>
  array
    .split('')
    .sort(() => 0.5 - Math.random())
    .join('')

const wordMiddlePart = (word) => word.slice(2, word.length - 1)

export default {
  data() {
    return {
      baseWord: 'watermelon',
      results: [],
    }
  },
  mounted() {
    const shuffledMiddleLettersVariants = [...Array(50)].map(() =>
      shuffledMiddleLetters(wordMiddlePart(this.baseWord))
    )

    const dedupedVariants = [
      ...new Set([
        wordMiddlePart(this.baseWord),
        ...shuffledMiddleLettersVariants,
      ]),
    ]
    this.results = dedupedVariants.map((dedupedVariants) =>
      [
        this.baseWord.slice(0, 2),
        dedupedVariants,
        this.baseWord[this.baseWord.length - 1],
      ].join('')
    )
  },
}
</script>

This is how it looks

enter image description here

  • Related