I am new to programming and trying to learn Java and I am trying to do some Java questions that I find quite tough for a beginner. The question asks to write a method that takes a double c and and array v of type double as it's parameters. The method should return a new array of double formed by multiplying all the elements of array v by c.
I really have no idea to do this and if anyone could help on this I'd appreciate it.
I have written some code but I don't understand what I am supposed to do exactly.
public static double times( double c, double [] v)
int i =0;
for( i =0; i < v .length; i++){
myArray =(c * v[i]);
i++;
}
}
public class Main {
public static void main(String[] args) {
double [] v={5.1,5.2,3.0,4.0};
double c= 4.1;
System.out.println(times(v,c));
It’s a good start but your method should return an array of doubles: double[].
public static double[] times( double c, double [] v)
double[] myArray = new double[v.length]; // this is a new array
int i =0;
for( i =0; i < v .length; i++){
myArray[i] =(c * v[i]); // assign new values to your array
// i++; << don’t need this line as your for loop is already incrementing i
}
return myArray;
}
The answer mentioned above is correct but you could do the same in the same array i.e double[] v, instead of creating a new array, just for optimization scenario
Read carefully your problem.
I added comments to the code so you understand what you did wrongly:
// Return a double[] instead of double
public static double[] times( double c, double [] v)
// Create a new double array
double[] myArray = new double[v.length];
for (int i = 0; i < v.length; i++) {
// Set each element of the new array equals to the old array element in
// The same position multiplied by c
myArray[i] = c * v[i]; // Parenthesis are not needed here
// i++ is not needed because you already add 1 to i in the for instruction
}
// Return the new array
return myArray;
}
Also be careful what you print. I believe you want to print the new values not the array reference.
public static void main(String[] args) {
double[] v = {5.1, 5.2, 3.0, 4.0};
double c = 4.1;
double[] newV = times(c, v);
System.out.print("Array address: ");
System.out.println(newV);
System.out.print("Array as string: ");
System.out.println(Arrays.toString(newV));
System.out.print("Array values for: ");
for (int index = 0; index < newV.length; ++index) {
System.out.println(newV[index]);
}
System.out.print("Array values foreach: ");
for (double value : newV) {
System.out.println(value);
}
}
Related
I have to do the Orthogonalization process using Gram-Schimdt so I can get A=QR. I'm working with the matrix columns as double[] and they are stored in an ArrayList, the thing is, I'm just calculating Q so I can do the rest which is easier once I got Q. But my problem is that when the program gets to add the finalArray, I don't know why the parameter array got modified and every vector in it is altered and obviously the result is wrong. What I'm doing wrong? (By the way, I can't use libraries of Java to solve this). Also I test the algorithm doing it with my own hands and it should works because I also print the result and notice where it got altered
/*
I should do Uk = (Vk - (Uk-1*Vk)*Uk-1 - ... - (U1*Vk)*Uk1)/||Uk||
Where ||Uk|| = Length of Uk
Vectors U own to finalArray and the V ones own to array
*/
public ArrayList< double[] > gramSchmidt(ArrayList< double[] > array)
{
ArrayList< double[] > finalArray= new ArrayList<>();
//I set the first vector because it never changes, it's always the first vector of the array receive divided between it's length
finalArray.add(multiplyScalarPerVector(1/(calculateVectorLength(array.get(0))), array.get(0)));
//This last line is the one that modifies EVERYTHING in array and it shouldn't
for(int i=1; i<array .size(); i++)
{
double[] newVector= substractVectors(array .get(i), proyection(finalArray.get(i-1),array .get(i)));
for(int e=i-1;e>0;e--)
{
newVector= substractVectors(newVector, proyection(finalArray.get(e-1),array .get(i)));
}
newVector= multiplyScalarPerVector(1/(calculateVectorLength(newVector)), newVector);
finalArray.add(newVector);
}
return finalArray;
}
//Obtain the (Uk-1*Vk)*Uk-1
public double[] proyection(double[] array1, double[] array2)
{
double dotProductResult= dotProduct(array1,array2);
double[] finalVector= multiplyScalarPerVector(dotProductResult, array1);
return finalVector;
}
//To do Uk-1*Vk
public double dotProduct(double[] vector1, double[] vector2)
{
double result = 0;
for(int i=0; i<vector1.length; i++)
{
result +=vector1[i]*vector2[i];
}
return result ;
}
public double[] multiplyScalarPerVector(double scalar, double[] vector)
{
double[] newVector = new double[vector.length];
for(int i=0; i<vector.length; i++)
{
newVector[i] = scalar*vector[i];
}
return newVector;
}
public double[] substractVectors(double[] vector1, double[] vector2)
{
double[] finalVector= new double[vector1.length];
for(int i=0; i<vector1.length; i++)
{
finalVector[i] = vector1[i] - vector2[i];
}
return finalVector;
}
//Calculate the euclidean distance
public double calculateVectorLength(double[] vector)
{
double result = 0;
for(int i=0; i<vector.length; i++)
{
result +=Math.pow(vector[i], 2);
}
return Math.sqrt(result );
}
When you assign
double[] newVector= vector;
then you don't create a new object, but newVector and vector reference to the same object. newVector is not a new object it is a reference to the same object as vector references to.
This causes that in the loop
for(int i=0; i<vector.length; i++)
{
newVector[i] = scalar*vector[i];
}
newVector and vector are change alike. An assignment to newVector[i] changes also vector[i], because they refer to the same object.
The same is the case when you do:
double[] finalVector= vector1;
for(int i=0; i<vector1.length; i++)
{
finalVector[i] = vector1[i] - vector2[i];
}
Note, you don't create new vector objects with new content, but you change the input vector objects and return a reference to the changed objects.
Because of that you change source vector objects, which are still needed in the further calculation. This causes that the final result is not as it ought to be.
Create new objects to solve the issue:
double[] newVector= new double[vector.length];
double[] finalVector= new double[vector1.length];
See also Java assigning object reference
a) Create an array of random numbers, whose size is a power of 2. Using loops, find the difference for each pair of values (index 0 & 1, 2 & 3, 4 & 5 etc.) and store them in a new array. Then find the difference for each pair of differences and so on until you have only one difference left.
Hint: Think carefully about your loop bounds
b) Now, create a solution that is 'in place', i.e., It does not require the creation of new arrays. Again, this will require careful consideration of loop bounds.
c) Finally, write a solution that makes use of a recursive function, instead of loops.
I have been trying to solve the above exercise but I am stuck with what b means and how can I use recursive function. The following is my solution for part a :
public class RandomArray{
private static double ArrayFn(int p){
double[] orignalArray = new double[(int)Math.pow(2,p)];
for (int i = 0; i< orignalArray.length; i++){
orignalArray[i] = (int)(Math.random() * 10) ;
}
System.out.println(Arrays.toString(orignalArray));
double y = ArrayDifferenceloop(orignalArray);
System.out.println("Value of Array" + y);
return y;
}
private static double ArrayDifferenceloop(double[] arg){
do{
double[] newArr = new double[(arg.length/2)];
for (int i = 0; i< arg.length; i+=2){
newArr[i/2] = arg[i] - arg[i+1];
}
System.out.println("New Array is =" + Arrays.toString(newArr));
//copy newArr to arg
arg = new double[(newArr.length)];
System.arraycopy(newArr,0,arg,0,newArr.length);
}while(arg.length > 1);
return arg[0];
}
public static void main(String[] args){
double z = ArrayFn(3);
System.out.println("value" + z);
}
}
I can help you with point b)
you can store the differences in the original array itself:
difference of [0] and [1] put in [0],
difference of [2] and [3] put in [1],
and so on.
You can calculate the index to put the result from the indexes of the pair or keep two index variables for the result and for picking the pairs.
you just keep iterate over the original array repeatedly, each time over fewer cells until only two cells left.
the recursive solution should be clear...
I guess option b means use the original array to store the differences, rather than creating a new array.
This can be achieved by dynamically changing the active range of elements used, ignoring others (see also Sharon Ben Asher answer ):
private static double ArrayDifferenceloop(double[] array){
int activeLength = array.length;
do{
int index =0; //index where to store difference
for (int i = 0; i< activeLength; i+=2){
array[index++] = array[i] - array[i+1];
}
System.out.println("Modified array (only "+index+ " elements are significant) " + Arrays.toString(array));
activeLength /=2;
}while(activeLength > 1);
return array[0];
}
/* Solution for part (b) hope it works for you*/
public class RandomArray{
static int len; /*modification*/
private static double ArrayFn(int p){
double[] orignalArray = new double[(int)Math.pow(2,p)];
len=(int)Math.pow(2,p);
for (int i = 0; i< orignalArray.length; i++){
orignalArray[i] = (int)(Math.random() * 10) ;
}
System.out.println(Arrays.toString(orignalArray));
double y = ArrayDifferenceloop(orignalArray);
System.out.println("Value of Array" + y);
return y;
}
private static double ArrayDifferenceloop(double[] arg){
do{
for (int i = 0; i< len; i+=2){ /*modification*/
arg[i/2] = arg[i] - arg[i+1];
}
//copy newArr to arg
//arg = new double[(arg.length)];
len=len/2; /*modification*/
System.out.print("new Array : ");
for(int i=0;i<len;i++){
System.out.print(arg[i]+" , ");
}
// System.arraycopy(arg,0,arg,0,len);
}while(len > 1);
return arg[0];
}
public static void main(String[] args){
double z = ArrayFn(3);
//System.out.println(Arrays.toString(orignalArray));
System.out.println("value" + z);
}
}
I am using a list of integer arrays, which is a class variable, to hold the answers. The integer arrays are added to the list in a method, and the results are fine (has 1s). But when I fetch it in main method, the value in it is all 0s! I do not understand, where is the list changed?
public class test {
private static int sum=0;
static ArrayList<Integer[]> res = new ArrayList<Integer[]>();
private static double max=0;
public static void main(String[] args) {
int n = 6;
double B = 23.6;
double[] menu = { 1.2, 2, 2.5, 3.5, 3.2, 6.2, 7.8, 4.0, 5.6, 10, 6.5 };
Integer[] solution = new Integer[menu.length];
combinate(menu, 0, n,0, res, solution);
for(int i=0;i<res.size();i++) {
//not getting the element!!!!!!!!!!!!
//Integer[] sol = res.get(i);
System.out.println(i+" "+res.get(i));
System.out.println("Arraylist contains:"+Arrays.toString( res.get( i ) ) );
double sums = 0.0;
for (int j = 0; j < res.get(i).length; j++) {
if(res.get(i)[j]!=null)
sums += menu[j] * res.get(i)[j];
}
if (max < sums && sums < B) {
max = sums;
}
}
System.out.println(max + " max");
}
public static void combinate(double[] left, int n, int k,int sum,
ArrayList<Integer[]> res, Integer[] holder) {
if (n == left.length) {
if (sum == k) {
res.add(holder);
System.out.println(res.size()+" "+Arrays.toString(res.get(res.size()-1)));
}
sum = 0;
return;
}
{
holder[n] = 1;
sum++;
combinate(left, n + 1, k, sum,res, holder);
holder[n] = 0;
sum--;
combinate(left, n + 1, k, sum,res, holder);
}
}
}
}
The answers looks like this:
when print in method combinate, the list elements looks like [1111100000]
while in main method, there are all [000000000000]
what goes wrong here?
if (sum == k)
{
res.add(holder.clone()); // take copy of holder at that moment
System.out.println(res.size()+" "+Arrays.toString(res.get(res.size()-1)));
}
Will Help.
[See Experiment : http://rextester.com/DNNZ68674 ]
Have your method "combinate" return new res like public static ArrayList<Integer[]> combinate(double[] left, int n, int k,int sum,
ArrayList<Integer[]> res, Integer[] holder)
then in your main : res = combinate(...);
You have only a single Integer[] instance that you add to your result (res.add(holder)) and overwrite while unwinding the recursion.
You should add a clone of your array to the result:
res.add(holder.clone());
In the original code you're passing the "holder"-variable as a parameter. In Java parameters are passed by value.
This means, you can change the value inside of the combinate-function, but this will never be reflected back to the calling main-function - that's the nature of call by value.
I have a programm that creates 2D arrays of ints and double (some are int, some are double). I wrote a method to print those arrays as a map to the console. But instead of having two methods for int and double each, i wondered if its possible to accept both int and double as a parameter.
This is my print function:
private void printMap(int map[][]){
for (int i=0; i<map.length;i++){
for (int j=0; j<map[i].length;j++){
if(map[i][j]<1000)System.out.print(" ");
if(map[i][j]<100)System.out.print(" ");
if(map[i][j]<10)System.out.print(" ");
System.out.print(imap[i][j]+" ");
}
System.out.println("");
}
}
Right now i have 2 times the same except for the params, like:
private void print_intMap(int map[][]){..}
private void print_doubleMap(double map[][]){..}
and I want it to be like
private void printMap(/*either int or double*/){..}
Any ideas?
thx in advance
You could use the Number type as your array type. It is extended by both Integer and Double. This type can be created from either double or int primitive types via Autoboxing which will do this conversion for you automatically.
Number doubleNumber = 1.0;
Number intNumber = 1;
Then your code would look like:
private void printMap(Number map[][]) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if(map[i][j].intValue() < 1000) System.out.print(" ");
if(map[i][j].intValue() < 100) System.out.print(" ");
if(map[i][j].intValue() < 10) System.out.print(" ");
System.out.print(imap[i][j].intValue() + " ");
}
System.out.println("");
}
}
I believe your best option here would be to use polymorphism. Essentially, you create two methods with the same name. The only difference will be the parameters- one will take an int, and the other will take a double. For example
private void printMap(int map[][])
private void printMap(double map[][])
This would allow you to call printMap with your array without needing a check on the type.
What you want to do is called "Method Overloading": http://en.wikipedia.org/wiki/Method_overloading
Here is a great example fiting with what you want to do! :
public class MainClass {
// method printArray to print Integer array
public static void printArray(Integer[] inputArray) {
// display array elements
for (Integer element : inputArray)
System.out.printf("%s ", element);
System.out.println();
}
// method printArray to print Double array
public static void printArray(Double[] inputArray) {
// display array elements
for (Double element : inputArray)
System.out.printf("%s ", element);
System.out.println();
}
// method printArray to print Character array
public static void printArray(Character[] inputArray) {
// display array elements
for (Character element : inputArray)
System.out.printf("%s ", element);
System.out.println();
}
public static void main(String args[]) {
// create arrays of Integer, Double and Character
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(integerArray); // pass an Integer array
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array
System.out.println("\nArray characterArray contains:");
printArray(characterArray); // pass a Character array
}
}
Taken from this website: http://www.java2s.com/Tutorial/Java/0100__Class-Definition/Usingoverloadedmethodstoprintarrayofdifferenttypes.htm
This is impossible. A few things you can do are:
Method overloading. You can make methods with the same name, as long as they have different parameters. E.g.:
private void printMap(int map[][]) {...}
private void printMap(double map[][]) {...}
You can then call printMap with either and int[][] or a double[][] as the argument, and it will execute the corresponding method.
Make it accept a Number[][]:
private void printMap(Number map[][]) {...}
You can keep the method taking as parameter the double and make a cast when calling the method with an 'int'
printMap((double)map[][])
I suggest converting the int variable into double variable, and then use it in your class (i believe it is the simplest solution):
int x=7;
double y=(double)x;
print_doubleMap(y);
//or
print_doubleMap((double)x);
You can use reflection but it is ugly
public static void print(int[][] ints) {
printMatrix(ints);
}
public static void print(double[][]] doubles) {
printMatrix(doubles);
}
public static void printMatrix(Object o) {
int len1 = Array.getLength(o);
for(int i = 0; i < len1; i++) {
Object o2 = Array.get(o, i);
int len2 = Array.getLength(o2);
for(int j = 0; j < len2; j++)
System.out.printf("%4s ", Array.get(o2, j);
System.out.println();
}
}
I don't know if this is any cleaner than just copying a method.
public static void print(int[][] ints) {
for(int[] is : ints) {
for(int i : is)
System.out.printf("%4d ", i);
System.out.println(i);
}
}
Basically I am wondering how I could make a method that takes a String that has a series of decimal numbers separated by spaces and then (after splitting the string according to separate numbers) returns a double. Then using the doubles returned, returning the sum of all the decimal numbers rounded to the nearest whole number.
Example: Like let's say I input String “42.5 7.2 1.2” and I want to make it return the sum of all the decimal numbers rounded to the nearest whole number, which here would be 51.0.
Here is my attempt so far.
String s = text1;
String[] ls;
ls = s.split(" ");
for(int i = 0; i<= s.length(); i++){
double a = Double.parseDouble(ls[i]);
Start with String.split, this will return an array of Strings
Create an array of double set to the same size as the String array
Iterate this array of Strings and parse each value to a double, adding them to the double array
Return this double array.
Iterate the double array, adding each value to sum value of type double.
Use Math.round to round the result
Take a look at Arrays and Control Flow Statements, in particular The for Statement
...Create an array of double...
String[] ls = s.split(" ");
double[] doubles = new double[ls.length];
...Iterate this array of Strings and parse each value to a double...
for (int index = 0; index < ls.length; index++) {
doubles[index] = Double.parseDouble(ls[index]);
}
You need something like this (if I understand your question):
public static double roundedSum(String s) {
String[] ls = s.split(" ");
double sum = 0;
for(int i = 0; i < ls.length; i++){
sum += Double.parseDouble(ls[i]);
}
return Math.round(sum);
}
And then to test it:
public static void main(String[] args) {
String s = "42.5 7.2 1.2";
System.out.println ( roundedSum(s) ); // prints 51.0
}
As a note, your for loop was wrong:
for(int i = 0; i<= s.length(); i++){
First of all, you can never go until <= the length (unless you subtract 1). Indexes start at 0, so the last position of the string is the length - 1.
Also, you were using the length of the string; you need to be using the length of the array as the bound.
public float rnd (String st) {
String[] v = st.split(" ");
float sum = 0.0f;
for (String s : v) {
sum += Float.valueOf(s);
}
return(Math.round(sum));
}
or replacing the float return by an int return (the question in not very clear on this).
Something like this?
public double getSum(String dec)
{
String[] nums = dec.split(" ");
double total = 0;
for(String a : nums)
total += Double.parseDouble(a);
return Math.round(total);
}
To read input just do
public void read()
{
Scanner scan = new Scanner(System.in);
//declare variable
variableHere = scan.nextLine() scan.nextInt() or w.e. you want
}
Here this works
package Split;
public class Split {
public Split(){
addEm("42.5 7.2 1.2");
}//constructor
private void addEm(String st) {
int i =0;
int len = st.length();
double sum =0 ;
String s = "";
st.charAt(0);
for(int j =0; j< len;j++ ){
s = s+st.charAt(j);
if(st.charAt(j)==' ' || j==len-1){
sum = sum + Double.parseDouble(s);
s = "";
}
}
System.out.print(sum);
}
public static void main (String args[]){
new Split();
}
}
the output will look like this
50.900000000000006...
Just round up the value to an int before output
If I want to avoid all rounding problems, but don't care about using arrays or using doubles, I might do it like this.
public double splitAndSum(String input) {
BigDecimal sum = BigDecimal.ZERO;
for (String number : input.split("\\s+")) {
sum = sum.add(new BigDecimal(number));
}
return sum.round(new MathContext(0)).doubleValue();
}