mark61196
mark61196

Reputation: 35

compare an element of a list with the following in a recursively way

Hi, Update: Thanks for all your suggestion

assuming that, this exercise it's like a rebus, I have a list of numbers made with the concept of Cons and Nil,

List l = new Cons(**3**, new Cons(**2**,new Cons(**1**, new
Cons(**4**, new Cons(**1**, new Nil())))));

and I want to count how many of them are immediately followed by a lower number, recursively.

For example

[5,0,5,3].count() == 2, [5,5,0].count() == 1

The count() method is made by me (it cannot have any parameters), the rest is default, and I can't make and other method or use already defined one's like add(),size()... The "NEXT" must have the next value after the current elem but I can't get a solution.

Any solutions are welcome.

abstract class List {

    public abstract boolean empty();

    public abstract int first();

    public abstract int count();

}

class Cons extends List {

    private int elem;

    private List next;

  public Cons(int elem, List next) {

   this.elem = elem;

   this.next = next;

}

public boolean empty(){
 return false; 
}

public int first(){
 return elem;
}

@Override
public int count() {
  if(elem>NEXT) {
      return 1 + next.count();  
  }else {
      return next.count();      
 }

}

```![enter image description here](https://i.sstatic.net/kWo0v.jpg)

Upvotes: 1

Views: 256

Answers (2)

Matthew
Matthew

Reputation: 1943

The following code will create a recursive list with N elements with N value being defined by the size of the amount of elements found in the int array called elements in RecursiveList class. Call the startRecursion() method to create a recursive list with the defined elements and call count() to get the amount of elements in the array that are immediately followed by a lower number.

Main Class

This your application entry point:

public static void main(String[] args) {

    int count = RecursiveList.startRecursion().count();
    System.out.printf("List has %d recursive elements", count);
}

RecursiveList Class

abstract class RecursiveList {

    protected static int index = -1;
    protected static int[] elements = new int[]{ 5,2,1,4,3,2,6 };

    public static RecursiveList startRecursion() {
        return new Cons();
    }

    public abstract boolean empty();

    public abstract int count();

    public abstract Integer getElement();

    public static int incIndex() {
        return index += 1;
    }
}

Cons Class

public class Cons extends RecursiveList {

    private static int result;

    private final Integer elem;
    private final RecursiveList prev;
    private final RecursiveList next;

    private Cons(Cons parent) {

        prev = parent;
        elem = incIndex() < elements.length ? elements[index] : null;
        System.out.printf("Creating new Cons with element %d(%d)%n", elem, index);
        next = elem != null ? new Cons(this) : null;
    }

    Cons() {
        this(null);
    }

    public boolean empty() {
        return false;
    }

    @Override
    public /*@Nullable*/ Integer getElement() {
        return elem;
    }

    @Override
    public int count() {

        if (elem != null)
        {
            if (prev != null && elem < prev.getElement())
                result += 1;

            if (next != null) {
                return next.count();
            }
        }
        return result;
    }
}

EDIT

Alright here is the answer you were actually looking for. This completely conforms to the limitations imposed on this exercise that you provided. The solution uses pure Java, neither the class nor any of it's method or field declarations were modified in any way and no such new elements were added. I've only added the implementation where the exercise said you should.

Main Class

public static void main(String[] args) {

    List l = new Cons(3, new Cons(2,new Cons(1, new
            Cons(4, new Cons(1, new Nil())))));

    assert l.count() == 3;

    l = new Cons(5, new Nil());
    assert l.count() == 0;

    l = new Cons(5, new Cons(5, new Cons(0, new Nil())));
    assert l.count() == 1;

    l = new Cons(5, new Cons(0, new Cons(5, new Cons(3, new Nil()))));
    assert l.count() == 2;

    System.out.println("All tests completed successfully!");
}

Cons Class

import java.util.NoSuchElementException;

public class Cons extends List {
    private int elem;
    private List next;

    public Cons(int elem, List next) {
        this.elem = elem;
        this.next = next;
    }

    public boolean empty()
    { return false; }

    public int first()
    { return elem; }

    public int count()
    {
        try {
            if (first() > next.first()) {
                return 1 + next.count();
            }
            else return next.count();
        }
        catch (NoSuchElementException e) {
            return 0;
        }
    }
}

Nil Class

import java.util.NoSuchElementException;

public class Nil extends List {
    public boolean empty()
    { return true; }

    public int first()
    { throw new NoSuchElementException(); }

    public int count()
    {
        throw new IllegalAccessError();
    }
}

Upvotes: 2

kkica
kkica

Reputation: 4104

public int NEXT(){
 if(next!=null)
   return next.first()
 else 
   throw new Exception("No next element")
}

Upvotes: 0

Related Questions