在javascript中从数组生成随机块

问题描述 投票:2回答:1

我有一个对象数组,如下所示:

[
    {
      pVerb: "ask somebody out",
      meaning: "invite on a date"
    },
    {
      pVerb: "ask around",
      meaning: "ask many people the same question"
    },
    {
      pVerb: "add up to something",
      meaning: "equal"
    },
    {
      pVerb: "back something up",
      meaning: "reverse"
    },
    {
      pVerb: "back somebody up",
      meaning: "support"
    },
    {
      pVerb: "blow up",
      meaning: "explode"
    }
  ]

我需要迭代每个对象并生成更小的数组块,应该:

  1. 长度为3
  2. 包含pVerb的当前对象条目
  3. 被放置在随机位置

如下所示:

[
  [
    "!ask somebody out!",
    "add up to something",
    "back something up"
  ],
  [
    "add up to something",
    "!ask around!",
    "blow up"
  ],
  [
    "blow up",
    "back somebody up",
    "!add up to something!"
  ]
]

目前我有类似的东西,但它没有检查重复的条目或随机化的位置:

const randomNumber = (max: number, min: number) => {
      const num = Math.floor(Math.random() * (max - min + 1)) + min;
      return num;
    };

    const array: any[] = [];
    for (const n of array) {
      array.push([
        n.meaning,
        array[randomNumber(0, array.length)]
          .meaning,
        array[randomNumber(0, array.length)]
          .meaning
      ]);
    }

TL:DR

我需要一大块的块,其中一个块将是[pVerb of first object, any other two pVerbs from any other two objects(unique)]下一个块将有[pVerb of second object, ...]等。

javascript arrays typescript
1个回答
1
投票

您可以在shuffle的帮助下从数组中随机选择三个元素:

const partialShuffle = (values, count) => {
  for (let i = 0; i < count; i++) {
    const j = Math.floor(Math.random() * (values.length - i)) + i;
    [values[i], values[j]] = [values[j], values[i]];
  }
};

const nums = [1, 2, 3, 4, 5, 6];
partialShuffle(nums, 3);
console.log('' + nums.slice(0, 3));
partialShuffle(nums, 3);
console.log('' + nums.slice(0, 3));
partialShuffle(nums, 3);
console.log('' + nums.slice(0, 3));

既然数组中有三个随机值,您需要确保其中一个是当前值 - 对应于pVerb的值。检查它是否在那里。

  • 如果它已经存在,则不需要做任何其他事情。
  • 如果不存在,请选择随机项目进行替换。
const randomTripleIncluding = (values, value) => {
  partialShuffle(values, 3);
  const triple = values.slice(0, 3);

  if (!triple.includes(value)) {
    triple[Math.floor(Math.random() * 3)] = value;
  }

  return triple;
};

这会弄乱数组的顺序,所以你需要专门为改组使用复制,因为你在原始数组上进行迭代。总而言之,有类型:

const partialShuffle = (values: any[], count: number) => {
  for (let i = 0; i < count; i++) {
    const j = Math.floor(Math.random() * (values.length - i)) + i;
    [values[i], values[j]] = [values[j], values[i]];
  }
};

const randomTripleIncluding = <T>(values: T[], value: T): T[] => {
  partialShuffle(values, 3);
  const triple = values.slice(0, 3);

  if (!triple.includes(value)) {
    triple[Math.floor(Math.random() * 3)] = value;
  }

  return triple;
};

const input = [
  {pVerb: "ask somebody out", meaning: "invite on a date"},
  …
];

const scratchInput = input.slice();

const result = input.map(n => randomTripleIncluding(scratchInput, n));
© www.soinside.com 2019 - 2024. All rights reserved.