Related
I've been working on a project where I needed to implement convolution and correlation methods using two formulas, which I did. Then I need to define the following method for printing f, correlation, and convolution side-by-side (which is the part I need help figuring out):
Convolution Formula:
(f * g)[n] = ∑ f[n + (M - 1) - m] * g[m]
where f is an array of size N, g is an array of size M, and f*g is the array of size N - M + 1 that stores the result of the convolution.
Correlation Formula:
(f ** g)[n] = ∑ f[n + m] * g[m]
where f is an array of size N, g is an array of size M, and f**g is the array of size N - M + 1 that stores the result of the correlation.
Define the following method for printing f, f*g, f**g side-by-side:
private static void print(double[] f, double[] convolution, double[] correlation)
This is what I have. Everything in main is driver code to test the program. I need help with the print method:
public static void main(String[] args) {
double[] f = new double[18];
for (int i = 0; i < f.length; i++) {
f[i] = i;
}
double[] g1 = {0.25, 0.25, 0.5},
g2 = {0.1, 0.2, 0.3, 0.4};
print(f, convolution(f, g1), correlation(f, g1));
print(f, convolution(f, g2), correlation(f, g2));
for (int i = 0; i < f.length; i++) {
f[i] = Math.sin(i);
}
print(f, convolution (f, g1), correlation(f, g1));
print(f, convolution (f, g2), correlation(f, g2));
}
**private static void print(double[] f, double[] convolution, double[] correlation) {
System.out.println("i\tf(i)\tconvolution[i]\tcorrelation[i]");
for (int i = 0; i < convolution.length; i++) {
System.out.println(i + "\t" + (f[i]) + "\t" + (convolution[i]) + "\t"
+ correlation[i] + "\t");
}
}**
private static double[] convolution (double[] f, double[] g) {
int n = f.length - g.length + 1; //N - M + 1
double[] result2 = new double[n]; //create new array and define bounds
for (int i = 0; i < n; ++i) { //outer loop executes n times
for (int j = 0; j < g.length; ++j) { //inner loop executes up to the length of g
result2[i] += f[i + (g.length - 1) - j] * g[j]; //convolution calculation
}
}
return result2;
}
private static double[] correlation (double[] f, double[] g) {
int n = f.length - g.length + 1; // N - M + 1
double[] result = new double[n]; // create new array and define bounds
for (int i = 0; i < n; ++i) { // outer loop executes n times
for (int j = 0; j < g.length; ++j) { //inner loop executes up to the length of g
result[i] += f[i + j] * g[j]; // correlation calculation
}
}
return result;
}
}
This is an example of what the output should look like. This is the last printing as per the calls in the main method. I didn't want to include too much info:
This is what I'm getting. I'm not really concerned about the formatting.
I can't seem to get i to print 17 times and I'm unsure as to how to get it to print "----" for the empty values. Do I use an if statement? If I change the for loop in the print method to this:
for (int i = 0; i < f.length; i++) {
System.out.println(i + "\t" + (f[i]) + "\t" + (convolution[i]) + "\t"
+ correlation[i] + "\t");
#panasconnie has the right concept (using printf() or the String.format() method) however I'm going to add my two cents worth anyways.
As you can see in the sample table, all the data is right aligned with the header and as you have stipulated there are some arrays that do not contain the same number of indexes (or elements) and are therefore replaced with "------". Converting the array elements to string (for display purposes only) allows us to easily do this. The conversion never affects any initial array data and therefore remains intact in its original state.
Because the f[] array is the array that contains the most elements it is that array that should be used for the iteration within your print() method. Whichever array contains the greatest amount indexes should be the array used for the iteration. The print() method sample I provide below will automatically determine which array is the largest and will use the length from that array within the for loop. This guarantees a full table display of data.
Keep in mind, there are several different ways to do this sort of thing in Java. I've opted to utilize both the String.format() method and the System.out.printf() method. You can see how both can work for you. They are basically the same.
The code below is over-commented of which can obviously be deleted if not required. It is only there for your initial benefit:
private static void print(double[] f, double[] convolution, double[] correlation) {
// Determine which array contains the most elements.
// We will use that array length for our iteration
// ahead.
int maxArrayLenth = f.length;
if (convolution.length > maxArrayLenth) { maxArrayLenth = convolution.length; }
if (correlation.length > maxArrayLenth) { maxArrayLenth = correlation.length; }
// Determine the location for the start of our header
// so as to achieve proper right alignment. This means
// it wont matter how many digits 'i' will contain, the
// table will always properly align.
int hiVal = String.valueOf(f.length).length();
// Print the Table Header to console...
String header = String.format("%n%" + hiVal + "s %10s %15s %15s","i", "f(i)",
"convolution[i]", "correlation[i]");
System.out.println(header);
// Print the Table Header Underline to the exact length of our
// Table Header. We use the String.join() method in conjuction
// with the Collection Class nCopies() method so as to create
// a string of "=" characters. We subtract 2 from the header
// length because we used the String format's newline (%n) tag
// to create a blank line before the Header itself for a cleaner
// display of multiple tables.
System.out.println(String.join("", Collections.nCopies(header.length() - 2, "=")));
// Do the iteration through all the arrays using the length
// based on our largest array.
for (int i = 0; i < maxArrayLenth; i++) {
// Convert the Double Data Type element from
// each array into a String variable. This way
// if any particular array does not contain a
// designated index the string for that particular
// array element will hold "------".
String strgF; // current element from the f[] Array
if (i > f.length-1) { strgF = "-------"; }
// "%.5f" is used in format() to ensure a decimal precison of 5
else { strgF = String.format("%.5f", f[i]); }
String conv; // current element from the convolution[] Array
if (i > convolution.length-1) { conv = "-------"; }
else { conv = String.format("%.5f", convolution[i]); }
String corr; // current element from the correlation[] Array
if (i > correlation.length-1) { corr = "-------"; }
else { corr = String.format("%.5f", correlation[i]); }
// Print the current Table Data line...
System.out.printf("%" + hiVal + "d %10s %15s %15s%n", i, strgF, conv, corr);
}
}
EDIT: Based on OP's Comment(s):
Why Convert Double Type Array Elements To String:
You can of course use the printf() method to display double type (or float) data to console using the "%f" (or %e or %g) format tag (or otherwise known as the Conversion Type Character):
double num1 = 0.4975282369714;
double num2 = 3.3457546760063;
double num3 = -0.1761164402327;
System.out.printf("%.5f %10.5f %10.3f", num1, num2, num3);
Would display to console something like: 0.49753 3.34575 -0.176
In essence, the printf() method (as does the String.format() method) actually converts the double to string and it sets the decimal precision automatically before displaying it. The problem here however is that if we want to actually display a string (like "-------") in place of a double data type value should that double be non-existent then we can't use the "%f" format tag, we need to use a different format tag (the "%s" format tag) otherwise we end up with a IllegalFormatConversionException. In this particular case, the easiest solution would be to pre-convert each double type value to a special String variable which is to represent that particular array value. If that value is non-existent (which in your case there are no elements to reach) then that variable would hold the String of "-------" instead of a string representation of a Double Type value. This does two things:
It allows us to utilize one specific format tag (%s) within the
printf() method so as to easily display the data in an organized
fashion;
It ensures that regardless of how many Indexes there may be between
two, three, or more different arrays of particular Type values, each
required value to display will contain something, either a
string representation of a Type value or a simple string of dashes
("-------") depending upon the circumstances during the current
iteration of those arrays.
You could of course code a means to build a custom format string for each iteration circumstance and along with each build an Object array to feed that format the required data, but trust me, this would be more runtime labour intensive than it's worth and it's harder to read later on down the road. Keep it simple, after all, it's only for display.
Read up on the System.out.printf() method.
It looks like we are working on the same problem!
https://alvinalexander.com/programming/printf-format-cheat-sheet
http://www.oxfordmathcenter.com/drupal7/node/24
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Have you looked into the printf method with java?
You can format the answer with the print f method %.3f to include just three decimals.
Try
for (int i=0; i<convolution.length; i++) {
System.out.printf("%f, %.3f, %.3f,%.3f", f[i],f[i], convolution[i], correlation[i]);
System.out.println();
}
try something along the lines of that.
The way that I understand it is that the everything is listed in string format. The % marks what values need to be changed or affected by the formatting, they are then followed by characters that make its appearance different. Once you close the string you follow with a comma and list what values from the arrays are being placed or formatted in the table:
printf("%[flags][width][.precision]conversion-character", Values in array separated by the commas)
Please, Please, Please let me know if this has helped out! I am still learning too so there may be errors! Thanks
recently I met a question like this:
Assume you have an int N, and you also have an int[] and each element in this array can only be used once time. And we need to design an algorithm to get 1 to N by adding those numbers and finally return the least numbers we need to add.
For example:
N = 6, array is [1,3]
1 : we already have.
2 : we need to add it to the array.
3 : we can get it by doing 1 + 2.
4: 1 + 3.
5 : 2 + 3.
6 : 1 + 2 + 3.
So we just need to add 2 to our array and finally we return 1.
I am thinking of solving this by using DFS.
Do you have some better solutions? Thanks!
Here's an explanation for why the solution the OP posted works (the algorithm, briefly, is to traverse the sorted existing elements, keep an accumulating sum of the preceding existing elements and add an element to the array and sum if it does not exist and exceeds the current sum):
The loop tests in order each element that must be formed and sums the preceding elements. It alerts us if there is an element needed that's greater than the current sum. If you think about it, it's really simple! How could we make the element when we've already used all the preceding elements, which is what the sum represents!
In contrast, how do we know that all the intermediate elements will be able to be formed when the sum is larger than the current element? For example, consider n = 7, a = {}:
The function adds {1,2,4...}
So we are up to 4 and we know 1,2,3,4 are covered,
each can be formed from equal or lower numbers in the array.
At any point, m, in the traversal, we know for sure that
X0 + X1 ... + Xm make the largest number we can make, call it Y.
But we also know that we can make 1,2,3...Xm
Therefore, we can make Y-1, Y-2, Y-3...Y-Xm
(In this example: Xm = 4; Y = 1+2+4 = 7; Y-1 = 6; Y-2 = 5)
Q.E.D.
I don't know if this is a good solution or not:
I would create a second array (boolean array) remembering all numbers I can calculate.
Then I would write a method simulating the adding of a number to the array. (In your example the 1, 3 and 2 are added to the array).
The boolean array will be updated to always remember which values (numbers) can be calculated with the added numbers.
After calling the add method on the initial array values, you test for every Number x ( 1 <= x <= N ) if x can be calculated. If not call the add method for x.
since my explanation is no good I will add (untested) Java code:
static int[] arr = {3,5};
static int N = 20;
//An Array remembering which values can be calculated so far
static boolean[] canCalculate = new boolean[N];
//Calculate how many numbers must be added to the array ( Runtime O(N^2) )
public static int method(){
//Preperation (adding every given Number in the array)
for(int i=0; i<arr.length; i++){
addNumber(arr[i]);
}
//The number of elements added to the initial array
int result = 0;
//Adding (and counting) the missing numbers (Runtime O(N^2) )
for(int i=1; i<=N; i++){
if( !canCalculate[i-1] ){
addNumber(i);
result++;
}
}
return result;
}
//This Method is called whenever a new number is added to your array
//runtime O(N)
public static void addNumber( int number ){
System.out.println("Add Number: "+(number));
boolean[] newarray = new boolean[N];
newarray[number-1] = true;
//Test which values can be calculated after adding this number
//And update the array
for(int i=1; i<=N; i++){
if( canCalculate[i-1] ){
newarray[i-1] = true;
if( i + number <= N ){
newarray[i+number-1] = true;
}
}
}
canCalculate = newarray;
}
Edit: Tested the code and changed some errors (but rachel's solution seems to be better anyway)
It is a famous problem from dynamic programming. You can refer to complete solution here https://www.youtube.com/watch?v=s6FhG--P7z0
I just found a possible solution like this
public static int getNum(int n, int[] a) {
ArrayList<Integer> output = new ArrayList<Integer>();
Arrays.sort(a);
int sum = 0;
int i = 0;
while(true) {
if (i >= a.length || a[i] > sum + 1) {
output.add(sum + 1);
sum += sum + 1;
} else {
sum += a[i];
i++;
}
if (sum >= n) {
break;
}
}
return output.size();
};
And I test some cases and it looks correct.
But the one who write this didn't give us any hints and I am really confused with this one. Can anybody come up with some explanations ? Thanks!
I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count
I'm new to the concept of arraylist. I've made a short program that is as follows:
ArrayList<int[]> arl=new ArrayList<int[]>();
int a1[]={1,2,3};
arl.add(0,a1);
System.out.println("Arraylist contains:"+arl.get(0));
It gives the output: Arraylist contains:[I#3e25a5
Now my questions are:
How to display the correct value i.e. 1 2 3.
How can I access the single element of array a1 i.e. if I want to know the value at a1[1].
First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add function:
arl.add(1);
arl.add(22);
arl.add(-2);
Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.
More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)
Use Arrays.toString( arl.get(0) ).
arl.get(0)[1]
The setup:
List<int[]> intArrays=new ArrayList<>();
int anExample[]={1,2,3};
intArrays.add(anExample);
To retrieve a single int[] array in the ArrayList by index:
int[] anIntArray = intArrays.get(0); //'0' is the index
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray ) {
System.out.println("Arraylist contains:" + aNumber );
}
To retrieve all int[] arrays in the ArrayList:
//iterate the ArrayList, get and print the elements of each int[] array
for(int[] anIntArray:intArrays) {
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray) {
System.out.println("Arraylist contains:" + aNumber);
}
}
Output formatting can be performed based on this logic. Goodluck!!
In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.
The answer to your first question is therefore
System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );
If you're looking for particular elements, the returned int[] object must be referenced as such.
The answer to your second question would be something like
int[] contentFromList = arl.get(0);
for (int i = 0; i < contentFromList.length; i++) {
int j = contentFromList[i];
System.out.println("Value at index - "+i+" is :"+j);
}
You have to use <Integer> instead of <int>:
int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
arl.add(i);
System.out.println("Arraylist contains:" + arl.get(0));
}
Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.
Using,
Arrays.toString(arl.get(0))
means splitting the String object into a substring if you want to insert anything in between, such as commas.
Here's what I think amv was looking for from an int array viewpoint.
System.out.println("Arraylist contains: "
+ arl.get(0)[0] + ", "
+ arl.get(0)[1] + ", "
+ arl.get(0)[2]);
This answer is a little late for amv but still may be useful to others.
For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.
ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
while(n > 0)
{
int d = scan.nextInt();
Integer temp[] = new Integer[d];
for (int i = 0 ; i < d ; i++)
{
int t = scan.nextInt();
temp[i]=Integer.valueOf(t);
}
arrayList.add(temp);
n--;
}//n is the size of the ArrayList that has been taken as a user input & d is the size
//of each individual array.
//to print something out from this ArrayList, we take in two
// values,index and index1 which is the number of the line we want and
// and the position of the element within that line (since the question
// followed a 1-based numbering scheme, I did not change it here)
System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));
Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.
java.util.Arrays.toString() converts Java arrays to a string:
System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));
ArrayList<Integer> list = new ArrayList<>();
int number, total = 0;
for(int i = 0; i <= list.size(); i++){
System.out.println("Enter number " + (i + 1) + " or enter -1 to end: ");
number = input.nextInt();
list.add(number);
if(number == -1){
list.remove(list.size() - 1);
break;
}
}
System.out.println(list.toString());
for(int i: list){
System.out.print(i + " ");
total+= i;
}
System.out.println();
System.out.println("The sum of the array content is: " + total);
Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.
List<Integer> integerList = IntStream.range(0,100)
.boxed()
.toList();
This is one of the ways, you can initialize the fixed size ArrayList in Java using Java8+ - Stream API. integerList is going to contain integer values from 0 to 99.
How do I get the second dimension of an array if I don't know it? array.length gives only the first dimension.
For example, in
public class B {
public static void main(String [] main){
int [] [] nir = new int [2] [3];
System.out.println(nir.length);
}
}
See that code run live at Ideone.com.
2
How would I get the value of the second dimension of nir, which is 3?
which 3?
You've created a multi-dimentional array. nir is an array of int arrays; you've got two arrays of length three.
System.out.println(nir[0].length);
would give you the length of your first array.
Also worth noting is that you don't have to initialize a multi-dimensional array as you did, which means all the arrays don't have to be the same length (or exist at all).
int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
You can do :
System.out.println(nir[0].length);
But be aware that there's no real two-dimensional array in Java. Each "first level" array contains another array. Each of these arrays can be of different sizes. nir[0].length isn't necessarily the same size as nir[1].length.
use
System.out.print( nir[0].length);
look at this for loop which print the content of the 2 dimension array
the second loop iterate over the column in each row
for(int row =0 ; row < ntr.length; ++row)
for(int column =0; column<ntr[row].length;++column)
System.out.print(ntr[row][column]);
int secondDimensionSize = nir[0].length;
Each element of the first dimension is actually another array with the length of the second dimension.
Here's a complete solution to how to enumerate elements in a jagged two-dimensional array (with 3 rows and 3 to 5 columns):
String row = "";
int[][] myArray = {{11, 12, 13}, {14, 15, 16, 17}, {18, 19, 20, 21, 22}};
for (int i=0; i<myArray.length; i++) {
row+="\n";
for (int j = 0; j<myArray[i].length; j++) {
row += myArray[i][j] + " ";
}
}
JOptionPane.showMessageDialog(null, "myArray contains:" + row);
nir[0].length
Note 0: You have to have minimum one array in your array.
Note 1: Not all sub-arrays are not necessary the same length.
Assuming that the length is same for each array in the second dimension, you can use
public class B {
public static void main(String [] main){
int [] [] nir= new int [2] [3];
System.out.println(nir[0].length);
}
}
Remember, 2D array is not a 2D array in real sense.Every element of an array in itself is an array, not necessarily of the same size.
so, nir[0].length may or may not be equal to nir[1].length or nir[2]length.
Hope that helps..:)
Expansion for multi-dimension array total length,
Generally for your case, since the shape of the 2D array is "squared".
int length = nir.length * nir[0].length;
However, for 2D array, each row may not have the exact same number of elements.
Therefore we need to traverse through each row, add number of elements up.
int length = 0;
for ( int lvl = 0; lvl < _levels.length; lvl++ )
{
length += _levels[ lvl ].length;
}
If N-D array, which means we need N-1 for loop to get each row's size.
//initializing few values
int[][] tab = new int[][]{
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1}
};
//tab.length in first loop
for (int row = 0; row < tab.length; row++)
{
//tab[0].length in second loop
for (int column = 0; column < tab[0].length; column++)
{
//printing one value from array with space
System.out.print(tab[row][column]+ " ");
}
System.out.println(); // new row = new enter
}