Hi Guys,
for example array1=[1,2,3,4,5,6] ,array2=[4,5,6] then your program need to give output as [4,5,6].
Solution:
Here am giving two solutions one by using an iteration method ,other one is using collections.
solution1:
----------------------------------
package logics;
public class comonBetweenTwoArrays {
public static void main(String []a)
{
int first[]=new int[]{1,2,3,4,5,6,7};
int second[]=new int[]{4,5,6,7,8,9,0};
for(int i=0;i<first.length;i++)
{
for(int j=0;j<second.length;j++){
if(first[i]==second[j])
{
System.out.print(first[i]);
}
}
}
}
}
output:
----------------------
4567
solution2:
--------------------------------------
package logics;
import java.util.*;
public class commonnInArraysUsingHastSet {
public static void main(String []a)
{
Set<Integer > s=new HashSet<Integer>();
Set<Integer> common=new HashSet<Integer>();
int first[]=new int[]{1,2,3,4,5,6,7,8,9,10};
int second[]=new int[]{0,4,5,6,7,8,9};
for(int index:first)
{
s.add(index);
}
for(int c:second)
{
if(s.contains(c))
{
common.add(c);
}
}
//printing common values
Iterator<Integer> i=common.iterator();
while(i.hasNext())
{
System.out.print(i.next());
}
}
}
output:
-------------------
456789
for example array1=[1,2,3,4,5,6] ,array2=[4,5,6] then your program need to give output as [4,5,6].
Solution:
Here am giving two solutions one by using an iteration method ,other one is using collections.
solution1:
----------------------------------
package logics;
public class comonBetweenTwoArrays {
public static void main(String []a)
{
int first[]=new int[]{1,2,3,4,5,6,7};
int second[]=new int[]{4,5,6,7,8,9,0};
for(int i=0;i<first.length;i++)
{
for(int j=0;j<second.length;j++){
if(first[i]==second[j])
{
System.out.print(first[i]);
}
}
}
}
}
output:
----------------------
4567
solution2:
--------------------------------------
package logics;
import java.util.*;
public class commonnInArraysUsingHastSet {
public static void main(String []a)
{
Set<Integer > s=new HashSet<Integer>();
Set<Integer> common=new HashSet<Integer>();
int first[]=new int[]{1,2,3,4,5,6,7,8,9,10};
int second[]=new int[]{0,4,5,6,7,8,9};
for(int index:first)
{
s.add(index);
}
for(int c:second)
{
if(s.contains(c))
{
common.add(c);
}
}
//printing common values
Iterator<Integer> i=common.iterator();
while(i.hasNext())
{
System.out.print(i.next());
}
}
}
output:
-------------------
456789
Không có nhận xét nào:
Đăng nhận xét