I have recently started to learn java. I have a task, where I have to print a number grid with specific values in it.
Heres the code:
public static void main(String[] args) {
int array[][] = {{1, 2, 3, 5, 7},
{10, 11, 12, 14, 16},
{19, 20, 21, 23, 25},
{28, 29, 30, 32, 34},
{37, 38, 39, 41, 43},
{46, 47, 48, 50, 52}};
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("");
}
}
}
Now it works perfectly fine, but ideally I could only declare values of the first row and use for loop with if statement to accomplish the same thing, yet I struggle to figure out code for that.
The difference between the two elements in a column is 9: a[i][j] = a[i-1][j] + 9, thus the code may be modified as:
public static void main(String args[]) {
int array[][] = new int[6][5];
// initialize the first row
array[0] = new int[] {1, 2, 3, 5, 7};
// print the first row
System.out.println(Arrays.toString(array[0]));
for (int i = 1; i < array.length; i++) {
// populate current row incrementing each element by 9
for (int j = 0; j < array[i].length; j++) {
array[i][j] = array[i - 1][j] + 9;
}
System.out.println(Arrays.toString(array[i]));
}
}
Output:
[1, 2, 3, 5, 7]
[10, 11, 12, 14, 16]
[19, 20, 21, 23, 25]
[28, 29, 30, 32, 34]
[37, 38, 39, 41, 43]
[46, 47, 48, 50, 52]
Update
It would be more interesting task to generate the sequence starting from 1.
Inside the row the differences between two adjacent elements change like 1, 1, 2, 2, 3, and 3 is the difference between the last element of the previous row and the first element in the next row.
int x = 1;
for (int i = 1; i < 7; i++) {
for (int j = 1; j < 6; j++) {
System.out.print(x + " ");
x += j / 2 + j % 2;
}
System.out.println();
}
Related
I want to print out an increasing number of elements in my array per line but I'm not sure how I could do it.
public static void main(String[] args) {
int[] x = new int[21];
for (int i = 0; i < x.length; i++) {
x[i] = i + 1;
}
System.out.println(Arrays.toString(x));
}
I would like my output to look like:
[1]
[2, 3]
[4, 5, 6]
etc...
instead of what I get right now which is
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
I'm really new to java so any tips would really be appreciated, thanks.
Add this below your code.
for (int i = 0, ctr = 0; i < x.length; ctr++) {
System.out.print("[ ");
for (int j = 0; j <= ctr; i++) {
System.out.print(x[i]);
j++;
if (j <= ctr) {
System.out.print(" ,");
}
}
System.out.println(" ]");
}
This method does not require storage
int start = 1;
int count = 1;
int outer = 6;
for (int y = 0; y < outer; y++) {
System.out.print ("[");
int x = start;
for (; x < start + count; x++) {
System.out.print (x);
if (x < start + count - 1)
System.out.print(",");
}
System.out.println ("]");
count++;
start = x;
}
result
[1]
[2,3]
[4,5,6]
[7,8,9,10]
[11,12,13,14,15]
[16,17,18,19,20,21]
You can use this code
int[] x = new int[21];
for (int i = 0; i < x.length; i++) {
x[i] = i + 1;
}
int start = 0, len = 1;
while(start + len <= x.length) {
int[] newArray = Arrays.copyOfRange(x, start, start + len);
System.out.println(Arrays.toString(newArray));
start += len;
len++;
}
Using two loops you can achieve the result, the outer loop will create an empty array with each iteration and the inner one will populate it with numbers. Also using a third variable to keep track of the last number generated.
public static void main(String[] args) {
int n = 21;
int lastNumber = 0;
int x[] = null;
for(int j = 0; j< n; j++) {
x = new int[j];
for (int i = 0, k = lastNumber; i< j; i++,k++) {
x[i] = k + 1;
}
if(x.length != 0){
lastNumber = x[x.length - 1];
System.out.println(Arrays.toString(x));
}
}
}
Output:
[1]
[2, 3]
[4, 5, 6]
[7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20, 21]
I'm struggling with the number of insertion sort key comparison and swap count..
I have this method that counts and prints out the key comparison at the end
public static void insertionSort(int[] array) {
int n = array.length;
int cm = 0;
int sw = 0;
for (int pass = 0; pass < array.length; pass++) {
// figure out what should go into a[pass]
int min = pass;
for (int j = pass + 1; j < array.length; j++) {
if (smaller(array, j, min)) {
cm++;
min = j;
}
}
swap(array, pass, min);
sw++;
}
System.out.print("Insertion sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}
private static void swap(int[] a, int i, int j) {
if (i != j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
private static boolean smaller(int[] a, int i, int j) {
//another suggestion came up to call a count variable here because a false comparison could still count as a comparison
count++;
if (a[i] < a[j]) {
return true;
}
return false;
}
With this test array
int[] test = {13, 12, 5, 6, 11};
I should get 7 comparisons and 4 swaps, but I'm getting 5 comparisons and 5 swaps.
With another array from 0 to 31 consequently (testing for the best case),
I get 0 comparison and 32 swaps.
Updating for an answer.
This works for the comparison count but still working on the swap count.
private static int COMPCOUNT = 0;
public static void main(String[] args) {
//best case for insertion sort is increasing order
int[] bestCase = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
//the worst case for insertion sort is decreasing order;
int[] worstCase = {31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int[] randomArray = new int[32];
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = genarateRandom(32);
}
}
public static int genarateRandom(int bound) {
Random random = new Random();
int rand = random.nextInt(bound);
return rand;
}
private static boolean smaller(int[] a, int i, int j) {
if (a[i] < a[j]) {
COMPCOUNT++;
return true;
}
return false;
}
public static void insertionSort(int[] arr)
{
COMPCOUNT=0;
int temp;
for (int i = 1; i < arr.length; i++) {
for(int j = i ; j > 0 ; j--){
//use boolean function to check A[i] < A[j]
if(smaller(arr, j, j-1)){
//swap
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
//print out the array
System.out.print("Insertion sort: ");
for (int c = 0; c < arr.length; c++) {
System.out.print(arr[c] + " ");
}
//print out the number of comparison
System.out.println("- " + COMPCOUNT + " comparisons");
}
I have been struggling with the following problem:
I am trying to print the below output using nested for loops and two dimensional arrays.
int[][] outputArray = {
{1,2,3,4,5,6,7,8,9,10},
{11,12,13,14,15,16,17,18,19,20},
{21,22,23,24,25,26,27,28,29,30},
{31,32,33,34,35,36,37,38,39,40},
{41,42,43,44,45,46,47,48,49,50},
{51,52,53,54,55,56,57,58,59,60},
{61,62,63,64,65,66,67,68,69,70},
{71,72,73,74,75,76,77,78,79,80}
};
Here is my code for the array which seems to be correct:
public ExerciseTwo() {
myArray1 = new int[8][10];
for (int i = 0; i < myArray1.length; i++) {
for (int j = 0; j < myArray1[i].length; j++) {
myArray1[i][j] = (i * myArray1[i].length) + j + 1;
}// end inner loop
}// end outer loop
}// end constructor
Now I am having several issues with the nested loop below:
public void printArrayStatement() {
System.out.print("int[][] outputArray = {");
for (int i = 0; i < myArray1.length; i++) {
if (myArray1.length >= 1)
// I am trying to remove the initial comma here but my
// logic is wrong. It is printing 1 first on each line.
System.out.print("\n" + "{" + myArray1[0][0]);
for (int j = 0; j < myArray1[i].length; j++) {
System.out.print("," + myArray1[i][j]);
}
}
System.out.println("};");
}// end method
I also can't seem to figure out how to get the }, at the end of each line. I think an if statement is necessary but I can't figure out the code!
The following code is working as required:
System.out.println("int[][] outputArray = {"); //int[][] outputArray = {
for (int i = 0; i < myArray1.length; i++) {
System.out.print("{"); //{
int j;
for (j = 0; j < myArray1[i].length - 1; j++) {
//1, 2,...9, i.e not last one.
System.out.print(myArray1[i][j] + ", "); //1, 2,...9, then terminate
// Not used if to check for last one
// because it would increase time complexity
}
System.out.print(myArray1[i][j] + "}"); //10}
if (i != myArray1.length - 1) {
System.out.println(", "); //, only if it is not last one
}
}
System.out.println("\n}");
Output:
int[][] outputArray = {
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
{21, 22, 23, 24, 25, 26, 27, 28, 29, 30},
{31, 32, 33, 34, 35, 36, 37, 38, 39, 40},
{41, 42, 43, 44, 45, 46, 47, 48, 49, 50},
{51, 52, 53, 54, 55, 56, 57, 58, 59, 60},
{61, 62, 63, 64, 65, 66, 67, 68, 69, 70},
{71, 72, 73, 74, 75, 76, 77, 78, 79, 80}
}
It looks like you're creating a complex bit of code that can be solved simply... print the comma if you're not at the end, and don't print it if you're at the end
for (int i = 0; i < myArray1.length; i++) {
for (int j = 0; j < myArray1[i].length; j++) {
// here print out myArray1[i][j]
if (j != myArray1[i].length - 1) {
// here print out comma if j is not == myArray1[i].length - 1
}
}
System.out.println();
}
Another option is to use java.util.Arrays.toString(...)
I'm not sure why you are trying to print the { and } symbols. Are you sure that you need them?
Your inner loop is starting from zero:
for (int j = 0; j < myArray1[i].length; j++) {
You should have
for (int j = 1; j < myArray1[i].length; j++) {
As for the closing brace, just print it after the inner loop, but still inside the outer loop:
System.out.println("}");
}
System.out.println("};");
After the inner loop we print '}' and we check to see if it just printed the last line, if not then we need to print comma also.
Here is the code:
for (int i = 0; i < myArray1.length; i++) {
if (myArray1.length >= 1)
System.out.print("\n" + "{" + myArray1[0][0]);
for (int j = 0; j < myArray1[i].length; j++) {
System.out.print("," + myArray1[i][j]);
}
// Print ',' if we are not at the end.
System.out.print("}"+(i==myArray1.length-1?"":","));
}
System.out.println("\n};");
I have to output the array with a maximum of 4 array values per line, but I can't figure out how to convert it to a 2 dimensional array. After the dashes is where I am having trouble. If I don't output it as a 2D array, how else would I restrict it to have only 4 values per line?
public class arrayExampleB{
public static void main(String[] args){
int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};
System.out.print("Pre-Swapped Array Set (linear): {");
for(int i=0; i<=x.length-1; i++){
if(i<x.length-1){
System.out.print(x[i] + ", ");
}
else{System.out.print(x[i]);}
}
System.out.print("}");
int y = x.length-1;
int temp = x[y];
x[y] = x[1];
x[1] = temp;
int z = x.length-2;
int temp2 = x[z];
x[z] = x[0];
x[0] = temp2;
System.out.print("\nPost-Swapped Array Set (linear): {");
for(int i=0; i<=x.length-1; i++){
if(i<x.length-1){
System.out.print(x[i] + ", ");
}
else{System.out.print(x[i]);}
}
System.out.print("}");
//-------------------------------------------------------------
int d = (x.length / 4) + (x.length % 4);
int i = 0;
int j = 0;
int[][] t = new int[i][j];
System.out.print("\nPre-Swapped Array Set (2D): {");
for(i=0; i <= 4; i++){
for(j=0; j < d; j++){
System.out.print(t[i][j] + " ");
}
System.out.println();
}
System.out.print("}");
}
}
To output a 1d array as 2d with a max of 4 values on a line, use this code:
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
if ((i+1) % 4 == 0)
System.out.println();
}
int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};
int[][] t = new int[4][4];
// populate 2D
int k = 0
for(i=0; i <= t.length; i++){
for(j=0; j < t[i].length; j++){
t[i][j] = x[k];
k++l
}
}
// print
for(i=0; i <= t.length; i++){
System.out.print("{");
for(j=0; j < t[i].length; j++){
System.out.print(t[i][j]);
}
System.out.println("}");
}
Without taking too close a look on your code: To output a one dimensional array on several lines on the console consider this:
int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};
for(int i = 0; i < x.length; i++)
{
System.out.print(x[i] + ' ');
if( (i+1) % 4 == 0)
System.out.print('\n');
}
What I'm trying to do is print the largest number within a two dimensional array and it's index location. I'm able to find the largest number, but I can't seem to figure out how to print it's index location. Anyway, here's what I have so far:
public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
double max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
}
System.out.println(max);
System.out.println(i + j); //No idea what I should be doing here, just trying out everything I can think of
Right now, you should consistently get 2 * arr.length as the final value. That isn't what you are probably looking for. It looks like you want to know the coordinates for the max value. To do this, you'll need to cache the values of the indexes and then use them later:
public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int tmpI = 0;
int tmpJ = 0;
double max = arr[0][0];
// there are some changes here. in addition to the caching
for (int i = 0; i < arr.length; i++) {
int[] inner = arr[i];
// caches inner variable so that it does not have to be looked up
// as often, and it also tests based on the inner loop's length in
// case the inner loop has a different length from the outer loop.
for (int j = 0; j < inner.length; j++) {
if (inner[j] > max) {
max = inner[j];
// store the coordinates of max
tmpI = i; tmpJ = j;
}
}
}
System.out.println(max);
// convert to string before outputting:
System.out.println("The (x,y) is: ("+tmpI+","+tmpJ+")");
Be careful with your array dimensions! The second for-statement most of you have is wrong. It should go to up to arr[i].length:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
tmpI = i; tmpJ = j;
}
}
}
Store i, j whenever you update max.
This would be if you wanted a single index into a flatten array:
public static void main (String[] args) throws java.lang.Exception
{
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int[] flattened = new int[6*3]; // based off above
int maxIndex = 0;
double max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
flattened[i + j] = arr[i][j];
if (arr[i][j] > max) {
max = arr[i][j];
maxIndex = i+j;
}
}
}
System.out.println(max);
System.out.println(flattened [maxIndex]);
}
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int max = arr[0][0];
int maxI = 0, maxJ = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
maxI = i;
maxJ = j;
}
}
}
System.out.println(max);
System.out.println(maxI + "," + maxJ);
You've got a two-dimensional array, therefore you need to know both indexes. Adding them together won't do because you lose which-is-which. How about this:
System.out.println("[" + i + "][" + j + "]");
//C++ code
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> b;
vector<int> c;
int Func(int a[][10],int n)
{
int max;
max=a[0][0];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
b.push_back(i);
c.push_back(j);
}
}
}
b.push_back(0);
c.push_back(0);
return max;
}
void display(int a[][10],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
}
int main()
{
int a[10][10],n;
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<endl;
display(a,n);
cout<<endl;
cout<<Func(a,n)<<" is the greatest "<<endl;
if(b.size()==1&&c.size()==1)
{
cout<<"Location is (1,1)"<<endl;
}
else
{
b.erase(b.end() - 1);
c.erase(c.end() - 1);
cout<<"Location is "<<"("<<b.back()+1<<","<<c.back()+1<<")"<<endl;
}
return 0;
}
You're just adding the indices i and j together and then printing it to the screen. Since you're running throug the entire loop it's just going to be equal to 2*arr.length-2. What you need to do is store the values of i and j when you encounter a new max value.
For example:
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int max = arr[0][0]; //dunno why you made it double when you're dealing with integers
int max_row=0;
int max_column=0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
max_row=i;
max_column=j;
}
}
System.out.println("The max is: "+max+" at index ["+max_row+"]["+max_column+"]");
Don't sure that you implement effective algorithm, but why you just don't save indices i,j in another variables when you set max.
This is very simple.
if (arr[i][j] > max) {
max = arr[i][j];
maxX = i;
maxY = j;
}
FYI If you want look at "insertion sorting" algorithms if you want better implementation.