Skip to main content

Anticlockwise spiral view of diamond matrix elements in scala

Anticlockwise spiral view of matrix

Scala program for Anticlockwise spiral view of diamond matrix elements. Here more solutions.

/*
  Scala program for
  Anticlockwise spiral view of diamond element in matrix
*/
class SpiralTraversal()
{
	// Method which is displaying the Anticlockwise spiral 
	// Of matrix in diamond(mid) element
	def spiralView(matrix: Array[Array[Int]], 
      x: Int, y: Int, p: Int, q: Int, size: Int): Unit = {
        var k: Int = size;
		// Find the middle column
		var midCol: Int = y + ((q - y) / 2);
		// Get middle row (valid for odd square matrix)
		var midRow: Int = midCol;
		// Matrix are divided into 4 section
		// Starting of middle row and column in form of top
		// Case A
		// Top to Left-bottom
		var i: Int = midCol;
		var j: Int = 0;
		while (i > y && k > 0)
		{
			print("  " + matrix(x + j)(i));
			i -= 1;
			k -= 1;
			j += 1;
		}
		// Case B
		// Middle left to middle right bottom
		i = y;
		j = 0;
		while (i <= midCol && k > 0)
		{
			print("  " + matrix((midRow) + j)(i));
			i += 1;
			k -= 1;
			j += 1;
		}
		// Case C
		// Middle bottom to middle right side 
		i = midCol + 1;
		j = 1;
		while (i <= q && k > 0)
		{
			print("  " + matrix((p) - j)(i));
			i += 1;
			k -= 1;
			j += 1;
		}
		// Case D
		// Middle right side to  top middle 
		i = q - 1;
		j = 1;
		while (i > midCol && k > 0)
		{
			print("  " + matrix((midRow) - j)(i));
			i -= 1;
			k -= 1;
			j += 1;
		}
		if (x + 1 <= p - 1 && k > 0)
		{
			// Recursive call
			spiralView(matrix, x + 1, y + 1, p - 1, q - 1, k);
		}
	}
	def diamondAnticlockwise(matrix: Array[Array[Int]]): Unit = {
		var row: Int = matrix.length;
		var col: Int = matrix(0).length;
		// Check whether the given matrix is a valid odd shape or not
		if (row != col || col % 2 == 0)
		{
			// When Yes not a valid size
			println("\nNot a valid perfect Odd square matrix");
			return;
		}
		// (row*col)-((col+1)/2)*4 are provide the value of number of 
		// Diamond element
		spiralView(matrix, 0, 0, row - 1, 
                   col - 1, (row * col) - ((col + 1) / 2) * 4);
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: SpiralTraversal = new SpiralTraversal();
		// Define matrix 
		var matrix: Array[Array[Int]] = Array(
          Array(1, 2, 3, 4, 5), 
          Array(6, 7, 8, 9, 10), 
          Array(11, 12, -1, 15, 16), 
          Array(17, 18, 19, 20, 21), 
          Array(22, 23, 24, 25, 26)
        );
		task.diamondAnticlockwise(matrix);
	}
}

Output

  3  7  11  18  24  20  16  9  8  12  19  15  -1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment