creating and printing a triangular array in java - java

here's my code:
public static int[][] arraytriangle(int lines){
int[][] tri = new int[lines][];
int c = 1; // incremented number to use as filler
for (int i = 0; i < lines; i++){
for (int j = 0; j <= i; j++){
tri[i] = new int[i+1]; // defines number of columns
tri[i][j] = c;
System.out.print(c + " ");
c++; // increment counter
}
System.out.println(); // making new line
}
System.out.println(Arrays.deepToString(tri));
return tri;
arraytriangle(3) gives:
1
2 3
4 5 6
[[1], [0, 3], [0, 0, 6]]
So the program is printing correctly (the 1,2,3...), but the matrix values are not correct when I use deepToString. What gives?

This assignment
tri[i] = new int[i+1];
has to happen inside the outer loop but outside the inner loop. Currently, your inner loop keeps re-assigning tri[i], so only the last item remains assigned for deepToString.

Related

Why is there a difference between two similar implementations of a 'for' loop?

I'm trying to write an insertion sort method, and I have managed to finish it, but I don't understand why my first version cannot work correctly.
Here's my first attempt:
public static void insertionSort(int[] list) {
for (int i = 1; i < list.length; i++) {
int current = list[i];
for (int k = i - 1; k >= 0 && current < list[k]; k--) {
list[i] = list[k];
list[k] = current;
}
}
}
public static void main(String[] args) {
int[] list = {8, 22, 90, 10};
insertionSort(list);
}
My output for the above code is: 8, 10, 10, 22
But the answer would be correct if the inside for-loop, at line 5, is changed from: list[i] = list[k]; to: list[k + 1] = list[k];
To my understanding, k + 1 is equal to i, but it must be different in loop counting and I can't figure out how. I have tried many sets of input, and only values that lie between the range of the 2 first indexes (in this case 8 and 22) would be incorrect.
k + 1 is equal to i, but only in the first iteration of the inner for loop. int k = i - 1 is only run once per iteration of the outer for loop.
In the second iteration of the inner for loop, k is decremented but i is not. Therefore, k + 1 and i are not interchangeable inside the inner for loop.
// second iteration of the outer for loop, second iteration of the inner for loop:
list[i] = list[k]; // means "list[2] = list[0]
// whereas
list[k + 1] = list[k]; // means "list[1] = list[0]"

Java/Replacing elements in a simple array with a while loop

I have two Arrays (not ArrayLists):
A: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 0, 0, 0, 0, 0];
B: [50, 100, 150, 200, 250];
I need to create a while loop that inserts the values from array B to array A.
For example, If position/index K = 5, then the result should be:
A: [0, 5, 10, 15, 20, 25, 50, 100, 150, 200, 250, 30, 35, 40, 45];
Such that the contents of B[] get inserted in-place into A[], at index K. This pushes existing contents to the right, and deletes any content that is pushed outside the bounds of the array.
Then I need to use a do while loop to print out the new A values.
I need to do all that using 2 loops: 1 while loop for replacing and a do While loop for printing. Even if that is not necessary, those are the conditions given to me.
In the context of my question, all that is mentioned in the assignment is:
Nest all the elements of Array B in the Array A according to the element with an index K.
Sorry if I am being unclear, I began learning programming 5 days ago and I am not that familiar as to what details I should mention, maybe the code that I have wrote up until now can help to bring some more context (The first while loop is where I try to do what I am asking in this thread):
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Rainers {
public static void main(String[] args) {
int A[] = new int[15];
int B[] = new int[5];
for (int i = 10; i < A.length; i++) {
A[i] = 0;
}
int K;
Scanner sc = new Scanner(System.in);
System.out.println("Name Lastname ID1 ID2");
System.out.print("K=");
if (sc.hasNextInt())
K = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
sc.close();
if (K >= 0 && K <= 9) {
for (int k = 0; k <= 9; ++k) {
A[k] = k * K;
}
for (int k = 0; k <= 4; ++k) {
B[k] = 10 * (k + 1) * K;
}
}
else if (K < 0 || K > 9) {
K = 5;
Random diapazons = new Random();
for (int c = 0; c < 10; ++c) {
A[c] = diapazons.nextInt(50);
}
for (int c = 0; c < 5; ++c) {
B[c] = diapazons.nextInt(100 - 50 + 1) + 50;
}
}
sc.close();
System.out.println("A: " + Arrays.toString(A));
System.out.println("B: " + Arrays.toString(B));
int count = K;
while (count > K && count <= A.length) {
int x = 0;
x++;
A[K] = B[x];
count++;
}
System.out.println("A: " + Arrays.toString(A));
}
}
Thank you in advance for your time, I really appreciate it.
I'm also a noobie in stack overflow .
First of all I suggest you to use ArrayList as they are more flexible once learnt.
It's not a clean or optimised code but,
Try to add the following algorithm into your code .
I am a noobie trying to be active and learn and participate in stack overflow. This code might have blunder bugs in it. But I hope I helped explain the approach of the alogirthm.
void mergep(ArrayList<Integer> a[], ArrayList<Integer> b[], ArrayList<Integer> c)
{
int acursor = c;
int bcursor = 0;
while(acursor<= b.length())
{
int shiftcursor = b.length()-1;
while(shiftcursor>acursor)
{
a[shiftcursor+1] = a[shiftcursor];
shiftcursor--;//This shifts all the existing entries to the right
}
a[acursor] = b[bcursor];
bcursor++;
acursor++;
}
}
Your code
int count = K;
while (count > K && count <= A.length) {
int x = 0;
x++;
A[K] = B[x];
count++;
}
has a few problems:
It does nothing because you set count = K and then give the condition count > K.
The condition count <= A.length will cause a AIOOBE because the last element is at A.length - 1.
You want to start accessing B from the beginning, but you increment its value before the first access to it.
Since you are iterating over B as well, you will need a stop condition in the loop to not attempt to access indexes greater than it has.
You are putting values of B into A, but at the same time you are losing the ones in A because they are overridden. You need to store the value at the right place before you overwrite it.
Once you fix these mistakes you will solve your problem. You can edit your question with your attempt at solving these.
The elements in A have to be moved before the elements from B can be inserted. Begin by shifting all values from the back of the array to avoid losing any elements. The shift of the elements should look as follows when moving the elements one step to the right:
1. [5, 10, 15]
2. [5, 10, 15] 15
3. [5, 10, 10] 15
4. [5, 5, 10] 15
5. [2, 5, 10] 15
The element 15 will be dropped from the array, but 5 and 10 will still be kept in the array. 5's old location can then be assigned a new value, e.g. 2.
Iterate from the last index of the array and move the elements so that B's elements can fit. But instead of one step as above, move the elements the length of B. Stop iterating when index K is reached, since no more elements will be inserted or moved. The below java code moves the elements of array A and assigns the values from B. The first if statement avoids indexing out of bounds. The second if statement checks if the elements from B should be inserted into A.
int idxA = A.length - 1;
int idxB = B.length - 1;
while(idxA >= K){
if (idxA + B.length < A.length)
A[idxA + B.length] = A[idxA];
if (idxA < B.length + K){
A[idxA] = B[idxB];
idxB--;
}
idxA--;
}
If you are unsure about how the code works, use pen and paper to write the current state of each array at each step in the code.
I modified the code as per output.
// while (count > K && count <= A.length) {
// int x = 0;
// x++;
// A[K] = B[x];
// count++;
//
// }
Change to new code
System.arraycopy(A, K, A, K + B.length, B.length);
System.arraycopy(B, 0, A, K, B.length);

