DEV Community

maxazillion
maxazillion

Posted on • Updated on

First post on this website.

Under this post is a function called the olBoxTurn. It's a problem that another much more experienced programer gave me to practice python. Since then, when I try other languages out I see if I can recreate this function without looking at my previous solves. For some reason I always forget how I solved it and what a pain in the butt the problem is. The cube turn is just taking a 3D array and turning it 90 degrees. You can make it easier and use just a set 3 X 3 cube and use indexing to make it simple. If you want a bit of a challenge then make it able to handle a variable size array. In my solution I struggled with my array resigning values on my source array. I tried to solve this by making the array a constant but I learned that constants didn't help me at all. I was unable to add things to a blank array the way that I had wanted to as well. So I decided to recreate a dummy array by using my create array function using the size of the source array. This way I could have an array that was completely unassociated with the source array... If you write a simple 3 X 3 array and the coordinates on a piece of paper you may notice something important. If you want the cube to turn to the right you want your top row ([0]) to be (0, 2) (1, 2) (2, 2). This is really helpful because the length of the array is 2! so you can simply make a loop within a loop (I know not the best) and set the Y coordinate to be the total size of the input array while filling a temporary array. This temporary array then is used to reassign values in the dummy array.Once the values are assigned the temporary array is set once again to an empty array.

javascript

function printArr(box){
  for(let i = 0; i < box.length; i++){
    console.log(box[i])
  }
}

function createBox(size){
  let retArr = [];
  let arrIncrement = 0;
  let counter = 1;

  if(size < 3){
    return
  }
  for(let i = 0; i < size; i++){
    retArr[i] = []
  }
  for(let i = 0; i < size; i++){
    for(let j = 0; j < size; j++){
      retArr[i][j] = counter;
      counter++;
    }
  }
  return retArr;
}

function olBoxTurn(box){
  const boxStatic = box;
  let boxManip = createBox(box.length);
  let tempArr = [];
  let size = box.length;
  let yCord = size - 1;

  for(let x = 0; x < size; x++)
  {
    for(let i = 0; i < size; i++){
      tempArr[i] = boxStatic[i][yCord]
    }
    boxManip[x] = tempArr;
    yCord--;
    tempArr = [];
  }
  return boxManip;
}



let arr = createBox(4)
arr = olBoxTurn(arr)
printArr(arr)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)