Bullseye Matrix |MATLAB|JAVA


Bullseye Matrix

Given n (always odd), return output a matrix that has concentric rings of the numbers 1 through (n+1)/2 around the center point. Examples:
 Input  n = 3
 Output a is   [ 2 2 2
                        2 1 2
                        2 2 2 ]
 Input  n = 5
 Output a is   [ 3 3 3 3 3
                        3 2 2 2 3
                        3 2 1 2 3
                        3 2 2 2 3
                        3 3 3 3 3 ]

MATLAB CODE:


clc;
clear all;
close all;
x=input('Enter the number:');
Y=[];
m=(x+1)/2;
w=1;
while(m>0)
for i=w:x
    for j=w:x
        if(i==w || j==w || i== x|| j==x)
            y(i,j)=m;
        end
    end
end
m=m-1;
w=w+1;
x=x-1;
end

Explanation:




Output:



JAVA CODE:

import java.util.Scanner;
class Damba
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the number:");
int x=obj.nextInt();
int r=x;
int y[][]=new int[x][x];
int m=(x+1)/2;
int w=0;
while(m>0)
{
for(int i=w;i<x;i++)
{
for(int j=w;j<x;j++)
{
if(i==w || j==w || i==x-1 || j==x-1)
{
y[i][j]=m;
}
}
}
m=m-1;
x=x-1;
w=w+1;
}
System.out.println("The output is:");
for(int i=0;i<r;i++)
{
for(int j=0;j<r;j++)
{
System.out.print(y[i][j]+"\t");
}
System.out.println();
}

}
}


OUTPUT:


No comments