Understanding what java code prints

Hi guys I am fairly new to this and have a question about this code. I am unsure about how the output is what it is so if someone could explain it to a beginner I'd be grateful! This is the code:
public class NewClass{
public static int[] first(int[] a) { // Array {1,2,3} is passed as an argument
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[a.length - 1 - i];
return b;
}
public static void second(int[] a) { // Use more descriptive names for you methods. If its aim is to reverse the array than call it reverseArray or something alike.
for (int i = 0; i < a.length/2; i++) { // a.length = 3, a.length/2 = 1; So this loop will run only once
int temp = a[i]; // temp = 4
a[i] = a[a.length - 1 - i]; // a[0] = a[3 - 1 - 0] (a[2]) equals a[0] = 6
a[a.length - 1 - i] = temp; // a[2] = temp equals a[2] = 4
} // Array has become {6,5,4} (So it's been reversed.)
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}}; // Array of two elements, both elements refering to an other array with three elements
System.out.println(matrix.length); // This will print 2. It is a two dimensional array.
first(matrix[0]); // Calling the first method and passing the {1,2,3} array as argument. It does stuff to a copy of the array (int[] b), but the returned value is never used. Array {1,2,3} is untouched.
second(matrix[1]); // Same as with the first method
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) // You should use { }. It will make the code easier to read. Only line 25 is executed inside this nested loop
System.out.print(matrix[i][j]); // This will run 6 times (2 (outer loop) x 3 (nested loop)). It will print matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]. Respectively 123 (next line) 456
System.out.println();
}
}
}
It outputs 2, then 1,2,3 and finally 6,5,4.
In your first function you are creating a new array. This array is returned however the value is never copied into the original. Therefore when printing the matrix the first loop will stay as 1, 2, 3. If you want this to change switch the line:
first(matrix[0]);
To:
matrix[0] = first(matrix[0]);
The second function takes the original array and loops once (since a.length is 3 and 3 / 2 = 1). During this loop it converts a[0] to a[a.length - 1 - i] or a[3 - 1 - 0]. It then switches a[a.length - 1 - i] or a[2] to temp which is a[0]. This will switch the first and last element in the array which are 6 and 4.
At first, your code is quite messy. Try to use the proper indentation (four spaces for each block). It makes the code easier to read (and you might have figured out the answer yourself).
public class NewClass{
public static int[] first(int[] a) { // Array {1,2,3} is passed as an argument
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[a.length - 1 - i];
return b;
}
public static void second(int[] a) { // Use more descriptive names for you methods. If its aim is to reverse the array than call it reverseArray or something alike.
for (int i = 0; i < a.length/2; i++) { // a.length = 3, a.length/2 = 1; So this loop will run only once
int temp = a[i]; // temp = 4
a[i] = a[a.length - 1 - i]; // a[0] = a[3 - 1 - 0] (a[2]) equals a[0] = 6
a[a.length - 1 - i] = temp; // a[2] = temp equals a[2] = 4
} // Array has become {6,5,4} (So it's been reversed.)
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6}}; // Array of two elements, both elements refering to an other array with three elements
System.out.println(matrix.length); // This will print 2. It is a two dimensional array.
first(matrix[0]); // Calling the first method and passing the {1,2,3} array as argument. It does stuff to a copy of the array (int[] b), but the returned value is never used. Array {1,2,3} is untouched.
second(matrix[1]); // Same as with the first method
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) // You should use { }. It will make the code easier to read. Only line 25 is executed inside this nested loop
System.out.print(matrix[i][j]); // This will run 6 times (2 (outer loop) x 3 (nested loop)). It will print matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]. Respectively 123 (next line) 456
System.out.println();
}
}
}
It outputs 2, then 1,2,3 and finally 6,5,4.

