NOTE: A cumulative histogram is a histogram in which each value is added to the sum of the values that have gone before, for example if there are 3 apples, 2 bananas and 6 oranges, then then numbers in the normal histogram will [3,2,6] but in a cumulative histogram they will be [3,5,11].
Question: Create a subclass of Histogram called CumulativeHistogram. I only need to override the toString() method to solve the problem.
class Histogram
{
public char symbol = '*';
protected String[] categories;
protected int[] frequencies;
public Histogram(int numCategories)
{
categories = new String [ numCategories ];
frequencies = new int [ numCategories ];
for (int index = 0; index < numCategories; index++) {
categories[index] = "unlabeled";
frequencies[index] = 0;
}
}
public void setCategory(int index, String name, int frequency)
{
categories[ index ] = name;
frequencies[ index ] = frequency;
}
public String toString()
{
String result = "";
for (int index = 0; index<categories.length; index++){
result+=categories[index] +": ";
result+=repeatSymbol(frequencies[index]);
result+="\n";
}
return result;
}
protected String repeatSymbol(int numTimes)
{
String result = "";
for (int index = 0; index <numTimes; index++)
result += symbol;
return result;
}
}
Here is a template for the class:
class CumulativeHistogram extends Histogram {
public CumulativeHistogram(int numCategories) {
super(numCategories);
}
public String toString() {
//*****fill in this method
}
}
Some test code
Histogram hist = new Histogram(3);
hist.setCategory(0, " Apples", 4);
hist.setCategory(1, "Bananas", 2);
hist.setCategory(2, "Oranges", 5);
println( hist );
CumulativeHistogram hist2 = new CumulativeHistogram(3);
hist2.setCategory(0, " Apples", 4);
hist2.setCategory(1, "Bananas", 2);
hist2.setCategory(2, "Oranges", 5);
println( hist2 );
And its output
Apples: ****
Bananas: **
Oranges: *****
Apples: ****
Bananas: ******
Oranges: ***********
Declare another counter outside the loop, incrementing with the loop, and use that with the index as such:
result+=repeatSymbol(frequencies[index]+counter);
counter+=frequencies[index];
Related
I am trying to call joinpoint.proceed with batches of arguments.
Is it possible to call.
I am not able to find any examples where we are partitioning the arguments or making new arguments then calling joinpoint.proceed on them.
Is this what you are looking for ?
#Service
public class AdditionService {
public Integer sum(List<Integer> list) {
Integer sum = 0;
for (Integer i : list) {
sum += i;
}
System.out.println("Sum :" + sum);
return sum;
}
}
and an aspect to find sum in batches
#Aspect
#Component
public class ExampleAspect {
#Around("execution(* com.package..*.sum*(..)) && within(com.package..*) && args(list)")
public Integer around(ProceedingJoinPoint pjp, List<Integer> list) throws Throwable {
Object[] args = pjp.getArgs(); // get the arguments array
Integer sum = 0;
for (int i = 0; i < 10; i += 5) {
args[0] = (list.subList(i, i + 5)); // modify the arguments array
System.out.println(args[0]);
sum += (Integer) pjp.proceed(args);
}
return sum;
}
}
the service bean accessed like following
Integer[] a= {1,2,3,4,5,6,7,8,9,10};
Integer sum = 0;
sum = service.sum(Arrays.asList(a));
System.out.println("Total : "+sum);
would print the following to console
[1, 2, 3, 4, 5]
Sum :15
[6, 7, 8, 9, 10]
Sum :40
Total : 55
Hope this helps
I cannot get the loop to work in the buildDimArray method to store the number combinations "11+11", "11+12", "11+21", "11+22", "12+11", "12+12", "12+21", "12+22", "21+11", "21+12", "21+21", "21+22", "22+11", "22+12", "22+21", and "22+22" into the 2d arraylist with each expression going into one column of the index dimBase-1 row. The loop may work for other people, but for some reason mine isn't functioning correctly. The JVM sees the if dimBase==1 condition, but refuses to check the other conditions. The "WTF" not being printed as a result from the buildDimArray method. If dimBase=1, it prints successfully, but doesn't for the other integers. The dimBase==3 condition needs a loop eventually. The "WTF" is for illustrative purposes. I could get away with a 1d arraylist, but in the future I will likely need the 2d arraylist once the program is completed.
package jordanNumberApp;
import java.util.Scanner;
import java.util.ArrayList;
/*
* Dev Wills
* Purpose: This code contains some methods that aren't developed. This program is supposed to
* store all possible number combinations from numbers 1-dimBase for the math expression
* "##+##" into a 2d arraylist at index row dimBase-1 and the columns storing the
* individual combinations. After storing the values in the arraylist, the print method
* pours the contents in order from the arraylist as string values.
*/
public class JordanNumberSystem {
// a-d are digits, assembled as a math expression, stored in outcomeOutput, outcomeAnswer
public static int dimBase, outcomeAnswer, a, b, c, d;
public static String inputOutcome, outcomeOutput;
public static final int NUM_OF_DIMENSIONS = 9; //Eventually # combinations go up to 9
public static ArrayList<ArrayList<String>> dimBaseArray;
public static Scanner keyboard;
/*
* Constructor for JordanNumber System
* accepts no parameters
*/
public JordanNumberSystem() // Defunct constructor
{
// Declare and Initialize public variables
this.dimBase = dimBase;
this.outcomeOutput = outcomeOutput;
this.outcomeAnswer = outcomeAnswer;
}
// Set all values of variable values
public static void setAllValues()
{
// Initialize
dimBase = 1;
outcomeAnswer = 22; // variables not used for now
outcomeOutput = "1"; // variables not used for now
//a = 1;
//b = 1;
//c = 1;
//d = 1;
dimBaseArray = new ArrayList<ArrayList<String>>();
keyboard = new Scanner(System.in);
}
public static void buildDimArray(int dim)
{
dimBase = dim;
try
{
//create first row
dimBaseArray.add(dimBase-1, new ArrayList<String>());
if( dimBase == 1)
{
a = b = c = d = dimBase ;
dimBaseArray.get(0).add(a+""+b+"+"+c+""+d);
System.out.println("WTF"); // SHOWS
}
else if (dimBase == 2)
{ // dim = 2
a = b = c = d = 1 ;
System.out.println("WTF"); // doesn't show
// dimBaseArray.get(dimBase-1).add(a+""+b+"+"+c+""+d);
for( int i = 1 ; i <= dim ; i++)
a=i;
for( int j = 1 ; j <= dim ; j++)
b=j;
for( int k = 1 ; k <= dim ; k++)
c=k;
for( int l = 1 ; l <= dim ; l++)
{
d=l;
dimBaseArray.get(dim-1).add(a+""+b+"+"+c+""+d);
}
}
else if (dimBase == 3)
{
a = b = c = d = dimBase;
dimBaseArray.get(2).add(a+""+b+"+"+c+""+d);
System.out.println("WTF");
}
}catch (IndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
public static void printArray(int num) // Prints the contents of the array
{ // Fixing the printing method
try
{
int i = num-1;
for( String string : dimBaseArray.get(i))
{
System.out.println(string);
System.out.println("");
}
} catch (IndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws java.lang.IndexOutOfBoundsException
{
setAllValues(); // sets the initial a,b,c,d values and dimBase, initializes 2d arraylist
// Get the Dimension Base number
System.out.println("Enter Dimension Base Number. Input an integer: ");
int dimBaseInput = keyboard.nextInt(); // Receives integer
dimBase = dimBaseInput;
if( dimBase != 1 && dimBase != 2 && dimBase != 3)
{// Error checking
System.out.println("invalid Dimension Base Number should be 1 or 2 ");
System.exit(1);
}
// Build the arraylist, print, clear, exit
buildDimArray(dimBase);
printArray(dimBase);
dimBaseArray.clear();
System.exit(1);
}
}// End of class
I have a list like shown below. Assume it has 16 Container objects in it. Each Container object is a simple bean, with fields like age, weight, height, etc. How can I create a sub-list that contains common 'Container' objects if a 'Container' object is considered equal if the weight and height are equal?
List<Container> containers = new ArrayList<Container>();
If by "common" containers you mean duplicating ones, then this code might help you:
import java.util.ArrayList;
import java.util.List;
public class CommonContainers {
public static void main(String[] args) {
List<Container> containers = new ArrayList<Container>(16);
for(int i=0; i<13; i++) {
containers.add(new Container(i, i));
}
//add a few duplicating ones
containers.add(new Container(1,1));
containers.add(new Container(5,5));
containers.add(new Container(6,6));
List<Container> sublist = new ArrayList<Container>();
for (Container c1 : containers) {
for (Container c2 : containers) {
if(c1 != c2 && c1.equals(c2)) {
sublist.add(c1);
}
}
}
for (Container c : sublist) {
System.out.println(c);
}
}
private static class Container {
private int weight;
private int height;
#Override
public String toString() {
return String.format("Container[w=%d,h=%d]", weight, height);
}
public Container(int weight, int height) {
this.weight = weight;
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + height;
result = prime * result + weight;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Container other = (Container) obj;
if (height != other.height)
return false;
if (weight != other.weight)
return false;
return true;
}
}
}
If you mean something else or need clarification, please let me know.
Thanks John Smith for giving direction on this question. I used the iterator instead and was able to make a nice solution to what I was looking for. below is the solution. Note that .equals is overriden for the Containers comparison. The technique I used will take the master list and create a sub-list while removing elements from the parent list at the same time. The solution can be called recursivly until you convert the master list into a subset of lists.
public List<Container> extractCommonSubList(
List<Container> masterContainerList) {
List<Container> subList = new ArrayList<Container>();
ListIterator<Container> iterator = masterContainerList.listIterator();
// get first item from master list and remove from master list
Container firstContainer = iterator.next();
iterator.remove();
// Add first container to sublist
subList.add(firstContainer);
while (iterator.hasNext()) {
Container container = iterator.next();
// Search for matches
if (firstContainer.equals(container)) {
// containers are a match, continue searching for matches
subList.add(container);
iterator.remove();
continue;
} else {
break;
}
}
// return common list
return subList;
}
import java.util.*;
public class MyTwoWayLinkedList<E> extends java.util.AbstractSequentialList<E> {
private Node<E> head, tail;
private int size = 0;
private List<E> list;
/** Create a default list */
public MyTwoWayLinkedList() {
list = new LinkedList<E>();
}
public MyTwoWayLinkedList(E[] objects) {
list = new LinkedList<E>();
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
/** Return the head element in the list */
public E getFirst() {
if (size == 0) {
return null;
}
else {
return head.element;
}
}
/** Return the last element in the list */
public E getLast() {
if (size == 0) {
return null;
}
else {
return tail.element;
}
}
/** Add an element to the beginning of the list */
public void addFirst(E e) {
Node<E> newNode = new Node<E>(e); // Create a new node
newNode.next = head; // link the new node with the head
head.previous = newNode; //link the old node with new head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node<E> newNode = new Node<E>(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode;// Link the new with the last node
newNode.previous = tail;
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
#Override /** Add a new element at the specified index
* in this list. The index of the head element is 0 */
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node<E> current = tail;
for (int i = size - 1; i > index; i--) {
current = current.previous;
}
Node<E> temp = current.next;
current.next = new Node<E>(e);
(current.next).previous = current;
(current.next).next = temp;
size++;
}
}
/** Remove the head node and
* return the object that is contained in the removed node. */
public E removeFirst() {
if (size == 0) {
return null;
}
else {
Node<E> temp = head;
head = head.next;
head.previous = null;
size--;
if (head == null) {
tail = null;
}
return temp.element;
}
}
/** Remove the last node and
* return the object that is contained in the removed node. */
public E removeLast() {
if (size == 0) {
return null;
}
else if (size == 1) {
Node<E> temp = head;
head = tail = null;
size = 0;
return temp.element;
}
else {
Node<E> temp = tail;
tail = tail.previous;
tail.next = null;
size--;
return temp.element;
}
}
#Override /** Remove the element at the specified position in this
* list. Return the element that was removed from the list. */
public E remove(int index) {
if (index < 0 || index >= size) {
return null;
}
else if (index == 0) {
return removeFirst();
}
else if (index == size - 1) {
return removeLast();
}
else {
Node<E> previous = tail;
for (int i = size - 1; i > index; i--) {
previous = previous.previous;
}
Node<E> current = previous.next;
(current.next).previous = previous;
previous.next = current.next;
size--;
return current.element;
}
}
#Override /** Override toString() to return elements in the list */
public String toString() {
StringBuilder result = new StringBuilder("[");
Node<E> current = tail;
for (int i = size - 1; i > 0; i--) {
result.append(current.element);
current = current.previous;
if (current != null) {
result.append(" ,"); // Separate two elements with a comma
}
else {
result.append("["); // Insert the closing ] in the string
}
}
return result.toString();
}
#Override /** Clear the list */
public void clear() {
size = 0;
head = tail = null;
}
#Override /** Override iterator() defined in Iterable */
public ListIterator<E> listIterator() {
Node<E> current = head; // Current index
return list.listIterator();
}
#Override /** Override iterator() defined in Iterable */
public ListIterator<E> listIterator(int index) {
Node<E> current = head; // Current index
for (int i = 0; i < index; i++) { // sets current int to the parameter
current = current.next;
}
return list.listIterator();
}
#Override
public int size()
{
return size;
}
public class Node<E> {
E element;
Node<E> next;
Node<E> previous;
public Node(E element) {
this.element = element;
}
}
}
This is my original class, I will include my test case below but first let me explain my problem. I am trying to create a Doubly linked list and iterate backwards through it. However I am getting a Null Pointer Exception by just adding elements to the list. I have looked over the section of code for my addFirst method for about 2 hours now and don't see any logic errors(doesn't mean there arent any), please help!
Here is my test case as promised.
public class TestMyLinkedList {
/** Main method */
public static void main(String[] args) {
// Create a list for strings
MyTwoWayLinkedList<String> list = new MyTwoWayLinkedList<String>();
// Add elements to the list
list.add("America"); // Add it to the list
System.out.println("(1) " + list);
list.add(0, "Canada"); // Add it to the beginning of the list
System.out.println("(2) " + list);
list.add("Russia"); // Add it to the end of the list
System.out.println("(3) " + list);
list.addLast("France"); // Add it to the end of the list
System.out.println("(4) " + list);
list.add(2, "Germany"); // Add it to the list at index 2
System.out.println("(5) " + list);
list.add(5, "Norway"); // Add it to the list at index 5
System.out.println("(6) " + list);
list.add(0, "Poland"); // Same as list.addFirst("Poland")
System.out.println("(7) " + list);
// Remove elements from the list
list.remove(0); // Same as list.remove("Australia") in this case
System.out.println("(8) " + list);
list.remove(2); // Remove the element at index 2
System.out.println("(9) " + list);
list.remove(list.size() - 1); // Remove the last element
System.out.print("(10) " + list + "\n(11) ");
for (String s: list)
System.out.print(s.toUpperCase() + " ");
list.clear();
System.out.println("\nAfter clearing the list, the list size is "
+ list.size());
}
}
I'm not completely sure why you are using a LinkedList within your own implementation of a Double Linked List. In regards to your question about your addFirst method however, I have the following comments and an example of how I would approach this solution.
Head is null when you call the addFirst method.
Head has not been initialized as a new Node.
Therefore newNode.next = head; is actually newNode.next = null; There is your null pointer exception, I would imagine!
public void addFirst (E e)
{
Node<E> newNode = new Node<E>(e); //create new node
if (head != null){ //if head exists
newNode.next = head; //the new node's next link becomes the old head
}
head = newNode; //the new head is the new node
if (tail == null){ //if the tail is non existent ie head the only object in list
tail = head; //the head and the tail are the same
head.next = tail; //the 'next' value of head will be tail
}
head.prev = tail; //the previous node to head will always be tail
size++;
}
}
i would like to assign my array vals to properties of my object.
like:
For i = 1 To 32
myClass.Prop_i = val[i]
Next
VB.NET isn't a dynamic language: you can't do such things.
Since VB.NET doesn't have a "dynamic" keyword like C#, your option is reflection:
myClass.GetType().GetProperty("Prop_" + i.ToString()).SetValue(myClass, val[i], null);
But if you're more explicit with your problem maybe there's a more elegant solution than reflection ;)
Your property needs to define Set. This will allow you to modify the property.
If you are willing to write some code in C# and use it in VB.NET, and need to store primitive types like int, float or byte, and all your properties are of the same type. Then you can create a union structure with an array covering the fields.
Then you can use code like this:
Sub Main() ' vb.net
Dim bag As New PropertyBag()
bag.AllProperties = New Single() {1, 2, 3, 4, 5, 6, 7, 8}
Dim three As Single = bag.Prop_3 'returns 3
Dim five As Single = bag(4) 'returns 5 (0-based index)
End Sub
When declared like
[StructLayout(LayoutKind.Explicit, Size=Size)]
public unsafe struct PropertyBag
{
const int Count = 8; //8 fields
const int Size = 8 * 4; //4 bytes per field
[FieldOffset(0)]
fixed float list[Count];
[FieldOffset(0)] float x1;
[FieldOffset(4)] float x2;
[FieldOffset(8)] float x3;
[FieldOffset(12)] float x4;
[FieldOffset(16)] float x5;
[FieldOffset(20)] float x6;
[FieldOffset(24)] float x7;
[FieldOffset(28)] float x8;
public float Prop_1 { get { return x1; } set { x1 = value; } }
public float Prop_2 { get { return x2; } set { x2 = value; } }
public float Prop_3 { get { return x3; } set { x3 = value; } }
public float Prop_4 { get { return x4; } set { x4 = value; } }
public float Prop_5 { get { return x5; } set { x5 = value; } }
public float Prop_6 { get { return x6; } set { x6 = value; } }
public float Prop_7 { get { return x7; } set { x7 = value; } }
public float Prop_8 { get { return x8; } set { x8 = value; } }
public float this[int index]
{
get
{
fixed (float* ptr = list)
{
return ptr[index];
}
}
set
{
fixed (float* ptr = list)
{
ptr[index] = value;
}
}
}
public float[] AllProperties
{
get
{
float[] res = new float[Count];
fixed (float* ptr = list)
{
for (int i = 0; i < Count; i++)
{
res[i] = ptr[i];
}
}
return res;
}
set
{
fixed (float* ptr = list)
{
for (int i = 0; i < Count; i++)
{
ptr[i] = value[i];
}
}
}
}
}
Note that reflection should work in your case (like others have answered), but this is just a different approach to the problem (and a very fast one too). The main limitation is what types can be made into pointers in C# (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool)