How to move index/position of an item in an array and shuffle others accordingly?

reorder an array according to given indexes
how to sort an array and keep track of the index in c
how to sort an array and keep track of the index in java
how to sort an array and keep track of the index in c++
arrangement and rearrangement of elements of array in java
reorder an array according to given indexes javascript
array slice
sort an array according to the order defined by another array

I was wondering if someone could explain how to move items in an array around in Ruby?

e.g

array = [a,b,c,d,e,f,l]

then becomes

array = [b,c,d,e,f,a,l]

I want to move "a" to where "f" is, but I do not want to switch them. I want to move "a" to that position and have "f" and all before it move down the array while the items before it such as "l" stays where they are. In this particular scenario duplicates do not exist. Additionally there is no need for keeping a copy of the original array unchanged.

*tidied up for clarification

You want to insert before the "l", which is position 6.

array = ["a", "b" ,"c", "d", "e", "f", "l"]
array.insert(5,array.shift)
=> ["b" ,"c", "d", "e", "f", "a", "l"]

Note that we specified position 5 because once the first element is removed (array.shift) the new numbering has "l" in position 5 (where formerly it was position 6).

If you did this in separate steps...

array = ["a", "b" ,"c", "d", "e", "f", "l"]
character_to_shift = array.shift # shift method removes and returns first entry in array
=> "a"
p array
=> ["b" ,"c", "d", "e", "f", "l"]
p.insert(5, character_to_shift) # insert inserts specified character at index position
    => ["b" ,"c", "d", "e", "f", "a", "l"]

Reorder an array according to given indexes, Given two integer arrays of same size, “arr[]” and “index[]”, reorder elements in (​iii) Copy old values of correct position (Stored in step (i)) to arr[i] and index[i] as  See the Pen JavaScript - Move an array element from one position to another-array-ex- 38 by w3resource (@w3resource) on CodePen. Improve this sample solution and post your code through Disqus. Previous: Write a JavaScript function to create a specified number of elements and pre-filled string value array.

You can do this by deleting 'a' out of the array and insert it back in at the index of 'f' + 1. Keep in mind that order of the code below is important since indexes shift after deleting an item.

array   = %w[a b c d e f l]
deleted = array.delete('a') # returns nil if not found
index   = array.index('f')  # returns nil if not found
array.insert(index + 1, deleted)
#=> ["b", "c", "d", "e", "f", "a", "l"]

If you'd change this to a one-liner you get a wrong result.

array.insert(array.index('f') + 1, array.delete('a'))
#=> ["b", "c", "d", "e", "f", "l", "a"]
#                                   ^ 'a' is placed one position to far

The reason this happens is because the order of execution is index -> (addition of index) -> delete -> insert. This can be fixed by removing the + 1. However this does only account for the case that 'f' is present after 'a'.

array = %w[f b c d e a l]
array.insert(array.index('f'), array.delete('a'))
#=> ["a", "f", "b", "c", "d", "e", "l"]
#     ^ 'a' is placed before 'f' (+ 1 is needed here)

Furthermore you would also have issues if one of the elements is not found since the result of index or delete might be nil. Doing this multiline allows you to handle exceptions by returning your method early.

