Is there an easy way to move all elements up or down by a certain amount and then set the spaces that would be empty to null? Say I have an int array that is 5 elements long and I want to move them all up by 1. Now array[4] is equal to what array[3] was, array[3] is now what array[2] was and so on while array[0] is now null. Can I somehow modify Array.Push to do this?
One solution is to have a temp array and use that to shift the original array.
This is what I would do (js):
private var OriginalArray : int[];
private var tempArray : int [];
function Start ()
{
OriginalArray = new int[5];
OriginalArray = [2,3,48,9,5]; //--this instantiation is only for demonstration prposes
OriginalArray = Shift("down", OriginalArray, 3);
//-----------Print the new array------------------
var tempPrint2 = "";
for (i in OriginalArray)
{
tempPrint2 += " " + i.ToString();
}
Debug.Log(tempPrint2);
}
function Shift (direction : String, arr : Array, ShiftSpaces : int)
{
tempArray = arr;
//----------Print the original array-------------------
var tempPrint = "";
for (i in arr)
{
tempPrint += " " + i.ToString();
}
Debug.Log(tempPrint);
//------------------------------------------------------
for (i = 0; i < tempArray.length; i++)
{
if (direction == "up")
{
try
{
arr *= tempArray[i + ShiftSpaces];*
-
}*
-
catch (err)*
-
{}*
-
}*
-
else*
-
{*
-
try*
-
{*
-
if ((i + ShiftSpaces) < tempArray.length)*
-
{*
_ arr[i + ShiftSpaces] = tempArray*;_
_ }_
_ }_
_ catch (err)_
_ {}_
_ }_
_ }_
_ //-----------Erase the now unrelevant data--------------_
_ if (direction == “up”)_
_ {_
_ for (i = 0; i < ShiftSpaces; i++)_
_ {_
_ arr[(tempArray.length - 1) - i] = 0;//— I replaced with 0 for the print. It can’t print null. just switch to null if you like, and erase the prints*_
* }*
* }*
* else*
* {*
* for (i = 0; i < ShiftSpaces; i++)*
* {*
_ arr = 0;
* }
}
return arr;
}*
This script will do the job, but if anyone has a better idea, please share it._
may be a bit redundant but this may make things simpler for you if you want to manage arrays that way.
var copyArr:Array = new Array(myArr.length);
for (var i=copyArr.length-1;i>0;i--) {
copyArr*=myArr[i-1];*
}
copyArr will have all the values of myArr but everything pushed up one element then simply make myArr elements equal the same as the copy.
var copyArr:Array = new Array(myArr.length);
for (var i=0;i<copyArr.length-1;i++) {
copyArr*=myArr[i+1];*
}
and that pushes them down