3 Lines only about for loop, very confused - java

why is the output 22212345?
Shouldn't it be: "43212345", because when we are keep adding the first values of the string onto the previous version of the string.
So everytime we increment k, we are going from 2,3,4 and adding it onto the previous version.
why is the output 22212345?
String str = "12345";
for (int k = 1; k <= 3; k++)
str = str.charAt(k) + str;

So everytime we increment k, we are going from 2,3,4 and adding it onto the previous version.
No, you're not. You're prefixing str with the char at k.
So, if we get a pen and piece of paper and desk check the code (why don't people desk check anymore 😓) you will see what's actually happening...
+---+-----------+---------+-----------------------+
| k | char at k | str | result (charAt + str) |
+---+-----------+---------+-----------------------+
| 1 | 2 | 12345 | 212345 |
| 2 | 2 | 212345 | 2212345 |
| 3 | 2 | 2212345 | 22212345 |
+---+-----------+---------+-----------------------+

This happends in each iteration:
first_loop_state: {
k : 1
initial_str : "12345";
str.charAt(k) : '2'
final_str : "212345"
}
second_loop_state:{
k : 2
initial_str : "212345";
str.charAt(k) : '2'
final_str : "2212345"
}
third_loop_state:{
k : 3
initial str : "2212345";
str.charAt(k) : '2'
final_str : "22212345"
}

Related

While loop gets terminated before condition is met when backtracking

I'm trying to write an iterative program that will help me palce 4 queens on a 4x4 board without them hitting each other. The problem is after looping through each position and backtracking a couple of times my main while loop that keeps looping until a solution is found gets terminated and the program ends even though the condition is not yet met.
I tried the following code:
static int[] solve(char[][] board){
int[] position = new int[4];
int row = 0;
int column = 0;
while(row < 4){
for(boolean check; column < board.length; column++){
System.out.println("["+row+","+column+"]");
check = true;
for(int queen= 0; queen < row; queen++){
if (position[queen] == column || queen- position[queen] == row - column || queen + position[queen] == row + column) {
check = false;
break;
}
}
if(check){
position[row] = column;
column = 0;
row++;
}
if(column > 2){
column = position[--row];
}
}
}
return position;
}
I'm currently getting the following output:
| Q | X | X | X |
| X | X | X | Q |
| X | Q | X | X |
| Q | X | X | X |
To check when exactly the while loop is getting terminated I printed the location (row and column)
System.out.println("["+row+","+column+"]"); and got the following:
[0,0][1,0][1,1][1,2][2,0][2,1][2,2][2,3][1,3][2,0][2,1][3,0][3,1][3,2][3,3][2,2][2,3]
After backtracking to [2,3] the while loop ends even though my row count is still less than 4.
I was expecting the following output:
| X | Q | X | X |
| X | X | X | Q |
| Q | X | X | X |
| X | X | Q | X |
I tried the code in a different compiler and still got the same wrong output. Is there a logical mistake that I missed out?
I'm new to programming so I'm still trying to get the hang of the fundamentals.

vice versa coding for value and its variables

I have 2 variables A and B
if A =1 then B should B=2
and if A=2 then B should B=1
Like this, there are 3 pairs 1-2,3-4,5-6
What's the best way of making a code instead of just if-else
It is possible to use simple addition and subtraction to get the other element of the two (x, x + 1):
int a = 1; // the other is 2, sum is 3
int b = 3 - a; // if a = 2, b = 1
int c = 3; // the other is 4, sum is 7
int d = 7 - c; // if c = 4, d = 3
int m = 5; // the other is 6, sum is 11
int n = 11 - m;
Another approach could be using the following logic:
if (a % 2 == 1) b = a + 1;
else b = a - 1;
So, an array could be used to provide +/- 1:
static int[] signs = {-1, 1};
public static int nextWithArrPositive(int a) {
return a + signs [a % 2];
}
This expression fails to work for negative a as in this case a % 2 == -1 and more advanced logic would be required to calculate the value properly to take into account the negative remainder:
public static int nextWithArr(int a) {
int sign = (a & 0x80000000) >> 31; //-1 if a < 0, 0 otherwise
// a >= 0 : 0 - even, 1 - odd;
// a < 0 : 1 - even, 0 - odd
return a + signs[a % 2 - sign];
}
However, a simpler expression can be designed:
public static int nextWithMod(int a) {
return a + a % 2 - (a - 1) % 2;
}
Let's compare the results of the three implementations including xor solution b = ((a - 1) ^ 1) + 1 offered in the comments by user3386109:
public static int nextXor(int a) {
return ((a - 1) ^ 1) + 1;
}
Tests:
System.out.println("+-----+-----+-----+-----+");
System.out.println("| a | arr | mod | xor |");
System.out.println("+-----+-----+-----+-----+");
for (int i = -6; i < 7; i++) {
System.out.printf("| %2d | %2d | %2d | %2d |%n", i, nextWithArr(i), nextWithMod(i), nextXor(i));
}
System.out.println("+-----+-----+-----+-----+");
Output:
+-----+-----+-----+-----+
| a | arr | mod | xor |
+-----+-----+-----+-----+
| -6 | -5 | -5 | -7 |
| -5 | -6 | -6 | -4 |
| -4 | -3 | -3 | -5 |
| -3 | -4 | -4 | -2 |
| -2 | -1 | -1 | -3 |
| -1 | -2 | -2 | 0 |
| 0 | -1 | 1 | -1 |
| 1 | 2 | 2 | 2 |
| 2 | 1 | 1 | 1 |
| 3 | 4 | 4 | 4 |
| 4 | 3 | 3 | 3 |
| 5 | 6 | 6 | 6 |
| 6 | 5 | 5 | 5 |
+-----+-----+-----+-----+
One simple solution is a table lookup. In an array for each possible value of a I store the corresponding value of b:
private static final int[] B_PER_A = { -1, 2, 1, 4, 3, 6, 5 };
Since array indices always start at 0 in Java, we need to put a dummy value at index 0. This value is never used (or should never be, at least).
Let’s try it out:
for (int a = 1; a <= 6; a++) {
int b = B_PER_A[a];
System.out.format("a: %d; b: %d.%n", a, b);
}
Output:
a: 1; b: 2.
a: 2; b: 1.
a: 3; b: 4.
a: 4; b: 3.
a: 5; b: 6.
a: 6; b: 5.
Generalized to more than 3 pairs
If you need to handle a variable number of pairs, resort to math.
public static int calcB(int a) {
// 0-based index of pair (0 = 1-2, 1 = 3-4, etc.)
int pairNumber = (a - 1) / 2;
// a + b for given pair
int pairSum = 4 * pairNumber + 3;
int b = pairSum - a;
return b;
}
In each pair the sum is equivalent to 3 modulo 4. I am exploiting this fact in finding the sum for a given pair. When I subtract a from that sum, I get b. Let’s see that demonstrated too:
for (int a = 1; a <= 8; a++) {
int b = calcB(a);
System.out.format("a: %d; b: %d.%n", a, b);
}
a: 1; b: 2.
a: 2; b: 1.
a: 3; b: 4.
a: 4; b: 3.
a: 5; b: 6.
a: 6; b: 5.
a: 7; b: 8.
a: 8; b: 7.
The latter solution is more complicated and harder to read. So if you always have got three pairs, no more, no less, I recommend the simpler table lookup presented first.

array combine inputs more then 2

I'm working on an implementation of the "Merge Numbers" game, seen here on the Play store: https://play.google.com/store/apps/details?id=com.ft.game.puzzle.cubelevels
The idea is that if I have a 2D array of cells, some of which are empty and others of which have numbers, and I place a given number into an empty cell, then if that number matches at least 3 of its neighbors, the neighbors are made empty and the cell value is incremented. A simple example:
| 1 | 2 | 3 | 4 |
| 3 | | 2 | |
| 1 | 2 | 3 | |
| | 2 | 1 | 4 |
If the next number (generated randomly by the game) is 2, and I place it into cell (1, 1) (where (0, 0) is the upper left cell), the new game board should look like this:
| 1 | | 3 | 4 |
| 3 | 3 | | |
| 1 | | 3 | |
| | 2 | 1 | 4 |
The newly-placed 2 is incremented to 3, and the neighboring cells with value of 2 have been cleared.
I'm having trouble figuring out how to do this. Here is my code so far:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[][] w = {{1, 2, 3, 4}, {3, 0, 4, 0}, {1, 2, 3, 0}, {0, 2, 1, 4}};
Scanner input = new Scanner(System.in);
System.out.println("Enter space for putting 1: ");
int a = input.nextInt();
int b = input.nextInt();
if (a == 1 && b == 1) {
w[1][1] = 1;
for (a = 0; a < w.length; a++) {
for (b = 0; b < w[0].length; b++) {
System.out.print(w[a][b] + " ");
}
System.out.print('\n');
}
System.out.println("Enter space for putting 4: ");
a = input.nextInt();
b = input.nextInt();
if (a == 1 && b == 3) {
w[1][3] = 4;
for (a = 0; a < w.length; a++) {
for (b = 0; b < w[0].length; b++) {
System.out.print(w[a][b] + " ");
}
System.out.print('\n');
}
}
}
}
}
How can I check to see if the neighbors of the newly-added number have the same value?
How can I increment the newly-added number?