What's the output of this code written in java?

int arr[ ] = new int[3];
for (int i = 0; i < 3; i++) {
arr[i] = i;
}
int res = arr[0] + arr[2];
System.out.println(res);
I'm a beginner in java, as you can see, and I'm not quite sure what's the output of this. Can someone answer and explain along the way?
//if you're using Eclipse, press ctrl-shift-f to "beautify" your code and make it easier to read
int arr[] = new int[3]; //create a new array containing 3 elements
for (int i = 0; i < 3; i++) {
arr[i] = i;//assign each successive value of i to an entry in the array
}
int res = arr[0] + arr[2];//add the 0th element value to the 2nd element value, save in res
System.out.println(res);//print res, which is == 0 + 2
basically what you are doing here is
int arr[ ] = new int[3];
for (int i = 0; i < 3; i++) {
arr[i] = i; // you are adding elements on array location
}
int res = arr[0] + arr[2];
System.out.println(res);
when first time loop execute i equals to 0, on location 0 you are assigning 0 there and for 1,2 the same process is being applied. On line int res = arr[0] + arr[2]; you are adding values of location 0 and 2 which are 0and 2 so the output is 2 when you add 0+2 = 2 in basic mathematics
On the first line, you are creating a new array of integers. The array has the elements arr[0], arr[1], and arr[2].
On the next three lines, is your for loop. As you have written in the loop, it will start from i=0 and will continue running while i < 3. Therefore, i will be 0, 1, and 2. In the loop itself, you are saying:
arr[0] = 0, arr[1] = 1, arr[2] = 2.
On the last two lines, you have two statements. The first expression creates an integer called res. Then you are saying res = arr[0] + arr[2]. But as we just saw, in the for loop you made arr[0] = 0 and arr[2] = 2. Therefore, res = 0 + 2 = 2.
On the last line you are just printing the result in the console.

Iterating over a sorted array and storing the count of distinct integers

