i have one array with the following values [1,2,3,4,5]
i want to print a message when my array hold the values 1,2,3. How do I do this? :)
int[] myarray = new int[] {1,2,3,4,5};
if ( ... ) {
System.out.println("This array is on fire!");
I suppose you could do like this:
if (myarray[0]==1 && myarray[1]==2 && myarray[2]==3) {
.....
}
but if it's possible, i will avoid this. I wish to avoid the position in the array being a factor.
Unluckily Arrays.asList(myarray) doesnt work for int, as noted in the comments, i forgot...
So use Integer as Array-Type or convert first in an Integer-List:
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < myarray.length; index++)
{
intList.add(myarray[index]);
}
as pointed out here, then follow the old solution with this list:
if (intList.contains(1) && intList.contains(2) && intList.contains(3)) {
...
}
You could write a utility method as follows (assumes the array is sorted before hand please see the update if it's not the case):
public static boolean checkIfOnFire(int[] arr, int... nums) {
for(int n : nums) {
if(Arrays.binarySearch(arr, n) < 0) {
return false;
}
}
return true;
}
Test with:
int[] myarray = new int[] {1,2,3,4,5};
System.out.println(checkIfOnFire(myarray, 1, 2, 3));
System.out.println(checkIfOnFire(myarray, 1, 2, 7));
Prints:
true
false
Update:
Since I am using the Arrays.binarySearch. The input array to the checkIfOnFire method has to be sorted as it is in your example.
But if your array might not be sorted then checkIfOnFire has to be modified as follows:
public static boolean checkIfOnFire(int[] arr, int... nums) {
//make a copy of the original array
int[] copyArr = new int[arr.length];
System.arraycopy(arr, 0, copyArr, 0, arr.length);
//sort the copy
Arrays.sort(copyArr);
for(int n : nums) {
if(Arrays.binarySearch(copyArr, n) < 0) {
return false;
}
}
return true;
}
It ain't pretty, but if you wrote something like this:
public static boolean containsAll(int[] arrayToTest, int... values) {
return asList(arrayToTest).containsAll(asList(values));
}
public static List<Integer> asList(int[] values) {
List<Integer> asList = new ArrayList<Integer>(values.length);
for (int intVal : values) {
asList.add(intVal);
}
return asList;
}
You can then call it like this:
int[] myarray = new int[] {1,2,3,4,5};
boolean result = containsAll(myarray, 1, 2, 3);
If your wanted ints are non-negative, small, and dense; and you don't care about the order they appear in ints, then:
BitSet wanted = new BitSet();
wanted.set(1);
wanted.set(2);
wanted.set(3);
for (int i : ints) {
wanted.clear(i);
}
boolean hasAll = wanted.cardinality() == 0;
If you do care about order, then you probably want to test whether one array is a sub-sequence of another: Get the list of index in subsequence matching
To find the elements in any order in the array, first add the elements you're interested to a hash map. Then see if they are in the array.
Runtime: O(m) to add to map, to iterate over array O(n), m < n. Total O(n).
In the code below, call main() to run the sample I wrote.
Map<Integer,Boolean> lookFor = new HashMap<Integer,Boolean>();
void main(){
int[] array = new int[] {1,2,3,4,5};
addMeaningfulValues();
System.out.println( arrayHasValues(lookFor, array) );
}
void addMeaningfulValues(){
lookFor.put(1,false);
lookFor.put(2,false);
lookFor.put(3,false);
}
boolean arrayHasValues(Map<Integer,Boolean> values, int [] array){
//mark entries found in array
for (int i=0; i<array.length; i++){
if (values.containsKey(array[i])){
values.put(array[i], true);
}
}
//go over map entries and see if they have all been found in the array
for (Boolean crtValue: values.values()){
if (!crtValue){
return false;
}
}
return true;
}
Put it in a Collection or List and do a contains for each item you are looking for.
Integer[] myarray = {1,2,3,4,5};
List<Integer> intList = Arrays.asList(myArray);
if (intList.contains(1) && intList.contains(2) && intList.contains(3))
// print your message
Longer solution, but requires only one pass. Can be easily customized to check for any number of items.
public boolean onFire(int array[])
{
boolean found1 = false;
boolean found2 = false;
boolean found3 = false;
for (int i : array) {
if(i==1)
{
found1= true;
continue;
}
if(i==2)
{
found2= true;
continue;
}
if(i==3)
{
found3= true;
continue;
}
if(found1&&found2&&found3)
return true;
}
if(found1&&found2&&found3)
return true;
return false;
}
Make use of the containsAll method in the Collection interface.
Collection<Integer> coll = new ArrayList<Integer>();
Collection<Integer> test = new ArrayList<Integer>();
for( int i=1; i<=5; i++)
coll.add(i);
test.add(1);
test.add(2);
test.add(3);
System.out.println(coll.containsAll(test));
Due to wide use of collections java considered as collection is a framework and each collections consisting of a method contains(Object o) to check whether an element is existing or not in a collection.
so first we can convert the int[] array to a List
List<Integer> list=new ArrayList<Integer>();
int[] myarray = new int[] {1,2,3,4,5};
for(int i=0;i<myarray.length;i++)
{
list.add(myarray[i]);
}
please use list.contains(Object o) to check whether its existing or not
for(Integer i:list)
{
if(list.contains(1)&&list.contains(2)&&list.contains(3))
{
flag=true;
break;
}
}
and check the complete code below
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws IOException {
boolean flag=false;
List<Integer> list=new ArrayList<Integer>();
int[] myarray = new int[] {1,2,3,4,5};
for(int i=0;i<myarray.length;i++)
{
list.add(myarray[i]);
}
for(Integer i:list)
{
if(list.contains(1)&&list.contains(2)&&list.contains(3))
{
flag=true;
break;
}
}
if(flag)
{
System.out.println("yes contain");
}
else
System.out.println("NO");
}
}
Related
Is a List Sorted?
Write a program that checks if a list is already sorted. For a list to be sorted, the next element must NOT be smaller than the previous one.
Input
On the first line - you will receive a number N.
On the next N lines, you will receive a list of numbers, separated by a comma
Output
There are N lines of output
for each list you receive, print 'true' if sorted or 'false' otherwise.
Constraints
1 <= N <= 10
1 <= list.length <= 20
CODE:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static public boolean isSorted(ArrayList<Integer> list) {
boolean sorted = false;
for (int i = 1; i< list.size(); i++){
if (list.get(i-1)<list.get(i)) sorted = true;
}
return sorted;
}
public static void main(String[] args) {
ArrayList<String> inputs = createList();
ArrayList<Integer> resultList = transformList(inputs);
printList(resultList);
}
public static ArrayList<String> createList() {
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
ArrayList<String> list = new ArrayList<>();
while(length-->-1){
String input = scanner.nextLine();
list.add(input.replaceAll(",",""));
}
return list;
}
public static ArrayList<Integer> transformList(ArrayList<String> stringArrayList){
ArrayList<Integer> result = new ArrayList<>();
for (int i = 1; i< stringArrayList.size(); i++){
result.add(Integer.parseInt(stringArrayList.get(i)));
}
return result;
}
public static void printList(ArrayList<Integer> list){
for (int i = 0; i< list.size(); i++){
System.out.println(isSorted(list));
}
}
}
Input
3
1,2,3,4,5
1,2,8,9,9
1,2,2,3,2
My OUTPUT gives an incorrect result:
true
true
true
Expected output is supposed to be looked like:
true
true
false
Please, give me a hint to let me implement isSorted method correctly.
NOTE: I need to implement it without Guava Ordering class.
Think you just need an else statement. Once sorted is true, it never seems to return false if the other values are not in sorted order. Hence the issue with 1,2,2,3,2 . Where at first sorted is true but when comparing 3 with 2 sorted is suppose to be false, which you have not set as
static public boolean isSorted(ArrayList<Integer> list) {
boolean sorted = false;
for (int i = 1; i< list.size(); i++){
if (list.get(i-1)<list.get(i))
sorted = true;
else{
sorted = false;
}
}
return sorted;
}
No need to traverse the whole list. As soon as you find that list.get(i-1)>list.get(i) which means that the list is not sorted, you can break out of the loop.
static public boolean isSorted(ArrayList<Integer> list) {
boolean sorted = true;
for (int i = 1; i < list.size(); i++) {
if (list.get(i - 1) > list.get(i)) {
sorted = false;
break;
}
}
return sorted;
}
You should update the sorted value if not sorted.
static public boolean isSorted(ArrayList<Integer> list) {
boolean sorted = false;
for (int i = 1; i < list.size(); i++) {
sorted = list.get(i - 1) <= list.get(i);
}
return sorted;
}
Need to do a method which takes ArrayList<ArrayList<<Integer>> and an Integer which then returns an ArrayList<ArrayList<<Integer>> from the orginal ArrayList<ArrayList<<Integer>> which do not contain the Integer argument e.g
ArrayList<ArrayList<<Integer>>
[[1,2,3],[7,5],[4,4,2],[8,12,3]] and Integer 2 should return
[[7,5],[8,12,3]]. arraylist of arraylist integers.
not entirely sure how to access the inner loop
You can use contains() rather than worrying about writing an inner loop yourself.
Also, removing elements from lists while iterating is tricky. So, since you are not modifying the list and seem to be expected to return one, then just make a new list and add rather than remove.
public static ArrayList<ArrayList<Integer>> removeTheNumber(ArrayList<ArrayList<Integer>> n , Integer p){
ArrayList<ArrayList<Integer>> a = new ArrayList<>();
for(int i=0; i < n.size(); i++){
ArrayList<Integer> innerList = n.get(i);
if (!innerList.contains(p)) a.add(innerList);
}
return a;
}
You can use .contains of the inner lists to check as Integer class supports this. Below is a function and its test.
public ArrayList<ArrayList<Integer>> removeTheNumber(ArrayList<ArrayList<Integer>> lists, Integer n) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
for (ArrayList<Integer> list: lists ) {
if (!list.contains(n))
result.add(list);
}
return result;
}
#Test
public void testRemoveNumber() {
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
lists.add(Lists.newArrayList(2,7,8));
lists.add(Lists.newArrayList(6,7,9));
lists.add(Lists.newArrayList(3,2,6));
ArrayList<ArrayList<Integer>> result = removeTheNumber(lists, 2);
Assert.assertArrayEquals(lists.get(1).toArray(new Integer[]{}), result.get(0).toArray(new Integer[]{}));
result = removeTheNumber(lists, 7);
Assert.assertArrayEquals(lists.get(2).toArray(new Integer[]{}), result.get(0).toArray(new Integer[]{}));
result = removeTheNumber(lists, 6);
Assert.assertArrayEquals(lists.get(0).toArray(new Integer[]{}), result.get(0).toArray(new Integer[]{}));
}
If you want to use two loops you can write it like this (where array is your input array, and toSearch is your integer):
ArrayList<ArrayList<Integer>> arrayToReturn = new ArrayList<>();
for(ArrayList<Integer> listInner : array){
boolean found = false;
for(Integer elem : listInner) {
if (elem == toSearch)
found=true;
}
if(found!=true)
arrayToReturn.add(listInner);
}
arrayToReturn.stream().forEach(System.out::println);
Of course i reccomend to use java 8, and then you can simply write it like this:
arrayToReturn = array.stream().filter(elem ->
!elem.contains(toSearch)).collect(
Collectors.toCollection(ArrayList<ArrayList<Integer>>::new));
arrayToReturn.stream().forEach(System.out::println);
Let's pretend you have
ArrayList<ArrayList<Integer>> myArrayList = [[1,2,3],[7,5],[4,4,2],[8,12,3]];
for (int i = 0; i < myArrayList.length; i++) {
//...
}
Your variable i is iterating through the initial ArrayList, which contains another ArrayList. So, myArrayList[i] will yield another ArrayList, which also has a length.
Building on this we have:
for (int i = 0; i < myArrayList.length; i++) {
ArrayList<Integer> inner = myArrayList.get(i);
for (int j = 0; j < inner.length; j++) {
//now we may check for the existence of our integer
}
}
I want to find the duplicate numbers in the array.
For this am comparing in the following way, but I am not able to get the desired output
The new array should contain numbers without duplicacy.
I have tried the following
public static void main(String[] args) {
int[] a={1,2,3,6,3,5,7,3,9,7};
int[] k=new int[a.length];
for(int i=0;i<a.length;i++){
for(int j=1;j<a.length;j++){
if(a[i]==a[j]){
k[i]=a[j];
}
}
}
for(int n=0;n<k.length;n++){
System.out.print(k[n]);
}
}
If you are not interested in finding the duplicates but only interested in removing them. the following approach would work.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Test
{
public static void main(String args[])
{
Integer[] a = new Integer[] {1,2,3,6,3,5,7,3,9,7};
Set<Integer> numberset = new HashSet<Integer>(Arrays.asList(a));
Integer[] output = numberset.toArray(new Integer[0]);
for (Integer i : output)
{
System.out.println(i);
}
}
}
Nice one.
public static void main(String[] args) {
int[] a={1,2,3,6,3,5,7,3,9,7};
int[] k=new int[a.length];
Set<Integer> dups = new HashSet<Integer>();
int index = 0;
for(int i=0;i<a.length;i++){
boolean found = false;
for(int j=1;j<index && !found;j++){
if(a[i]==k[j]){
// found duplicate.
found = true;
dups.add(a[i]);
}
}
if (!found)
{
k[index++]=a[i];
}
}
System.out.print("Unique entries: ");
for(int n=0;n<index;n++){
System.out.print(k[n]+" ");
}
System.out.println("\nDups:" + dups);
Output
Unique entries:1 2 3 6 5 7 9
Dups:[3, 7]
You should iterate your inner loop from i+1 to length, change it to following.
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
if(a[i]==a[j]){
k[i]=a[j];
}
}
}
The problem with your code is, It will check all the values at a[i] from 1 to n and will compare the values. It will be true for all i such that 1 <= i < n.
I tried to print the string without duplicate but i not getting the proper output and here I exposed my code snippets.
class Duplicatestring
{
public static void main(String [] args)
{
String word = "";
String[] ip ={"mani" ," manivannan","raghv ","mani"};
for(int i =0; i<ip.length; i++)
{
for(int j = i+1; j<=ip.length; j++)
{
if(ip[i].equals(ip[j])){
word = word+ip[i];
}
}
System.out.println(word);
}
}
}
And one more thing is I don't want use the collections that is my task and pleas give any proper solution for this.
Example:
Input -> {mani, manivanna,raghv, mani};
output -> {mani, manivanna,raghv}
If you don't want to use collections then I assume it's a homework, so I don't want to provide you a full solution, but I'll guide you.
You can have a helper array of the size of the original array. Now you write two nested loops and for each word, if you find a duplicate, you mark the helper array with 1.
After this procedure you'll have something like this in the helper array:
[0,0,0,1]
Now you iterate on the arrays in parallel and print the element only if the corresponding index in the helper array is 0.
Solution is O(n2).
Your loop is incorrect.
To solve the problem, you can use a Set to eliminate duplicated words.
If the problem must be solved by O(n^2) loops, the following code will work:
public class Duplicatestring {
public static void main(String[] args) {
String[] ip = { "mani", " manivannan", "raghv ", "mani" };
for (int i = 0; i < ip.length; i++) {
boolean duplicated = false;
//search back to check if a same word already exists
for (int j = i - 1; j >= 0; j--) {
if(ip[i].equals(ip[j])) {
duplicated = true;
break;
}
}
if(!duplicated) {
System.out.println(ip[i]);
}
}
}
}
if you want to remove the duplicate from the array call the below method and pass the array has the duplicate values.. it will return you the array with non-duplicate values..
call method here
ip = removeDuplicates(ip);
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}
it will return you the non duplicates values array..!!
u may try this:
public class HelloWorld{
public static void main(String []args){
String[] names = {"john", "adam", "will", "lee", "john", "seon", "lee"};
String s;
for (int i = 0; names.length > i; i ++) {
s = names[i];
if (!isDuplicate(s, i, names)) {
System.out.println(s);
}
}
}
private static boolean isDuplicate(String item, int j, String[] items) {
boolean duplicate = Boolean.FALSE;
for (int i = 0; j > i; i++) {
if (items[i].equals(item)) {
duplicate = Boolean.TRUE;
break;
}
}
return duplicate;
}
}
output
john
adam
will
lee
seon
if string order does not matter for you, you can also use the TreeSet.. check the below code.. simple and sweet.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class MyArrayDuplicates {
public static void main(String a[]){
String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
System.out.println();
Iterator<Integer> iterator = unique.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
it will print as -
[five, four, one, three, two]
five
four
one
three
two
I have an array of strings, and I want to delete a particular string from that array. How can I do that? My code is:
private void nregexp(){
String str_nregexp = i_exp_nregexp.getText();
boolean b;
for(int i=0; i<selectedLocations.length; i++){
b= selectedLocations[i].indexOf(str_nregexp) > 0;
if(b){
String i_matches = selectedLocations[i];
........
........
}
}
}
I have to remove i_matches from selectedLocations.
I depends what you mean by "delete a particular String from an array". If you wish to remove its value, you can simply set its value to null, however if you mean actually remove that element from the array (you have an array of 5 elements and you want the result after deleting the element to be 4), this is not possible without copying the array with the item removed.
If you want this behavior, you might want to take a look at a dynamic list such as ArrayList or LinkedList
Edit: If you wanted a simple method to copy the array into an array with the String removed, you could do something like:
List<Foo> fooList = Arrays.asList(orgArray);
fooList.remove(itemToRemove);
Foo[] modifiedArray = fooList.toArray();
You will need to copy the array to a smaller array, omitting the string you don't want. If this is a common situation, you should consider using something other than an array, such as LinkedList or ArrayList.
If you really want to do it yourself, here is an example:
import java.util.Arrays;
public class DelStr {
public static String[] removeFirst(String[] array, String what) {
int idx = -1;
for (int i = 0; i < array.length; i++) {
String e = array[i];
if (e == what || (e != null && e.equals(what))) {
idx = i;
break;
}
}
if (idx < 0) {
return array;
}
String[] newarray = new String[array.length - 1];
System.arraycopy(array, 0, newarray, 0, idx);
System.arraycopy(array, idx + 1, newarray, idx, array.length - idx - 1);
return newarray;
}
public static void main(String[] args) {
String[] strings = { "A", "B", "C", "D" };
System.out.printf("Before: %s%n", Arrays.toString(strings));
System.out.printf("After: %s%n",
Arrays.toString(removeFirst(strings, "D")));
}
}
You cannot change the length of the array, after initializing an array its length is set. So you cannot delete the element directly, you can only replace it, also with null.
String[] arr = new String[10];
// fill array
...
// replace the fifth element with null
arr[4] = null;
If you want to change the length of the Array you should try a list instead:
List<String> list = new ArrayList<String>();
// fill list
...
// remove the fifth element
list.remove(4);
Could you show us your code? Why don't you use ArrayList, as it has a remove(index) and remove(object) support?
Edit: Perhaps
private void nregexp() {
String str_nregexp = i_exp_nregexp.getText();
boolean b;
List<String> list = new ArrayList<String>(Arrays.asList(selectedLocations));
for(Iterator<String> it = list.iterator(); i.hasNext();){
String e = it.next();
b = e.indexOf(str_nregexp) > 0;
// b = e.matches(str_regexp); // instead?
if(b){
String i_matches = s;
it.remove(); // we don't need it anymore
........
........
}
}
selectedLocations = list.toArray(new String[list.size()]);
}
I've reached this solution that allows you to remove all the elements that equal the removal element:
private static <T> T[] removeAll(T[] array, T element) {
if (null == array)
throw new IllegalArgumentException("null array");
if (null == element)
throw new IllegalArgumentException("null element");
T[] result = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length);
int j = 0;
for (int i = 0; i < array.length; i++) {
if (!element.equals(array[i]))
result[j++] = array[i];
}
return Arrays.copyOf(result, j);
}
I also did some benchmarking and this solution is definitely better then using Lists. Although, if performance is not a problem here, I would use Lists.
If you really need to remove only one element (the first) #kd304 has the solution.