-3

Imagine that we have two string arrays (name it A and B) with 1000 cells. A contains 1000 words but the B is null.

Now I want to copy each element of A to B but there should not be any relation or sequence between the element’s index in A and B, atleast harldy recognizable.

At the end array A will be nulled so I have to use array B, but I want to get the actual index of an element (index that the element has in array A).

Can u suggest any approach to solve this problem? (using a key or an equation to generate indexes would be nice)

  • So you want to copy the elements from one array into the other in different (arbitrary) order? Just mix your array and copy to `B`, where exactly is your problem? On Mixing an array? On copying the values to a new one? Your question is too broad and doesn´t include *any* own research-affords. – MakePeaceGreatAgain Aug 09 '17 at 13:35
  • Sounds like you want a reversible shuffle? You will have to be able to either store or generate the original index. – Lasse V. Karlsen Aug 09 '17 at 13:35
  • Are you looking for ``Array.IndexOf``? https://msdn.microsoft.com/en-us/library/7eddebat(v=vs.110).aspx – Rand Random Aug 09 '17 at 13:36
  • You might want to solve the simpler problem first, i.e. just shuffle (or at least indicate that you know how to solve that problem already). Because the question seems fairly broad currently. – Bernhard Barker Aug 09 '17 at 13:42
  • @LasseV.Karlsen yes i need a reversible shuffle. – Kyle Marriot Aug 09 '17 at 13:59
  • @Stonehead thanks, that was exactly what i need. – Kyle Marriot Aug 09 '17 at 14:01

1 Answers1

2

You can produce a random number for every element in your source-array and sort by this:

var r = new Random();
var B = A.OrderBy(x => r.Next(0, A.Length + 1)).ToArray();

This may produce the same numbers, but as from your question that won´t matter to much as long as you have some different order than your input-array A.

If you also need the original index of your element within A use the overload for Select that also uses the index of the current element:

var B = A.Select((x, i) => new { Index = i, Value = x })
    .OrderBy(x => r.Next(0, A.Length + 1)).ToArray();

Now your B-is an array of an anonymous type having an Index- and a Value-property.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111