i was reading into this thread
Removing an element from an Array (Java)
And saw you could use ArrayUtils but i am unsure how?
This is the code so far
package javatesting;
import static java.lang.System.*;
public class main
}
public static int countIt( int[] iRay, int val )
{
int count = 0;
for(int item : iRay)
{
if( item == val )
{
count = count + 1;
}
}
return count;
}
public static int[] removeIt( int[] iRay, int val )
{
return null;
}
public static void printIt( int[] iRay )
{
for(int item : iRay)
{
out.print(item + " ");
}
}
public static void main(String[] args)
{
int[] nums = {7,7,1,7,8,7,4,3,7, 9,8};
printIt( nums );
System.out.println("\ncount of 7s == " + countIt( nums, 7 ));
nums = removeIt( nums, 7 );
printIt( nums );
System.out.println("\ncount of 7s == " + countIt( nums, 7 ));
}
I tryed placing it in removeIt but i dont understand how it should connect?
My AP Teacher didnt explain it to us
If possible could one of you link me a tutorial for java
As i understand it asks for the count of non sevens that why i want ot create a array with the seven's removed using the ArrayUtils
(i am using eclipse if it matters)
The usage of ArrayUtils.removeElement is pretty straight forward and would look like this:
public static int[] removeIt( int[] iRay, int val )
{
return ArrayUtils.removeElement(iRay, val);
}
Also, avoid asking things like "If possible could one of you link me a tutorial for java." The StackOverflow community wont respond to generic request like this if it can easily be Googled.
Proper usage can be found here.
You can use
ArrayUtils.removeElements(array, element)
However, since you this is for a class, your professor probably doesn't want you to be using any libraries. In which case you would create a new array, loop through the old one, extract all entries whose value is not 7, add them to the new array and return it.
If you wanted, you could also do a while loop of
while(ArrayUtils.indexOf(array, 7) =! -1){
ArrayUtils.removeElement(array, 7)
}
However, please make sure you are allowed/encouraged to use libraries. And if you are, make sure you download the ArrayUtils.jar and include it in your build path, otherwise you will not be able to use its static methods.
Related
In c++ permutations of an array can be generated using the function next_permutation. Is there a java equivalent of such a function to generate permutations of a size N array?
I am trying to come up with an equivalent recursive implementation but am struggling to solidify my logic.
There isn't a built-in function like this in java. You'll have to create your own, which is not that complicated. I'll provide an edit to this answer momentarily with a solution (not necessarily the best solution)
public static void printperms(int[] perm, boolean[] used, int k)
{
if (k == perm.length) print(perm);
for (int i=0; i<perm.length; i++) {
if (!used[i]) {
used[i] = true;
perm[k] = i;
printperms(perm, used, k+1);
used[i] = false;
}
}
}
you can then create a new method, like so, to call it:
public void perms(int n){
printperms(new int[n], new boolean[n], 0);
}
Lastly, where I have the print method, you can have the Array added to a list instead so that you can collect them all in a list, or you can just print it out. Your choice. Do with it as you please.
This question already has answers here:
Java, Simplified check if int array contains int
(15 answers)
Closed 6 years ago.
for example I want to do something like this:
package tst;
public class forInif {
public static void main(String[] args) {
int[] a = {1,2,3,4,5};
if (for(int i : a) {i == 5;}) {/**/}
}
}
I know normally I should make a boolean value of this situation by my own, but just in case, is there anyway to do something like that rather than make a boolean value somewhere else?
In Java 8+, you can use IntStream.anyMatch:
if (IntStream.of(a).anyMatch(i -> i == 5)) { ...
Not directly no: the condition check in a Java if needs to be a boolean type. But you could build a function:
public class forInif {
public static void main(String[] args) {
int[] a = {1,2,3,4,5};
if (foo(a)) {/**/}
}
}
where foo is a function returning a boolean that takes an int[] as a parameter.
There is no way to make a for loop return a boolean value. However, streams sound like a good way to do this in one or two lines:
int[] a = {1,2,3,4,5};
int fives = Arrays.stream(a).filter(e -> e == 5).count();
if (fives > 0) {
//replace this with whatever you want to do when a five is found
System.out.println("One or more fives exists in the array");
}
Can anyone help me to provide the code for finding duplicate values from the array. Here the condition is no loop statements. I tried with recursion method but it not working out. Pls anyone help me on this.
My attempt:
public static void main(String[] args) {
Integer a[] = { 1, 2, 7, 3, 4, 5, 2, 7 };
ArrayList<Integer> al = new ArrayList<Integer>(Arrays.asList(a));
if (duplicate(al) == true) {
System.out.println("Duplicate");
}
}
static int i = 1;
private static boolean duplicate(ArrayList<Integer> al) {
if (al.get(i) != null) {
if (al.get(i - 1) == al.get(i)) {
System.out.println("Duplicate are : " + al.get(i));
}
} else {
return true;
}
i++;
return duplicate(al);
}
Please refer below code to find duplicates in array without loop
public class ArrayDuplicate {
public static void main(String[] args) {
findDuplicateElementsInArray(new int[] { 20, 10, 20, 5, 10 });
}
private static void findDuplicateElementsInArray(int arr[]) {
Set<Integer> uniqueElements = new LinkedHashSet<Integer>();
Arrays.stream(arr).filter(i -> !uniqueElements.add(i)).forEach(System.out::println);
}
}
This isn't a good use case for recursion, which leads me to wonder what the point of the problem is. However, it's worth noting that LISP programmers (from what I've observed) traditionally used recursion for everything; early versions of the language may not have had any kind of loop construct. When programming in this way, one gets used to figuring out how to use recursion for an algorithm that would be a loop in any other language.
The main technique, I think, is to figure out what running local variables you'll need to keep, and pass them as parameters to a recursive helper function.
To solve this problem with a loop, I'd define a Set that is initially empty. As I go through the array, I'd: (1) see if the array element is already in the set, and return true if it is; (2) add the element to the set.
Here, the Set is the running variable that you need to keep. The array index is another "running variable". (In classic LISP, you'd just use a cdr function that means "the rest of the list", so you wouldn't need to maintain an index; I don't think that's easy to do with a Java ArrayList.) So you'll want a recursive method that has a Set and a "current index" as a parameter:
private boolean hasDuplicateHelper(ArrayList<Integer> a, int currentIndex, Set<Integer> alreadySeen) { ... }
The outer method will initialize the set to an empty set and call the helper with it this set, and with 0 as the current index. The recursive method will (1) look at the current element and see if it's in alreadySeen and return true if it is; (2) add the current element to the set; (3) call the method recursively with the new set as the alreadySeen parameter, and with the appropriate new value for the current index (I'll let you figure that one out).
I'll leave it to you to work out the rest of the details, such as how to stop.
EDIT: Now that it's clear from the comments that the desired result is to print the duplicate values instead of just "yes" or "no", something will have to change. But I think this can be done just by changing the method result to a Set<Integer> that contains a set of all the duplicates. If more information is needed, such as the indexes where the duplicates occur or the number of times each duplicate occurs, a different result structure may have to be used.
I completed the code to find the duplicate number from the array without using the loop statement. I implemented two recursions to finalize the code. Please check code on below
static int size;
public static void main(String[] args) {
Integer a[] = { 2, 10, 6, 1, 2, 4, 6, 10, 1 };
ArrayList<Integer> al = new ArrayList<Integer>(Arrays.asList(a));
size = a.length - 1;
findDuplOne(al, 0);
}
static int i = 0;
private static void findDuplOne(ArrayList<Integer> al, int i) {
if (i <= size) {
int valOne = al.get(i);
i++;
findDuplTwo(al, i, valOne);
findDuplOne(al, i);
}
}
private static void findDuplTwo(ArrayList<Integer> al, int i, int compareVal) {
if (i <= size) {
int valOne = al.get(i);
if (compareVal == valOne) {
System.out.println("Duplicate is " + compareVal);
}
i++;
findDuplTwo(al, i, compareVal);
}
}
Simply you can try it. If you pass your array object then it will return the count of duplicates.
public static int findDuplicatesCountOnArray(Integer[] arr) {
List<Integer> list = new ArrayList<Integer>();
if (arr != null) {
list.addAll(Arrays.asList(arr));
}
HashSet<Integer> set = new HashSet<Integer>(list);
return list.size() - set.size();
}
I want to return odd numbers of an array yet Eclipse doesn't seem to accept my return array[i]; code. I think it requires returning a whole array since I set an array as a parameter to my method.
As I said before, I need to pass an array and get a specific element of that array in return. Even if I make that array static, how do I return a single element?
Edit : Alright then, here it is:
public class newClass{
public static void main(String[] args)
{
int [] newArray= new int [4];
int [] array = {4,5,6,7};
newArray[0] = array[0]+array[1]+array[2]+array[3];
newArray[1] = array[0]*array[1]*array[2]*array[3];
newArray[2] = findOut(array);
}
public static int findOut (int [] array3)
{
int e1=0;
int e2=0;
for (int i=0; i<array3.length; i++)
{
if (array3[i]%2==0)
{
e1+=array3[i];
array3[i]=e1
return array3[i];
}
else
{
e2+=array3[i];
array3[i]=e2;
return array3[i];
}
}
}
}
I know there are probably more than a few mistakes here but I'm working on it and I'm not only returning odd numbers, I also add them together.
You code should look like this:
public int getElement(int[] arrayOfInts, int index) {
return arrayOfInts[index];
}
Main points here are method return type, it should match with array elements type and if you are working from main() - this method must be static also.
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
Make sure return type of you method is same what you want to return.
Eg:
`
public int get(int[] r)
{
return r[0];
}
`
Note : return type is int, not int[], so it is able to return int.
In general, prototype can be
public Type get(Type[] array, int index)
{
return array[index];
}
(Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:
array3[i]=e1
Also the findOut method doesn't return any value if the array length is 0. Adding a return 0; at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.
Ok, here is the code and then the discussion follows:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop,
the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same "experiment" with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the currentRow array. Move that inside the row loop and it should behave more like you expect.
Specifically, the assignment in setCurrentRow does not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the same int[] array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.
i don' t want to sound condescending, but always try to remember tip #26 from the excellent pragmatic programmer book
select isn't broken
it is very rare to find a java bug. keeping this in mind often helps me to look over my code again, turn it around, and shake out the loose bits until i finally discover where i was wrong. of course asking for help early enough is very encouraged, too :)