Sie sind auf Seite 1von 4

Name Sonaal kalra

Rno.-45

Sap id 500046982

ASSIGNMENT 1
1. Write the Java code for the following pattern

2.

Ans.
package pro1;
import java.util.*;

public class s1 {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements : ");
int x = sc.nextInt();

int A[][] = new int[x][x];


int k=1, c1=0, c2=x-1, r1=0, r2=x-1;

while(k<=x*x)
{
for(int i=c1;i<=c2;i++)
{
A[r1][i]=k++;
}

for(int j=r1+1;j<=r2;j++)
{
A[j][c2]=k++;
}

for(int i=c2-1;i>=c1;i--)
{
A[r2][i]=k++;
}
for(int j=r2-1;j>=r1+1;j--)
{
A[j][c1]=k++;
}

c1++;
c2--;
r1++;
r2--;
}

/* Printing the Circular matrix */


System.out.println("The pattern is:");
for(int i=0;i<x;i++)
{
for(int j=0;j<x;j++)
{
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
}

2.
Write Java program to check whether two strings are anagrams or not, string is assumed to
consist of alphabets only. Two words are said to be anagrams of each other if the letters from
one word can be rearranged to form the other word. From the above definition it is clear that
two strings are anagrams if all characters in both strings occur same number of times. For
example "abc" and "cab" are anagram strings, here every character 'a', 'b' and 'c' occur only
one time in both strings. Our algorithm tries to find how many times characters appear in the
strings and then comparing their corresponding counts.
Ans.

package pro1;

import java.util.Arrays;

public class s2 {
static void isAnagram(String s1, String s2)
{

String copyOfs1 = s1.replaceAll("\\s", "");

String copyOfs2 = s2.replaceAll("\\s", "");

boolean status = true;

if(copyOfs1.length() != copyOfs2.length())
{

status = false;
}
else
{

char[] s1Array = copyOfs1.toLowerCase().toCharArray();

char[] s2Array = copyOfs2.toLowerCase().toCharArray();

Arrays.sort(s1Array);

Arrays.sort(s2Array);

status = Arrays.equals(s1Array, s2Array);


}

if(status)
{
System.out.println(s1+" and "+s2+" are anagrams");
}
else
{
System.out.println(s1+" and "+s2+" are not anagrams");
}
}

public static void main(String[] args)


{
isAnagram("Mother In Law", "Hitler Woman");

isAnagram("keEp", "peeK");

isAnagram("SiLeNt CAT", "LisTen AcT");

isAnagram("Debit Card", "Bad Credit");

isAnagram("School MASTER", "The ClassROOM");


isAnagram("DORMITORY", "Dirty Room");

isAnagram("ASTRONOMERS", "NO MORE STARS");

isAnagram("Toss", "Shot");

isAnagram("joy", "enjoy");
}

Das könnte Ihnen auch gefallen