Printing dashes with and array

I have to write a method called print() that prints out the results as follows;
Original:
-----------
|9|7|9|4|3|
-----------
Sorted:
-----------
|3|4|7|9|9|
-----------
My new code is as follows:
for(int i=0;i< intArray.length; i++)
{
if(i==intArray.length-1)
{
System.out.print("----\n");
}
else{
System.out.print("----");
}
}
for(int i=0;i< intArray.length; i++)
{
if(i==0)
{
System.out.println("| "+intArray[i]+" | ");
}
else if(i==intArray.length-1)
{
System.out.print(intArray[i]+" |\n");
}
else{
System.out.print(intArray[i]+" | ");
}
}
for(int i=0;i< intArray.length; i++)
{
if(i==intArray.length-1)
{
System.out.print("----\n");
}
else{
System.out.print("----");
}
}
Its almost perfect except one number is out of place and is displaying as follows:
Original:
| 3 |
2 | 9 | 9 | 6 |
Sorted:
| 2 |
3 | 6 | 9 | 9 |
Frequencies:
Original:
| 9 |
1 | 6 | 6 | 4 | 8 | 5 | 8 | 5 | 1 |
Sorted:
| 1 |
1 | 4 | 5 | 5 | 6 | 6 | 8 | 8 | 9 |
Frequencies:
Can somebody please tell me what the problem is as I can't figure it out. Thanks for all of your help in the comments
System.out.println appends a newline after the output, that is, after every array item in your code. You should use System.out.print instead. Also it looks like you are only printing the pipes at the end of the array, making it look something like
34799|
For the example output you need something like
public void print()
{
//no need for \n, println produces one at the end of the string
System.out.println("-------------------");
System.out.print("|");
for(int i=0;i< intArray.length; i++)
{
System.out.print(intArray[i] + "|");
}
System.out.print("\n-------------------\n");
}
There is no need of if-else, we can print the array with a simple for loop, e.g.:
int[] array = new int[]{1,2,3,4,5};
System.out.println("--------------");
System.out.print("|");
for(int element : array){
System.out.print(element + "|");
}
System.out.println("--------------");
update
Here's how it works:
First println() prints first dashed line.
Second print() before the for loop prints initial '|'
print() in the for loop prints element appended by '|'
There is no need to print the last '|' it is already done in the for loop.
Last println() prints dashed line after the array contents.

Complexity in tilde notation of nested for loops

How do I find the complexity in tilde notation of the following algorithm:
for (int j = 0; j < N; j++) {
for (int k = j + 1; k < N; k++) {
array[k] = array[j];
}
array[j] = k
}
I've made a table with how many times the inner for-loop loops if N = 9:
| j | # of loops |
|:-----------|------------:|
| 0 | 8 |
| 1 | 7 |
| 2 | 6 |
| 3 | 5 |
| 4 | 4 |
| 5 | 3 |
| 6 | 2 |
| 7 | 1 |
| 8 | 0 |
As you evaluate, the number of inner iterations decreases linearly from 8 down to 0, i.e. it is 4 on average, for a total of 4.9=36.
More generally, the average is (N-1)/2 and the total N.(N-1)/2.
Consequently, I(N) ~ N²/2, in terms of the iteration count.
In terms of memory accesses (R+W), it's the double: A(N) ~ N². (The extra access in the outer loop adds a negligible N contribution.)

Categories

Resources