I have a method overload that goes as follows:
public class Odddetector {
public static void main(String[] args) {
int count = countOdd(new int [] {5, 7, 3, 9, 0});
System.out.println(count);
count = countOdd(new int [] {2, 6, 4, 8, 1});
System.out.println(count);
count = countOdd(5, 7, 10);
System.out.println(count);
count = countOdd(8, 2, 7);
System.out.println(count);
count = countOdd(new int[][] {{1, 2}, {3, 4, 5}});//extra point only
System.out.println(count);
count = countOdd(new int[][] {{6, 2}, {3, 4, 0}});//extra point only
System.out.println(count);
}
public static int countOdd(int[] a){
int count=0;
for (int i: a) count = (i %2 != 0)?++count:count;
return count;
// Do Something;
}
public static int countOdd(int[][] a){
// Do Something;
int count=0;
for (int b = 0; b< a.length; b++){
//System.out.println(java.util.Arrays.toString(a[b])); not a necessary line.
count += countOdd(a[b]);
}
return count;
}
// more method overloading
My question is there a way to condense the solution to have one method that takes into account N-Dimensional Arrays. The code runs fine like this however, I would like to know what Java techniques can help account for the increase in dimensions. I would like to add some details and that is that the first method is the base method, and all the other methods call that first int[] a. The new section I added is the full code I am currently in developing this code which my professor gave as a challenge. I currently have the Data Structures by Lang, and I can accept hints. I prefer hints actually because I would like to learn to code this.
When the parameter is amulti dimensional array, you can recursively call the function that digs down until you end up with a 1d array of numbers. The logic is:
if a is a multi-dimensional array
for each array in a
call recursively
else
count odd numbers in a
I have 2 functions. One that takes a variable number of args, and a recursive one. The first just calls the second with the var args as an array. The varargs function needs a bit of work if you want to allow mixed parameters (eg: countOdd(new int [] {1,2,3}, 4, 5);)
// The var args version. You call this. It then calls the recursive
// version.
public static <T> int countOdd(T... arguments)
{
return countOddRec(arguments);
}
// Recursive version
private static <T> int countOddRec(T[] a)
{
if (a == null || a.length == 0) return 0;
int count=0;
// Is it an array of Numbers?
if (a[0] instanceof Number) {
for (T i: a) {
// Simplified the counting code a bit. Any # mod 2 is either 0 or 1
count += ((Number)i).intValue() % 2;
}
}
// Is it an multi-dimensional? Call recursively for each sub-array.
else {
for (T sub : a) {
count += countOddRec((T[])sub);
}
}
return count;
}
As mentioned in the comments, this will not work for primitive data types (ex: int, etc). Instead, use non-primitive types (ex: Integer, etc).
Well, I guess there are some very interesting problems around, all coupled together. Namely
How to generify array processing and method declaration for
arbitrary depth (this is your initial question)?
How to deep traverse array with unknown depth?
How to inject some useful payload
into array traversal (in your case - count odd numbers)
independently of traversal itself?
Is it possible to generify approach for primitive and object arrays, and how?
I have a good suggestion for points 3: instead of hardcoding payload in the method itself we can produce IntStream (or generic Stream for Object version) which can be processed separately.
On points 1 and 4 my guess it's probably not possible or at least not elegant. java.lang.reflect.Array doesn't show any wonder in this and my assumption is - if JDK couldn't do this, I cannot neither. So, the best option is probably to allow general signature with Object accompanied with couple of frequently used overloads, up to depth 3. Of course, this implies danger of ClassCastExceptions at runtime.
So, final result with implementation of point 2 may look like this
public class FlattenArray {
public static IntStream flatten(int n) {
return IntStream.of(n);
}
public static IntStream flatten(int[] array) {
return IntStream.of(array);
}
public static IntStream flatten(int[][] array) {
return flatten((Object) array);
}
public static IntStream flatten(Object array) {
Class<?> aClass = array.getClass();
if (!aClass.isArray())
return IntStream.of(((Number) array).intValue());
else {
Class<?> componentType = aClass.getComponentType();
if (componentType.isPrimitive())
return IntStream.of((int[]) array);
else
return Arrays.stream((Object[]) array).flatMapToInt(FlattenArray::flatten);
}
}
}
And use this like
long count = FlattenArray.flatten(2, 3, 5, 7).filter(i -> i & 1 != 0).count();
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.
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 :)
I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method.
I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element.
It works, but it just doesn't feel right!
I have also noticed that I seem to use the static modifier much more than my classmates in general...
Can anybody please provide any general tips as well as feedback as to how I can improve my code?
public class RecursiveTry{
static int[] n = new int[] {1,2,4,3,3,32,100};
static int current = 0;
static int maxValue = 0;
static int SIZE = n.length;
public static void main(String[] args){
System.out.println(Max(n, SIZE));
}
public static int Max(int[] n, int SIZE) {
if(current <= SIZE - 1){
if (maxValue <= n[current]) {
maxValue = n[current];
current++;
Max(n, SIZE);
}
else {
current++;
Max(n, SIZE);
}
}
return maxValue;
}
}
Your use of static variables for holding state outside the function will be a source of difficulty.
An example of a recursive implementation of a max() function in pseudocode might be:
function Max(data, size) {
assert(size > 0)
if (size == 1) {
return data[0]
}
maxtail = Max(data[1..size], size-1)
if (data[0] > maxtail) {
return data[0]
} else {
return maxtail
}
}
The key here is the recursive call to Max(), where you pass everything except the first element, and one less than the size. The general idea is this function says "the maximum value in this data is either the first element, or the maximum of the values in the rest of the array, whichever is larger".
This implementation requires no static data outside the function definition.
One of the hallmarks of recursive implementations is a so-called "termination condition" which prevents the recursion from going on forever (or, until you get a stack overflow). In the above case, the test for size == 1 is the termination condition.
Making your function dependent on static variables is not a good idea. Here is possible implementation of recursive Max function:
int Max(int[] array, int currentPos, int maxValue) {
// Ouch!
if (currentPos < 0) {
raise some error
}
// We reached the end of the array, return latest maxValue
if (currentPos >= array.length) {
return maxValue;
}
// Is current value greater then latest maxValue ?
int currentValue = array[currentPos];
if (currentValue > maxValue) {
// currentValue is a new maxValue
return Max(array, currentPos + 1, currentValue);
} else {
// maxValue is still a max value
return Max(array, currentPos + 1, maxValue);
}
}
...
int[] array = new int[] {...};
int currentPos = 0;
int maxValue = array[currentPos] or minimum int value;
maxValue = Max(array, currentPos, maxValue);
A "max" function is the wrong type of thing to write a recursive function for -- and the fact you're using static values for "current" and "maxValue" makes your function not really a recursive function.
Why not do something a little more amenable to a recursive algorithm, like factorial?
"not-homework"?
Anyway. First things first. The
static int[] n = new int[] {1,2,4,3,3,32,100};
static int SIZE = n.length;
have nothing to do with the parameters of Max() with which they share their names. Move these over to main and lose the "static" specifiers. They are used only once, when calling the first instance of Max() from inside main(). Their scope shouldn't extend beyond main().
There is no reason for all invocations of Max() to share a single "current" index. "current" should be local to Max(). But then how would successive recurrences of Max() know what value of "current" to use? (Hint: Max() is already passing other Max()'s lower down the line some data. Add "current" to this data.)
The same thing goes for maxValue, though the situation here is a bit more complex. Not only do you need to pass a current "maxValue" down the line, but when the recursion finishes, you have to pass it back up all the way to the first Max() function, which will return it to main(). You may need to look at some other examples of recursion and spend some time with this one.
Finally, Max() itself is static. Once you've eliminated the need to refer to external data (the static variables) however; it doesn't really matter. It just means that you can call Max() without having to instantiate an object.
As others have observed, there is no need for recursion to implement a Max function, but it can be instructive to use a familiar algorithm to experiment with a new concept. So, here is the simplified code, with an explanation below:
public class RecursiveTry
{
public static void main(String[] args)
{
System.out.println(Max(new int[] {1,2,4,3,3,32,100}, 0, 0));
}
public static int Max(int[] n, int current, int maxValue)
{
if(current < n.Length)
{
if (maxValue <= n[current] || current == 0))
{
return Max(n, current+1, n[current]);
}
return Max(n, current+1, maxValue);
}
return maxValue;
}
}
all of the static state is gone as unnecessary; instead everything is passed on the stack. the internal logic of the Max function is streamlined, and we recurse in two different ways just for fun
Here's a Java version for you.
public class Recursion {
public static void main(String[] args) {
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("Max: " + max(0, data));
}
public static int max(int i, int[] arr) {
if(i == arr.length-1) {
return arr[i];
}
int memo = max(i+1, arr);
if(arr[i] > memo) {
return arr[i];
}
return memo;
}
}
The recurrence relation is that the maximum element of an array is either the first element, or the maximum of the rest of the array. The stop condition is reached when you reach the end of the array. Note the use of memoization to reduce the recursive calls (roughly) in half.
You are essentially writing an iterative version but using tail recursion for the looping. Also, by making so many variables static, you are essentially using global variables instead of objects. Here is an attempt at something closer to a typical recursive implementation. Of course, in real life if you were using a language like Java that doesn't optimize tail calls, you would implement a "Max" function using a loop.
public class RecursiveTry{
static int[] n;
public static void main(String[] args){
RecursiveTry t = new RecursiveTry(new int[] {1,2,4,3,3,32,100});
System.out.println(t.Max());
}
RecursiveTry(int[] arg) {
n = arg;
}
public int Max() {
return MaxHelper(0);
}
private int MaxHelper(int index) {
if(index == n.length-1) {
return n[index];
} else {
int maxrest = MaxHelper(index+1);
int current = n[index];
if(current > maxrest)
return current;
else
return maxrest;
}
}
}
In Scheme this can be written very concisely:
(define (max l)
(if (= (length l) 1)
(first l)
(local ([define maxRest (max (rest l))])
(if (> (first l) maxRest)
(first l)
maxRest))))
Granted, this uses linked lists and not arrays, which is why I didn't pass it a size element, but I feel this distills the problem to its essence. This is the pseudocode definition:
define max of a list as:
if the list has one element, return that element
otherwise, the max of the list will be the max between the first element and the max of the rest of the list
A nicer way of getting the max value of an array recursively would be to implement quicksort (which is a nice, recursive sorting algorithm), and then just return the first value.
Here is some Java code for quicksort.
Smallest codesize I could get:
public class RecursiveTry {
public static void main(String[] args) {
int[] x = new int[] {1,2,4,3,3,32,100};
System.out.println(Max(x, 0));
}
public static int Max(int[] arr, int currPos) {
if (arr.length == 0) return -1;
if (currPos == arr.length) return arr[0];
int len = Max (arr, currPos + 1);
if (len < arr[currPos]) return arr[currPos];
return len;
}
}
A few things:
1/ If the array is zero-size, it returns a max of -1 (you could have another marker value, say, -MAX_INT, or throw an exception). I've made the assumption for code clarity here to assume all values are zero or more. Otherwise I would have peppered the code with all sorts of unnecessary stuff (in regards to answering the question).
2/ Most recursions are 'cleaner' in my opinion if the terminating case is no-data rather than last-data, hence I return a value guaranteed to be less than or equal to the max when we've finished the array. Others may differ in their opinion but it wouldn't be the first or last time that they've been wrong :-).
3/ The recursive call just gets the max of the rest of the list and compares it to the current element, returning the maximum of the two.
4/ The 'ideal' solution would have been to pass a modified array on each recursive call so that you're only comparing the first element with the rest of the list, removing the need for currPos. But that would have been inefficient and would have bought down the wrath of SO.
5/ This may not necessarily be the best solution. It may be that by gray matter has been compromised from too much use of LISP with its CAR, CDR and those interminable parentheses.
First, let's take care of the static scope issue ... Your class is defining an object, but never actually instantiating one. Since main is statically scoped, the first thing to do is get an object, then execute it's methods like this:
public class RecursiveTry{
private int[] n = {1,2,4,3,3,32,100};
public static void main(String[] args){
RecursiveTry maxObject = new RecursiveTry();
System.out.println(maxObject.Max(maxObject.n, 0));
}
public int Max(int[] n, int start) {
if(start == n.length - 1) {
return n[start];
} else {
int maxRest = Max(n, start + 1);
if(n[start] > maxRest) {
return n[start];
}
return maxRest;
}
}
}
So now we have a RecursiveTry object named maxObject that does not require the static scope. I'm not sure that finding a maximum is effective using recursion as the number of iterations in the traditional looping method is roughly equivalent, but the amount of stack used is larger using recursion. But for this example, I'd pare it down a lot.
One of the advantages of recursion is that your state doesn't generally need to be persisted during the repeated tests like it does in iteration. Here, I've conceded to the use of a variable to hold the starting point, because it's less CPU intensive that passing a new int[] that contains all the items except for the first one.