so i'm trying to setup an array that holds x y coordinates.
the program seems to work but my print results are memory addresses.
here's my code:
static class Point{
int x;
int y;
#Override
public String toString() {
return x + " " + y;
}
}
public static Object thePoints( int x, int y){
Point[] mypoints = new Point[10];
for (int i = 0; i < mypoints.length; i++){
mypoints[i] = new Point();
}
mypoints[0].x = 200;
mypoints[0].y = 200;
return mypoints;
}
public static void main(String args[]) {
Object thing = thePoints(0,0);
System.out.print(thing);
}
}
input is appreciated.
You are printing out an array of type Point[] in your main() method, contrary to what it appears. A quick way to get around this problem is to use Arrays.toString(). Try changing the code in your main() method to this:
public static void main(String args[]){
Object thing = thePoints(0,0);
System.out.print(Arrays.toString((Point[])thing));
}
If you also refactor Point.toString() to the following, then you get some fairly nice looking output:
static class Point{
int x, y;
#Override
public String toString() {
return "(" + x + ", " + y + ")"; // print out a formatted ordered pair
}
}
Output:
[(200, 200), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
You are trying to print an array of Point Objects which is why it prints out the memory address. You can use an ArrayList instead of an array. Printing an array list would call the toString method of each element which in you case is the toString method of Point Class.
Your printing the 'Object thing' directly. System.out.print() only works on strings and primitive datatypes, so if you wanted to print information about the 'Object thing' you would have to use the toString() method you declared for the class 'Point'.
System.out.println(thing[0].toString());
Related
I'm new to java and having trouble basically passing an array through to a method in another class, using the values to compute a new array, and then passing that back again to print. The problem is that when it prints the array it always prints the empty string. When I step through in debug mode I can see that the values are getting passed in and the array gets generated, but then when it prints it is always empty. It seems like somehow to code is failing to return the correct array maybe. Here is my code
public static void main(String[] args) {
double[] rnoDivs;
double[] rnoEarnings;
Company rno = new Company();
rnoDivs = new double[] {355, 355, 315, 240, 190};
rno.yearlyDividendsGrowth(rnoDivs);
rnoEarnings = new double[] {0.019, 3.451, 5.210, 3.543, 2.960};
rno.yearlyEarningsGrowth(rnoEarnings);
This is passed through to my other class
public class Company {
double[] yearlyEarningsGrowth = {};
public double[] getYearlyEarningsGrowth(){return yearlyEarningsGrowth;}
public double[] yearlyEarningsGrowth(double[] yearlyEarnings){
double[] yearlyEarningsGrowth = new double[yearlyEarnings.length];
for (int x = 0; x <= yearlyEarnings.length; x++) {
if (x < yearlyEarnings.length - 1) {
yearlyEarningsGrowth[x] = (yearlyEarnings[x] / yearlyEarnings[x + 1]) * 100;
}
}
return yearlyEarningsGrowth;
}
}
And then I try to print this statment
Company[] companies = {rno};
for(int i=0; i < companies.length; i++) {
double[] array = companies[i].getYearlyEarningsGrowth();
System.out.println("Yearly earnings growth: " + Arrays.toString(array));
}
But then I just get the array "[]". Any help with this would be appreciated! I seem to be going in circles because everything looks correct.
I been trying to implement what been discussed here in this thread Algorithm to apply permutation in constant memory space. However I am not able to may be understand the problem solution correctly or my code has some bug which I cant detect and fix. Ant kind of help is appreciated.
public class ArrayPermute{
public static void main(String[] args){
char[] arr = {'a','b','c','d'};
int[] p = {2,0,1,3};
for(int i=0; i<arr.length; i++){
int tmp = i;
while(p[tmp] >= 0){
char t = arr[p[tmp]];//d
arr[p[tmp]] = arr[tmp];
arr[tmp]=t;
int _tmp = p[tmp];
p[tmp] = -1;
tmp = _tmp;
print(arr);
print(p);
}
}
for(char i: arr){
System.out.print(i + " ");
}
}
public static void print(char[] arr){
for(char c: arr){
System.out.print(c + " " );
}
System.out.println();
}
public static void print(int[] arr){
for(int c: arr){
System.out.print(c + " " );
}
System.out.println();
}
}
Don't use the very array elements to keep the displaced values (i.e. swap between the elements of the initial array), this is how you screwed your code.
Instead, use some O(1) temp variables to keep the "displaced" value and where from that value originated.
Commented code below, with 2 test cases (note the use of Arrays.toString instead of your custom print(char[]/int[]) methods)
import java.util.Arrays;
public class InPlacePermutation {
static public void inPlacePermute(char arr[], int p[]) {
for(int i=0; i<p.length; i++) {
if(p[i]<0) continue; // already visited
char toMove=arr[i]; // value-at-hand
int currIx=i; // index from where the value-at-hand originated
while(currIx>=0 && p[currIx]!=i) { // as long as we aren't back where we started
int destIx=p[currIx];
if(destIx<0) {
// the permutation is bad, we are stepping again
// on places we stepped before. This should not happen
throw new IllegalArgumentException("bad permutation");
}
// take the value "at hand" before it get overwritten
char destVal=arr[destIx];
// place current "value at hand" in the destination
arr[destIx]=toMove;
// update bookkeeping the vals/indexes values
p[currIx]=-1; // mark where we've been
currIx=destIx; // then take a step further
toMove=destVal; // don't forget to carry the new "value at hand"
}
// now we are back where we started with a "value at hand"
arr[i]=toMove;
p[currIx]=-1; // mark the source of the moved value as visited
}
}
static public void main(String[] args) {
char[] arr = {'a','b','c','d'};
int[] p = {2,0,1,3};
System.out.print("arr:"+Arrays.toString(arr)+" + pmt:"+Arrays.toString(p) + " =>");
inPlacePermute(arr, p);
System.out.println(" "+Arrays.toString(arr));
System.out.println();
// two cycles and one in place
arr = new char[]{'a','b','c','d', 'e', 'f'};
p = new int[]{2,3,4,1,0,5};
System.out.print("arr:"+Arrays.toString(arr)+" + pmt:"+Arrays.toString(p) + " =>");
inPlacePermute(arr, p);
System.out.println(" "+Arrays.toString(arr));
}
}
Output:
arr:[a, b, c, d] + pmt:[2, 0, 1, 3] => [b, c, a, d]
arr:[a, b, c, d, e, f] + pmt:[2, 3, 4, 1, 0, 5] => [e, d, a, b, c, f]
You don't need to make a swap when your reach the beginning of the cycle. That is, it should go like:
int tmp = i;
int start = i;
while (p[tmp] >= 0 && p[tmp] != start) {
// Your code here doesn't change
}
if (p[tmp] == start) {
p[tmp] = -1;
}
hello everyone I got this codes but I need to make some constraint on my arrays: public static void main (String[] args)
{Random myRand = new Random ();
// Pick array size T from 1 to 100.
int T = 1 + myRand.nextInt(5);
System.out.println("T="+(T));
int C = 1 + myRand.nextInt(100);
System.out.println("C="+(C));
// Declare array of size T.
int [] production_cost=new int [T];
int []stock1= new int [T];
int[]stock2= new int [T];
int[]fix_cost1= new int [T];
int[]fix_cost2= new int [T];
int[] Demands=new int[T];
// Fill the array with random numbers.
{for (int i=0; i< T; i++){
production_cost[i] = myRand.nextInt(Integer.max(0,20));
stock1[i] = myRand.nextInt(Integer.max(0, 20));
stock2[i]= myRand.nextInt(Integer.max(0,20));
fix_cost1[i]=myRand.nextInt(Integer.max(10, 20) );
fix_cost2[i]=myRand.nextInt(Integer.max(20,30));
Demands[i] = myRand.nextInt(Integer.max(1,C));}
System.out.println("p2::"+Arrays.toString(production_cost));
System.out.println("h1::"+Arrays.toString(stock1));
System.out.println("h2::"+Arrays.toString(stock2));
System.out.println("K1::"+Arrays.toString(fix_cost1));
System.out.println("K2::"+Arrays.toString(fix_cost2));
System.out.println("d::"+Arrays.toString(Demands));
You can see this link : Fill an array with random numbers
You need to add logic to assign random values to double[] array using
randomFill method.
Change
public static double[] list(){
anArray = new double[10];
return anArray; }
To
public static double[] list() {
anArray = new double[10];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray; }
Then you can call methods, including list() and print() in main method to generate random double values and print the
double[] array in console.
public static void main(String args[]) {
list(); print(); }
One result is as follows:
-2.89783865E8
1.605018025E9
-1.55668528E9
-1.589135498E9
-6.33159518E8
-1.038278095E9
-4.2632203E8
1.310182951E9
1.350639892E9
6.7543543E7
This program is for printing sum of all the numbers in the array given as input parameter. However this does not happen. Please let me know what is the mistake and provide me the solution with explanation.
namespace linkedLists
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int x = sumOfNum(arr, 0);
Console.WriteLine(x);
Console.ReadLine();
}
public static int sumOfNum(int[] arr, int x)
{
int[] arr_new = new int[arr.Length - 1];
if (arr.Length > 1)
{
x += arr[arr.Length - 1];
for (int i = 0; i < arr.Length - 1; i++)
{
arr_new[i] = arr[i];
}
}
if (arr.Length > 1)
{
sumOfNum(arr_new, x);
}
return x;
}
}
}
Your question's title is "how to avoid a return statement in recursion", which is exactly what you should be doing instead of avoiding in a recursion scenario.
But this is not the only problem with your code, because it does nothing like what you described it is supposed to do.
As already mentioned in the comments, this is not something that requires (or for which it is recommended) to use a recursive approach. It can be done, but is inefficient and could lead to a stack overflow if you have a large input array (it needs a new stack frame for each recursive method call in c#).
To solve this recursively, you need to try and state the problem as a recursive problem, before you start trying to code it. In pseudo code, for an input array x of size n:
array_sum(x):
if (x is empty)
return 0;
else
return x[0] + array_sum(x[1:n-1])
An implementation in C# would try to avoid allocating a new array instance (as opposed to what one of the non-functioning parts in the code of your question is doing), and instead keep track of the start index into the input array:
public static array_sum(int startIndex, int[] x)
{
// ...
}
If you want to know the answer without the recursion you just iterate over it while summing the numbers.
If you want to make a recursive solution the return is essential. Without it the recursion is just a different way of making a for loop.
public static int sumOfElements(int[] arr, int currentIndex, int accumulator)
{
if( finished-expression )
return accumulator;
else
return sumOfElements(...);
}
public static int sumOfElements(int[] arr)
{
return sumOfelements(arr, 0, 0);
}
Your mistake is that x is a different one at each iteration. You don't use the returned value from the recursion so you have the sum of one element as the result.
Agree with the previous comments about recursion, inefficiency, and complexity but as an exercise below is the minimal number changes to get the code to work.
Changes:
Added array size guard
Moved sum out of if-block
Added return statement
Code:
namespace linkedLists
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int x = sumOfNum(arr, 0);
Console.WriteLine(x);
Console.ReadLine();
}
public static int sumOfNum(int[] arr, int x)
{
if (arr.Length == 0) return x; // Change #1
int[] arr_new = new int[arr.Length - 1];
x += arr[arr.Length - 1]; // Change #2
if (arr.Length > 1)
{
for (int i = 0; i < arr.Length - 1; i++)
{
arr_new[i] = arr[i];
}
}
if (arr.Length > 1)
{
return sumOfNum(arr_new, x); // Change #3
}
return x;
}
}
}
Assuming that you are required to use recursion as an exercise I will comment no further on that.
The reason your programme does not work appears to be that when the array has only one element, your do not add that element to the subtotal (that you call x) before returning it.
While recursion is somewhat expensive, your program uses roughly ½arr.Length² ints, which would need a terabyte of memory in the unlikely event that you applied it to an array of length 500,000! So you would be far better not to copy the array.
I am creating a game using an array, I have my Hunter class which looks somewhat like this ;
public static int x= 11;
public static int y =11;
public static String name = "H";`
And a method for its path using x and y.
I have declared hunter as an array in my board (2d array) class this way;
public Hunter hunters[] = new Hunter[5];
and the position of a hunter is declared in the board class as ;
a2[Hunter.x][Hunter.y] = Hunter.name;
Question: I want 5 hunters to appear on the board, how do I use the array to spawn additional 4 hunters? Thanks.
you created your array fine all you need to do is use it:
for (int i = 0; i < 5; ++i)
{
a2[hunters[i].x][hunters[i].y] = hunters[i].name
}
also, you need to make your Hunter members non-static
class Hunter
{
private int x, y;
public void setLocation(int x_, int y_)
{
x = x_; y = y_;
}
}
you get the idea :)
The static keyword (assuming you are using C++, java, C#) means that the variable is shared among all instances of the Hunter class. To allow each Hunter to have its own position, remove the static keyword and initialize them with a constructor.
I'll assume you're using Java bases on your use of String:
public class Hunter {
public int x;
public int y;
public String name;
public Hunter(int x, int y, string name) {
this.x = x;
this.y = y;
this.name = name;
}
}
Then to initialize 5 you would do
int numHunters = 5;
for (int i = 0; i < numHunters; i ++) {
hunters[i] = new Hunter(/* put x and y and name here */);
}
You can then use them to populate the board:
for (int i = 0; i < numHunters; i ++) {
Hunter h = hunters[i];
a2[h.x][h.y] = h.name;
}
You didn't specify what language you're using. That would help a bit.
At a minimum, try removing the "static" keyword from your property definitions.
In C#, your Hunter class might look like
public class Hunter
{
public int x;
public int y;
public String name;
public Hunter(int newX, int newY, String newName)
{
x = newX;
y = newY;
name = newName;
}
}
You create new Hunters using Hunter h1 = new Hunter(11, 11, "H");. Once created, you can do whatever with it.
You may want to do some reading up on Object Oriented Programming - see Intro to OOP esp sections 4.3 - 4.5 (they're short)