import java.util.Arrays;
public class main {
public static void main (String[] args ) {
int rand = (int)Math.random()*17;
int[][] output = array(rand);
//System.out.println(Arrays.deepToString(output));
}
public static int[][] array(int n) { //btw n is y/height
int x = (int)Math.pow(2, n-1); //# of col
int max = (int)Math.pow(2, n) - 1;
int [][] out = new int[n][x];
for (int i = 0; i < n; i++) {
for (int j = 0; j < x; j++) {
out[i][j] = (int) (Math.random() * (max + 1));
}
}
return out;
}
}
I'm learning how to code and a cousin gave me their old laptop and I found some small java files here and there. This one is called "itsmagic.java" but I don't really understand what the purpose is?
From what I understand it seems that we are creating a 2D array of some sort and then what? I understand that deepToString is supposed to be used to convert multidimensional arrays to strings, but how does that work? Why is it commented out?
What I understood from your code is:
-Pick a random int n from 0 to 17.
-setting a x = 2^(n-1)
-setting a max= 2^n
-Creating a double entry tab dimensions n*x
-Filling each case with a random number between 0 and max
So the result is a double entry tab of dimensions [0 to 17][2^(0 to 16)] filled with numbers between 0 and 2^(0 to 17)
Arrays.deepToString() is used for either single or multidimensional arrays, it's usually used for multidimensional arrays as it can clearly output each array.
You will be able to output both the first and second array of "output" in your example.
If you run a test and add in the array manually, you will see it prints both the arrays together instead of showing just the first dimension.
I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;
I'm trying to code a method which draws a cross in JAVA. (see the photo for an example).
Here is the example:
Few Questions:
how do I give an array the dimensions via parameter? It seems that Eclipse needs a number instead of variables for the array dimensions. I thought it is possible to give the method a parameter, how big the dimensions of the array should be.
Don't get the idea how to tell the loop which one of the array positions should be an X and which one not.
Here is my code idea so far...it does not really what it should do :) I took "1" instead of "X", so I can do it with an int array.
public void drawCross(int number){
int i,j;
int array[][]=new int[40][40];
for(j=1;j<=number;j++){
for(i=1;i<=number;i++){
if(array[i]==array[j]){
array[i][j]=1;
System.out.print(array[i][j]+" ");
}
}
System.out.print("\n");
}
}
Thank you in advance.
Pete
As this does not really seem homework, the solution
int[][] array = new int[number][number];
for (int i = 0; i < number; i++){
for (int j = 0; j < number; j++){
if (i == j || i == number - 1 - j) {
array[i][j] = 1;
}
System.out.print(array[i][j] + " ");
}
System.out.print("\n");
}
int[][] a is the conventional way. int a[][] is syntactic sugar for C programmers.
In math i normally is the row, and j the column, so switched the for-loops.
Arrays are indexed from 0.
The condition should say whether one is on one of both diagonals, so only concerns the indices i and j.
|| is OR, and && is AND (should you not already know).
As you see, the matrix array is not needed
So:
boolean isOnDiagonal = i == j || i == number - 1 - j;
System.out.print(isOnDiagonal ? "X " : ". "); // if-then-else operator.
Write a program that prompts the user to enter a nxn matrix of double values and displays a new matrix which has the columns of the initial matrix sorted. You may use any sorting algorithm to solve the problem; please specify the name of the used sorting algorithm into your code header. Your program must implement a sorting algorithm; you cannot use the sorting methods provided in the Array class. The sorting should be implemented into a method, in which a new array is returned and the original array is intact:
public static double[][] sortCol(double[][] a)
The program should also implement a method that prints the initial and the result matrices to user. The print out should be nicely formatted. Here is a sample run:
What is the dimension of matrix? 3
Enter a 3x3 matrix row by row:
0.15 0.875 0.375
0.55 0.005 0.225
0.30 0.12 0.4
The column sorted array is:
0.15 0.005 0.225
0.3 0.12 0.375
0.55 0.875 0.4
This is what I have. I believe it is almost perfect. The sorting method I used I think will sort the column but it may also be sorting the rows. However when I run the program I get this...
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Hmwk3_jrgluck.main(Hmwk3_jrgluck.java:16)
Any ideas/ help..
import java.util.Scanner;
public class sdfjasdf {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is the dimension of your matrix?");
int matrixdim = input.nextInt();
double[][] matrix = new double[matrixdim][matrixdim];
System.out.println("Enter " + matrixdim + " rows, and " + matrixdim
+ " columns.");
Scanner input1 = new Scanner(System.in);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix.length; column++)
matrix[row][column] = input1.nextDouble();
}
System.out.println(sortCol(matrix));
}
public static double sortCol(double[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
double currentMin = matrix[i][0];
int currentMinIndex = i;
for (int j = i; j < matrix.length; j++) {
if (currentMin > matrix[j][0]
|| (currentMin == matrix[j][0] && matrix[currentMinIndex][1] > matrix[j][1])) {
currentMin = matrix[j][0];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
double temp0 = matrix[currentMinIndex][0];
double temp1 = matrix[currentMinIndex][1];
matrix[currentMinIndex][0] = matrix[i][0];
matrix[currentMinIndex][1] = matrix[i][1];
matrix[i][0] = temp0;
matrix[i][1] = temp1;
}
}
return sortCol(matrix);
}
}
I suspect that your locale can require commas instead dots in float number format. Try changing your data to
0,15 0,875 0,375
0,55 0,005 0,225
0,30 0,12 0,4
If that is true but you prefer to (or must) use dots instead of comma you can change locale used in Scanner by invoking
input.useLocale(new Locale("en", "US"));
or change global Locale before creating Scanner object with
Locale.setDefault(new Locale("en", "US"));
Also return type of sortCol should be aether
double[][] in case you want to return sorted copy of array (without changing original one). In that case you will need to first create copy of original array
void in case you want to sort original array (you don't have to return reference to object that you already have since you used it as methods argument)
Right now you are trying to return double by invoking again sortCol(matrix), so it again will try to return sortCol(matrix) (and so on) which will lead to stack overflow.
Good evening all,
I'm trying to write a method that creates and returns a 2D array whose elements in each location are the same as the elements in the mirror image location of the parameter array. Unfortunately, no matter what pair of numbers I enter into the method call I get an "out of bounds" error in my compiler. Below is my program. Tell me where I've gone wrong! Thanks!
public static int[][] transpose(int [][] a) {
int r = a.length;
int c = a[r].length;
int [][] t = new int[c][r];
for(int i = 0; i < r; ++i) {
for(int j = 0; j < c; ++j) {
t[j][i] = a[i][j];
}
}
return t;
}
}
Arrays in java are 0 based, change your assignment to c to :
int c = a[r - 1].length;
#Suraj is correct, however you must assume the 2D array is rectangular, in which case it is sightly more efficient to change line 3 to:
int c = a[0].length;
#Kris answer text is correct however code sample is wrong line.
Note this error is a reproduction of a broken "answer" posted in "Yahoo Answers": http://answers.yahoo.com/question/index?qid=20080121204551AAn62RO
Your problem lies in line two: a[r].length returns the number of columns, but arrays are indexed from 0. You should adjust accordingly:
int r = a.length - 1;