Shift elements in array by index
You can use ranged subscripting and concatenate the results. This will give you what you're looking for, with names similar to the standard library:
extension Array {
func shiftRight(var amount: Int = 1) -> [Element] {
guard count > 0 else { return self }
assert(-count...count ~= amount, "Shift amount out of bounds")
if amount < 0 { amount += count } // this needs to be >= 0
return Array(self[amount ..< count] + self[0 ..< amount])
}
mutating func shiftRightInPlace(amount: Int = 1) {
self = shiftRight(amount)
}
}
Array(1...10).shiftRight()
// [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
Array(1...10).shiftRight(7)
// [8, 9, 10, 1, 2, 3, 4, 5, 6, 7]
Instead of subscripting, you could also return Array(suffix(count - amount) + prefix(amount))
from shiftRight()
.
Shifting array element by indexes
You could simply splice the array for adding an object at the wanted index.
var a = { index: 0, value: 'a' }, b = { index: 0, value: 'b' }, c = { index: 2, value: 'c' }, d = { index: 2, value: 'd' }, e = { index: 1, value: 'e' }, array = [];
function add(array, object) { array.splice(object.index, 0, object);}
add(array, a);add(array, b);add(array, c);add(array, d);add(array, e);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Change elements positions in an array and shift elements in between
You can use Array.prototype.splice
to cut out the element you want and insert at the desired index (the shifting will happen automatically):
function insertAndShift(arr, from, to) { let cutOut = arr.splice(from, 1) [0]; // cut the element at index 'from' arr.splice(to, 0, cutOut); // insert it at index 'to'}
let data = [ 0, 1, 2, 3, 4, 5, 6 ];
insertAndShift(data, 0, 3);console.log("[" + data + "]");
insertAndShift(data, 3, 0);console.log("[" + data + "]");
Shift the position of an element in an array
You need to cover the edge cases when the updated index is less than 0 OR greater than the array length. You can try following
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function move(array, index, offset) { const output = [...array]; const element = output.splice(index, 1)[0]; let updatedIndex = index + offset; if(updatedIndex < 0) updatedIndex++; else if (updatedIndex >= array.length) updatedIndex -= array.length; output.splice(updatedIndex, 0, element); return output;}
console.log(move(numbers, 3, -5));
How to shift array list elements to the right with some index at fixed position in java
Here's my simple solution making use of the existing ArrayList
class, though it might be best if you define your own implementation to meet your needs. Note that you may need to override more methods if you want to be sure they adhere to the rules you define:
public static class FixableArrayList extends ArrayList {
// ascending and descending views of the fixed indices
private final SortedSet fixedAsc;
private final SortedSet fixedDec;
public FixableArrayList() {
TreeSet treeSet = new TreeSet<>();
fixedAsc = treeSet;
fixedDec = treeSet.descendingSet();
}
public boolean addFixedIndex(int ind) { return fixedAsc.add(ind); }
public boolean removeFixedIndex(int ind) { return fixedAsc.remove(ind); }
public void move(int fromInd, int toInd) {
if (fromInd == toInd) {
return;
}
if (fixedAsc.contains(fromInd)) {
throw new IllegalArgumentException("Cannot remove from fixed index: " + fromInd);
}
if (fixedAsc.contains(toInd)) {
throw new IllegalArgumentException("Cannot add to fixed index: " + toInd);
}
super.add(toInd, super.remove(fromInd));
if (toInd < fromInd) {
// all between `from` and `to` shifted up, swap fixed indices down back into position
// iterate from low (toInd) to high (fromInd)
for (int i : fixedAsc.subSet(toInd, fromInd)) {
super.add(i, super.remove(i + 1));
}
} else {
// all between `from` and `to` shifted down, swap fixed indices up back into position
// iterate from high (toInd) to low (fromInd)
for (int i : fixedDec.subSet(toInd, fromInd)) {
super.add(i, super.remove(i - 1));
}
}
}
}
public static void main(String[] args) {
FixableArrayList values = new FixableArrayList<>();
values.addAll(Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80, 90, 100));
// set the indices that you want to remain fixed
values.addFixedIndex(3);
values.addFixedIndex(5);
values.addFixedIndex(9);
System.out.println(values);
values.move(0, 8);
System.out.println(values);
values.move(8, 0);
System.out.println(values);
}
How do I shift elements in an array to the left by 1 if there is a zero?
The main thing your algorithm/procedure should focus on is this:
If the value in an index is zero and it isn't the last index, perform two operations:
- Move the value of the index to the right
- Move the number previously at the right to the left.
The steps above are very important. I see that you've neglected step 2 in your question.
Here's how I'd handle it:
public int[] shiftArray(int[] arr){
for(int i = 0; i < arr.length - 1; i ++) {
if((arr[i] == 0) && (i != (arr.length - 1))){
int prev = arr[i];
int next = arr[i + 1];
arr[i] = next;
arr[i + 1] = prev;
}
}
return arr;
}
I hope this helps.. Merry coding!
How to shift all the items in an array to the right(by 1) using method map?
You could subtract one from the index and add the lenght to prevent negative values, get the reaminder with the length and take it as index for the element for mapping.
function shift(arr) { return arr.map((_, i, a) => a[(i + a.length - 1) % a.length]);}
const b = [{ value: "" }, 8, "left"];
console.log(shift(b));
Java, Shifting Elements in an Array
Assuming your array is {10,20,30,40,50,60,70,80,90,100}
What your loop does is:
Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}
Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}
What you should be doing is
Object temp = pool[position];
for (int i = (position - 1); i >= 0; i--) {
array[i+1] = array[i];
}
array[0] = temp;
Related Topics
Dyld'_Abort_With_Payload: Without an Error Message
Framework Not Found Googletoolboxformac
What's the Best Way to Find the User's Documents Directory on an Iphone
Connect Objective-C Framework to Swift iOS 8 App (Parse Framework)
Swift 3.0 Error: Escaping Closures Can Only Capture Inout Parameters Explicitly by Value
Testing Corelocation on iPhone Simulator
How to Display .Svg Image Using Swift
Use of Unresolved Identifier' in Swift
In Swift, How to Avoid Both Optionals and Nil Object References
Insert CSS into Loaded HTML in Uiwebview/Wkwebview
How to Create a Circular Progress Indicator for a Count Down Timer
Xcodebuild Different Provisioning Profile for Target Dependency
Afnetworking 3.0 Migration: How to Post with Headers and Http Body
In Swift, Array [String] Slicing Return Type Doesn't Seem to Be [String]
Swift Filter Dictionary Error: Cannot Assign a Value of Type '[(_, _)]' to a Value of Type '[_:_]'