Shuffling an array keeping some elements fixed, Therefore the process needs to only randomize the position of all other elements in the array. Thus leaving us with six different possible results: [1  Using array.splice (): The array.splice () method is usually used to add or remove items from an array. This method takes in 3 parameters, the index where the element id is to be inserted or removed, the number of items to be deleted and the new items which are to be inserted.

This solves your request for:

"first element to a specific position"

def move_first_element(a, x)
  first = a.shift
  a.insert(x, first)
end 

if you run this:

(0..6).each do |i|
  a = [0,1,2,3,4,5,6]
  move_first_element(a, i)
  puts "First element to index: #{i}"
  puts "#{a}"
end

the results are:

First element to index: 0
[0, 1, 2, 3, 4, 5, 6]
First element to index: 1
[1, 0, 2, 3, 4, 5, 6]
First element to index: 2
[1, 2, 0, 3, 4, 5, 6]
First element to index: 3
[1, 2, 3, 0, 4, 5, 6]
First element to index: 4
[1, 2, 3, 4, 0, 5, 6]
First element to index: 5
[1, 2, 3, 4, 5, 0, 6]
First element to index: 6
[1, 2, 3, 4, 5, 6, 0]

Array, The JavaScript Array class is a global object that is used in the Access an Array item using the index position let first = fruits.shift() // remove Apple from the front // ["Banana"] Other methods (e.g., push() , splice() , etc.) bounds of the array, the engine will update the array's length property accordingly: /* #move - Moves an array item from one position in an array to another. Note: This is a pure function so a new array will be returned, instead of altering the array argument. Arguments: 1. array: Array in which to move an item. (required) 2. moveIndex: The index of the item to move. (required) 3. toIndex

Array methods, But for arrays we usually want the rest of elements to shift and occupy the freed place. It starts from the position index : removes deleteCount elements and then Here and in other array methods, negative indexes are allowed. let arr = [ 1 , 2 , 3 ] ; shuffle ( arr ) ; // arr = [3, 2, 1] shuffle ( arr ) ; // arr = [2, 1,  The next step is for us to pick our random number:. let randomIndex = Math.floor(Math.random() * (i + 1)); let itemAtIndex = input[randomIndex]; The randomIndex variable stores the random number mapping to an item's position that we are interested in. Notice that the maximum value of our random number is not the array's length.

Shuffle an array, Write the function shuffle(array) that shuffles (randomly reorders) elements of the array. Multiple runs of shuffle may lead to different orders of elements. Improve this sample solution and post your code through Disqus. Previous: Write a Java program to test if an array contains a specific value. Next: Write a Java program to remove a specific element from an array.

C++ Vectors, When using a vector or array followed by square brackets with a subscript, The above extends to other data types as well; if we have a vector of strings for the index or subscript is that it must indicate a valid element in the vector. As with strings, class vector<type> provides a size_type to represent positions and sizes. The indexOf() method searches the array for the specified item, and returns its position. The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array. Returns -1 if the item is not found.

Comments
  • Do you want to always move the first element to a specific position (second last in this example)? Or do you always want to move a specific element (that equals a) move to the position of an element that equals f?
  • It would be interesting to know both, but first element to a specific position is enough.
  • When you are asked for clarification it is much better to edit your question than to elaborate in comments. Might you also want to know how to "move", say, "c" so that it follows "f"? If so, what if the array contains two "c"'s? Do you want to modify your array in place or do you want to create a new array with the desired ordering and leave the original array unchanged. You need to state your question in such a way that all these questions--and any others you can think of--are answered. The ability to state code requirements precisely is of crucial importance in your profession.
  • Readers may want to cut and paste your code so write array = [a,b,c,d,e,f,l] without the "e.g." preface. It is good that you included the local variable array, which is omitted in many SO questions. Assigning a variable to each of an examples inputs allows readers to refer to those variables in comments and answers. Also, => array [b,c,d,e, f , a ,l] makes no sense. If` you mean you want array to be modified to equal [b,c,d,e, f , a ,l], say that in words.
  • The type of manipulation you describe is more often expressed in terms of indices; for example, "I wish to modify the array array so that the element at index i is moved to index j and the order of all other elements is unchanged."
  • Thank you for taking the time to explain it to me.
  • What if the array were %w[a b a c d e f l]?
  • @CarySwoveland Then it would delete both 'a's and add one after the first 'f'.
  • That was my point. The OP says nothing about duplicate values, but if one "a" is to be "moved" it's a stretch to assume all other "a"'s should be deleted. The question certainly needs to be clarified.
  • @CarySwoveland It's possible to overcomplicate every question. In the provided scenario there are no duplicates. The same issue is present for the excepted answer. Who says that 'a' is always on the first position?