Can somebody PLEASE answer my specific question, I cannot use material not covered in class yet and must do it this way.
I'm trying to iterate over a sorted array and if the previous number == the current number it stores the count in possiton n of a new array; when the previous number != the current number, it then moves to n+1 on the new array and starts counting again.
I'm debugging it now but having trouble working out what it isn't work. Any help is much appreciated.
// Get the count of instances.
int[] countOfNumbers = new int[50]; // Array to store count
int sizeOfArray = 0; // Last position of array filled
int instanceCounter = 1; // Counts number of instances
int previousNumber = 0; // Number stored at [k-1]
for (int k=1; k < finalArrayOfNumbers.length; k++) {
previousNumber = finalArrayOfNumbers[k-0];
if (previousNumber == finalArrayOfNumbers[k]) {
instanceCounter++;
countOfNumbers[sizeOfArray] = instanceCounter;
}
instanceCounter = 1;
sizeOfArray++;
countOfNumbers[sizeOfArray] = instanceCounter;
Don't worry about mapping or anything, I just need to know how If I have an array of:
[20, 20, 40, 40, 50]
I can get back
[2, 2, 1]
There's lots of neat tools in the Java API so you can avoid doing a lot of this yourself:
List<Integer> list = Arrays.asList(20, 20, 40, 40, 50);
Map<Integer, Integer> freq = new LinkedHashMap<>();
for (int i: list) {
freq.put(i, Collections.frequency(list, i));
}
System.out.println(freq.values());
That'll print [2, 2, 1] like you wanted.
Alternatively if you'd like a list of only the distinct values in the list, you can use an implementation of Set.
But since you're restricted because this is a class assignment, you could do something like this instead:
int[] a = { 20, 20, 40, 40, 50 };
int[] freq = new int[a.length];
// count frequencies
for (int i = 1, j = 0, count = 1; i <= a.length; i++, count++) {
if (i == a.length || a[i] != a[i - 1]) {
freq[j++] = count;
count = 0;
}
}
// print
for (int i = 0; i < freq.length && freq[i] != 0; i++) {
System.out.println(freq[i]);
}
And the output is still the same.
I put comments in the two places you were off, here's your fixed code.
for (int k = 1; k < finalArrayOfNumbers.length; k++) {
previousNumber = finalArrayOfNumbers[k - 1]; // changed 0 to 1
if (previousNumber == finalArrayOfNumbers[k]) {
instanceCounter++;
countOfNumbers[sizeOfArray] = instanceCounter;
} else { // put this last bit in an else block
instanceCounter = 1;
sizeOfArray++;
countOfNumbers[sizeOfArray] = instanceCounter;
}
}
I'm debugging it now but having trouble working out what it isn't work. Any help is much appreciated.
Here's a clue for you:
previousNumber = finalArrayOfNumbers[k-0];
if (previousNumber == finalArrayOfNumbers[k]) {
Clue: 'k - 0' has the same value as 'k' in the above.
Clue 2: If your intention is that previousNumber contains the number you are currently counting, then it needs to be initialized outside of the loop, and updates when the current number changes.
Clue 3: You should not increment sizeOfArray on every loop iteration ...
Based on your Question, I'd say that your thinking about / understanding of the code that you have written is woolly. And this is why you are having difficulty debugging it.
In order to debug a piece of code effectively, you first need a mental model of how it ought to work. Then you use the debugger to watch what is happening at key points to confirm that the program is behaving as you expect it to.
(If you come into the debugging process without a mental model, all you see is statements executing, variables changing, etcetera ... with nothing to tell you if the right thing is happening. It is like watching the flashing lights on a computer in an old movie ... not enlightening.)
I would opt for a hashmap where the key is the number and its value the count. This way you have a unique number and count. Your solution runs into a problem where you don't really know at index i, what count that number belongs to, unless your list has no duplicates and is in order with no gaps, like 1, 2, 3, 4, 5 as opposed to the case of 1, 1, 1, 1, 5, 5, 5, 5
HashMap<Integer, Integer> occurances = new HashMap>Integer, Integer>();
int[] someSortedArray = new int[10];
//fill up a sorted array
for(int index = 0; index < someSortedArray.length; index++)
{
someSortedArray[index] = index+1;
}
int current = someSortedArray[0];
int count = 1;
for(int index = 1; index < someSortedArray.length; index++)
{
if(someSortedArray[index] != current)
{
occurances.put(current, count);
current = someSortedArray[index];
count = 1;
}else
{
count++;
}
}
System.out.println(occurances);
I think this should do it (haven't compiled).
You where not increasing sizeOfArray anywhere in your for loop.
// Get the count of instances.
int[] countOfNumbers = new int[50]; // Array to store count
int sizeOfArray = 0; // Last position of array filled
int instanceCounter = 1; // Counts number of instances
int previousNumber = finalArrayOfNumbers[0]; // Number stored at [k-1]
for (int k=1; k < finalArrayOfNumbers.length; k++) {
if (previousNumber == finalArrayOfNumbers[k]) {
instanceCounter++;
}
else
{
countOfNumbers[sizeOfArray] = instanceCounter;
instanceCounter = 1;
sizeOfArray++;
previousNumber = finalArrayOfNumbers[k]
}
}
countOfNumbers[sizeOfArray] = instanceCounter;

Categories

Resources