I am having difficulties for writing an algorithm that will create an array of arrays, from a single array of integers.
Say, I have an
int[] intArray = new int[] {1,2,3,4,5};
What I need from it is an array of an arrays that will look like this:
int[][] array = new int[][]{
{-1,2,3,4,5},
{1,-2,3,4,5},
{1,2,-3,4,5},
{1,2,3,-4,5},
{1,2,3,4,-5};
Thank you in advance!!
EDIT:
The following code works for the case if I want to have only one negative value. How about if I would like to have 2,3,4... negative values? Is there a way to make it more dynamic? For example, from {1,2,3,4,5}; to get: {-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-2,-3,4,5},{1,-2,3,-4,5}, {1,-2,3,4,-5}.... or for 3 negative values: {-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5}, {1,-2,-3,4,-5}, {1,2,-3,-4,-5}...etc I hope you get my point! Thanks again guys!!
You could try this:
int l = intArray.length;
int[][] newArray = new int[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
}
}
newArray will have the values you are expecting.
how about
public class x
{
public static int[][] convert(int in[])
{
int s = in.length;
int out[][] = new int[s][s];
for (int i = 0; i < s; ++i) { // row loop
for (int j = 0; j < s; ++j) {
if (i == j)
out[i][j] = -in[j];
else
out[i][j] = in[i];
}
}
return out;
}
public static void print(int in[][])
{
for (int i = 0; i < in.length; ++i) {
String sep = "";
for (int j = 0; j < in[i].length; ++j) {
System.out.print(sep + in[i][j]);
sep = ", ";
}
System.out.println("");
}
}
public static void main(String argv[])
{
int in[] = { 1, 2, 3, 4, 5 };
int out[][];
out = convert(in);
print(out);
}
}
int[] intArray = new int[] {1,2,3,4,5};
int algoIntArray[][] = new int[intArray.length][intArray.length];
for(int i = 0; i < intArray.length; i++){
for (int j = 0; j < algoIntArray[i].length; j++){
if (i == j){
algoIntArray[i][j] = -intArray[j];
} else {
algoIntArray[i][j] = intArray[j];
}
}
}
This code will work for you!
The following code is what I have so far, and nothing is working at all. I am intend to Declares a 7×10 two dimensional array in the main. Pass that array to a method which fills the array with random integers [1,9]. Pass the filled array to a method which prints the two dimensional array with the sum of the row at the end of each row and the sum of the column at the end of each column. Row and column labels must also be printed. Any help will be greatly appreciated.
package twodimensionalarray;
import java.util.Arrays;
import java.util.Random;
/**
*
* #author Kristy7
*/
public class TwoDimensionalArray {
//This method is for generating random integers between 1 and 9.
public static int randInt(){
Random rand = new Random();
int randNum;
randNum = rand.nextInt(9)+1;
return randNum;
}
//This method is for filling a 2D array with random integers
public static int[][] fillArray(int[][] toFill){
int[][] toReturn = new int[0][0];
for(int r = 0; r < toFill.length; r++){
for(int c = 0; c < toFill[0].length; c++){
toReturn[toFill[r]][toFill[c]] = randInt(toFill);
}
}
return toReturn;
}
//This method is for for summing rows and columns, and printing rows, columns, the sum of ruws at each row, and the sum of columns at each column.
public static void summingRC(int[][] toSum){
int[] colSums = new int[0];
for(int i = 0; i < toSum.length; i++){
System.out.print(i);
}
System.out.println();
int sum = 0;
for (int r = 0; r < toSum.length; r++) {
for (int c = 0; c < toSum[r].length; c++) {
sum += toSum[c][r];
colSums[c] += toSum[r][c];
}
System.out.println(sum);
}
System.out.println(colSums);
}
/**
* #param args the command line arguments
*
*/
public static void main(String[] args) {
//Declare a 7x10 2D array
int [][] twoDArray = new int[7][10];
//call fillArray method.
int[][] fillingArray = fillArray(twoDArray);
//call SummingRC method
summingRC(fillingArray);
}
}
There's a lot of issues with this code as you are probably aware. Most of them stem from incorrectly instantiating and accessing arrays. I fixed it up:
public static int randInt(){
Random rand = new Random();
int randNum;
randNum = rand.nextInt(9)+1;
return randNum;
}
//This method is for filling a 2D array with random integers
public static int[][] fillArray(int[][] toFill){
int[][] toReturn = new int[toFill.length][toFill[0].length];
for(int r = 0; r < toFill.length; r++){
for(int c = 0; c < toFill[0].length; c++){
toReturn[r][c] = randInt();
}
}
return toReturn;
}
//This method is for for summing rows and columns, and printing rows, columns, the sum of ruws at each row, and the sum of columns at each column.
public static void summingRC(int[][] toSum){
int[] colSum = new int[toSum[0].length];
int[] rowSum = new int[toSum.length];
for(int i = 0; i < toSum.length; i++){
for(int j = 0; j < toSum[i].length; j++){
colSum[j] += toSum[i][j];
rowSum[i] += toSum[i][j];
}
}
System.out.println("Matrix: ");
print2dArray(toSum);
System.out.println("Col sum:");
printArray(colSum);
System.out.println("Row sum:");
printArray(rowSum);
}
/**
* #param args the command line arguments
*
*/
public static void main(String[] args) {
//Declare a 7x10 2D array
int [][] twoDArray = new int[7][10];
//call fillArray method.
int[][] fillingArray = fillArray(twoDArray);
//call SummingRC method
summingRC(fillingArray);
}
public static void print2dArray(int[][] arr){
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void printArray(int arr[]){
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
There's a lot of places where you are instantiating an array with 0 length. Which is basically just a useless array at that point because you can't put any values into it. Ex:
int[] colSums = new int[0];
If you are using Java8. You can do this elegantly by Stream.
Here is the code:
import java.util.Arrays;
import java.util.stream.IntStream;
public class Q47129466 {
public static void main(String[] args) {
int[][] mat = get(5, 5);
System.out.println(Arrays.deepToString(mat));
System.out.println(Arrays.toString(rowSum(mat)));
System.out.println(Arrays.toString(columnSum(mat)));
}
public static int[][] get(int width, int height) {
return IntStream.range(0, height)
.mapToObj(c -> IntStream.range(0, width)
.map(r -> (int) (9 * Math.random() + 1))
.toArray())
.toArray(int[][]::new);
}
public static int[] rowSum(int[][] matrix) {
return Arrays.stream(matrix).mapToInt(row -> IntStream.of(row).sum()).toArray();
}
public static int[] columnSum(int[][] matrix) {
return Arrays.stream(matrix).reduce((a, b) -> add(a, b)).orElse(new int[0]);
}
public static int[] add(int[] a, int[] b) {
int[] sum = new int[Math.max(a.length, b.length)];
for (int i = 0; i < sum.length; i++) {
sum[i] = (i < a.length ? a[i] : 0) + (i < b.length ? b[i] : 0);
}
return sum;
}
}
I think the problem in your code is that you initialized the two dim array in the line int[][] toReturn = new int[0][0];. Here you give the array size and dimension, then in the loop you are trying to populate the array based on the toFill length. Because arrays are fixed in size and do not expand dynamically you can not do this.
Below is the same style code which gots an arrayindexoutofboundsexception. What I suggest to you is that you give the length and dimensions to the method and then initialize the array with these sizes.
The code below is also getting an exception because of the same problem you did which is initializing the array to a size then trying to add elements to it.
public static void main(String[] args) {
int [] [] x =new int[0][0];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
x[i][j]=i+j;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(x[i][j]);
}
}
}
I'm stuck..... i have been trying to use Arrays in methods to count the number of numbers divisible by 10 from the range 1-100.
here's my code:
import java.util.Scanner;
import java.util.Random;
public class Journal5a {
// METHOD
public int[] creatArray (int size)
{
int[] array = new int[size];
Random r = new Random();
for (int i = 0; i < array.length; i++)
array[i] = r.nextInt(100);
return array;
}
public int[] DivByTen()
{
int x = 0;
int y[] = this.creatArray(1);
for (int i = 0; i < y.length; i++)
if (y[i] % 10 == 0)
{
x++;
}
return x;
}
public int[] printArray ()
{
int[] myArray = this.creatArray(1);
for (int i = 0; i<myArray.length; i++)
System.out.println(myArray[i]);
return myArray;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Journal5a j5a = new Journal5a();
j5a.DivByTen();
}
So my output would be :
there is 10 numbers divisible by 10
Another problem is the x used in the method DivByTen isn't being returned.
Your createArray() method fills the array with random numbers from 0-99, so it is not clear how much numbers are dividable by 10.
for(int i = 0; i < size; i++) {
array[i] = i;
}
will create an array with values from 0 to size - 1.
The second problem is that your return type is int[] instead of int
First, create and fill the array. For the range 1 to 100 you would need to pass in 100 and either start with i at 1 (or add 1 to i when you initialize the array);
private static int[] creatArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
return arr;
}
Next, count the multiples of some multiple. Something like,
private static int countMultiples(int[] arr, int multiple) {
int count = 0;
for (int val : arr) {
if (val != 0 && val % multiple == 0) {
count++;
}
}
return count;
}
Finally, call the above methods and output the result
public static void main(String[] args) {
final int multiple = 10;
int count = countMultiples(creatArray(100), multiple);
System.out.printf("There are %d numbers divisible by %d.", count, multiple);
}
Output is
There are 10 numbers divisible by 10.
Everything with my code seems to work correctly, whenever the boolean method returns true. However, when trying to test false, after the user enters 10 numbers I receive the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at FunArrays.main(FunArrays.java:15
What am I missing or overlooking with my code?
Here is my code:
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Please enter ten numbers....");
int [] userArray = new int [9];
for(int b = 0; b < 10 ; b++){
userArray [b] = input.nextInt();
}
boolean lucky = isLucky(userArray);
if (lucky){
sum(userArray);
} else
sumOfEvens(userArray);
}
public static boolean isLucky(int [] numbers){
for (int i = 0; i <= numbers.length; i++){
if (numbers[i]== 7 || numbers[i] == 13 || numbers[i] == 18){
return true;
}
}
return false;
}
public static void sum(int [] numbers){
int sum = 0;
for (int x = 0; x <= numbers.length -1; x++){
sum += numbers[x];
}
System.out.println(sum);
}
public static void sumOfEvens(int [] numbers){
int evens = 0;
for (int y = 0; y <= numbers.length -1; y++){
if (numbers[y] % 2 == 0){
evens += numbers[y];
}
}
System.out.println(evens);
}
}
You are entering 10 numbers but your array has only 9 spots. Change it to
int [] userArray = new int [10];
int [] userArray = new int [9];
for(int b = 0; b < 10 ; b++){
userArray [b] = input.nextInt();
}
Your array size is 9 (from index 0 to index 8) and your loop increment b from 0 to 9 (10 cases)
In this case b should be less than 9 in your loop.
So you could replace by this code:
int maxInput = 9;
int [] userArray = new int [maxInput];
for(int b = 0; b < maxInput ; b++){
userArray [b] = input.nextInt();
}
You should declare a size 10 array, since you are accepting 10 values from the user.
int [] userArray = new int [9];
Here is a good read on Arrays: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html
You're trying to store 10 numbers in an array of length 9.
Use int[] userArray = new int[10];
Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.