Printing integer from 2D array using nested FOR Loops - java

I'm having a bit of a problem with a piece of Java code, part of an AI project. The programm is supposed to take a 11x13 2d array representing a maze. The printed maze we are given uses characters for each cell, but for ease of use I've converted it to integers using a mnemonic code.
My problem is when I try to print the 2d integer array to the screen, to check eveything is OK, I get zeros at every cell, even though I have a check function in place which parses the array cell-by-cell checking for incorrect values.
The project is currently composed of 2 files. The main file - function (AISemesterProject.java) and a file that will implement the UCS algorithm in the future (UCS.java)
AISemesterProject.java
package aisemesterproject;
public class AISemesterProject
{
public static void main(String[] args)
{
UCS a = new UCS();
a.checkArrayInt();
a.printInt();
}
}
UCS.java
package aisemesterproject;
import java.util.Arrays;
public class UCS
{
int row = 11;
int col = 13;
int[][] array_int = new int[row][col];
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
int[][] array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
}
public void checkArrayInt()
{
int i = 0, j = 0;
boolean checker = false;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
if(!(array_int[i][i] == 0 || array_int[i][j] == 1 || array_int[i][j] == 2 || array_int[i][j] == 8 || array_int[i][j] == 9))
{
checker = true;
System.out.print("Error at Row:" + i + " Column:" + j + "\n");
}
}
}
if(checker == false)
{
System.out.print("Array OK... \n");
}
}
public void printInt()
{
int i = 0, j = 0;
//System.out.println(Arrays.deepToString(array_int));
for(i = 0; i < row; i++)
{
System.out.print("Row " + (i + 1) + ":");
for(j = 0; j < col; j++)
{
System.out.print(" " + String.valueOf(array_int[i][j]));
//System.out.print(" " + Integer.toString(array_int[i][j]));
//System.out.printf(" %d", array_int[i][j]);
//System.out.print(" " + array_int[i][j]);
}
System.out.print("\n");
}
}
}
Output
As you can see the output is not what I expected and I have tried 4 different methods for the print (1 active, 3 commented) but the result is always the same.
Anyone have an idea what am I missing or doing wrong?
Thanks for your time.

It looks like you have a scope issue...
int[][] array_int = new int[row][col];
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
you already created the array as a class level variable

Your constructor is setting the local variable array_int. This local variable overshadows the field with the same name, and thus it never sees the array you're assigning to it.
You should make sure that you're assigning to the field, which can most easily be done by removing the int[][] word from your constructor.

Thank you everyone. I moved the declatarion from the constructor to the variable at the beggining and it worked.
package aisemesterproject;
import java.util.Arrays;
public class UCS
{
int row = 11;
int col = 13;
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
int[][] array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
// Array initialization outside the constructor scope
}
public void checkArrayInt()
{
int i = 0, j = 0;
boolean checker = false;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
if(array_int[i][j] == 0) //Check for 0 = x
{
checker = false;
}
else if(array_int[i][j] == 1) //Check for 1 = e
{
checker = false;
}
else if(array_int[i][j] == 2) //Check for 2 = d
{
checker = false;
}
else if(array_int[i][j] == 8) //Check for 8 = s
{
checker = false;
}
else if(array_int[i][j] == 9) //Check for 9 = g
{
checker = false;
}
else //All other integers, which are false
{
checker = true;
System.out.print("Error at Row:" + i + " Column:" + j + "\n");
}
}
}
if(checker == false)
{
System.out.print("Array OK... \n");
}
}
public void printInt()
{
int i = 0, j = 0;
//System.out.println(Arrays.deepToString(array_int));
for(i = 0; i < row; i++)
{
System.out.print("Row " + (i + 1) + ":");
for(j = 0; j < col; j++)
{
System.out.print(" " + String.valueOf(array_int[i][j]));
//System.out.print(" " + Integer.toString(array_int[i][j]));
//System.out.printf(" %d", array_int[i][j]);
//System.out.print(" " + array_int[i][j]);
}
System.out.print("\n");
}
}
}

Related

How do I print out factors of an input using loops?

Here is my mess of a code. I have to write a program that inputs a positive integer greater than 3. Validate that the integer is in fact greater than 3. Then print all possible pairs of positive integers great than whose product is less than or equal to the number entered.
ex. If 24 is the input.
It would print:
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8....
9 = 3 x 3
12 = 3 x 4..
24 = 3 x 8...
all the way to
24 = 4 x 6
import java.util.Scanner;
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int j = 0;
int k = 2;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
while (product < i) {
if (product == i) { j++; k = 2;
for (j = 2; product < i; k++) {
product = j * k;
System.out.println(product + " = " + j + " x " + k);
if (product == i) { j++; k = 2;
}
}
}
}
}
}
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
for (int j = 2; j < i / 2; j++) {
for (int k = 2; k < i / 2; k++) {
if (j <= k && j * k <= i)
System.out.println(j * k + " = " + j + "*" + k);
}
}
// while (product < i) {
// if (product == i) {
// j++;
// k = 2;
// for (j = 2; product < i; k++) {
// product = j * k;
// System.out.println(product + " = " + j + " x " + k);
// if (product == i) {
// j++;
// k = 2;
// }
// }
// }
// }
}
}

Need help to solve the hackerrank challenge

I'm trying to solve an "Almost Sorted" challenge in hackerrank the problem is:
Given an array with elements, can you sort this array in ascending order using only one of the following operations?
Swap two elements.
Reverse one sub-segment.
Input Format
The first line contains a single integer, , which indicates the size of the array.
The next line contains integers separated by spaces.
Sample Input #1
2
4 2
Sample Output #1
yes
swap 1 2
Sample Input #2
3
3 1 2
Sample Output #2
no
Sample Input #3
6
1 5 4 3 2 6
Sample Output #3
yes
reverse 2 5
I tried to solve the challenge and my code is working but it seems it's to slow for big arrays.
Kindly asking you to help me to find a better solution for mentioned problem.
Below is my code:
import java.util.*;
public class Solution
{
private static int[] arr;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int N = in.nextInt();
arr = new int[N];
for (int i = 0; i < N; i++)
{
arr[i] = in.nextInt();
}
if (IsSorted(arr))
{
System.out.println("yes");
return;
}
if(CheckSingleSwap(arr))
return;
if(CheckSingleReverse(arr))
return;
System.out.println("no");
}
private static boolean CheckSingleReverse(int[] arr)
{
int length = arr.length;
int limit = length - 2;
int current = 1;
List<Integer> indexes = new ArrayList<Integer>();
while (current < limit)
{
for (int i = 0; i < length; i++)
{
int temp = current + i;
for (int j = i; j <= temp && temp < length; j++)
{
indexes.add(j);
}
if (IsSorted(ReverseArrayPart(arr, indexes)))
{
System.out.println("yes");
System.out.println("reverse " + (indexes.get(0) + 1) + " " + (indexes.get(indexes.size() - 1) + 1));
return true;
}
indexes.clear();
}
current++;
}
return false;
}
private static int[] ReverseArrayPart(int[] arr, List<Integer> indexes)
{
int[] result = new int[arr.length];
int[] arrayPart = new int[indexes.size()];
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (indexes.contains(i))
{
arrayPart[j] = arr[i];
j++;
}
result[i] = arr[i];
}
for(int i = 0; i < arrayPart.length / 2; i++)
{
int temp = arrayPart[i];
arrayPart[i] = arrayPart[arrayPart.length - i - 1];
arrayPart[arrayPart.length - i - 1] = temp;
}
j = 0;
for (int i = 0; i < result.length; i++)
{
if (indexes.contains(i))
{
result[i] = arrayPart[j];
j++;
}
}
return result;
}
private static boolean CheckSingleSwap(int[] arr)
{
int count = 0;
int[] B = Arrays.copyOf(arr, arr.length);
Arrays.sort(B);
List<Integer> indexes = new ArrayList<Integer>();
for(int i = 0; i < arr.length; i++)
{
if(arr[i] != B[i])
{
count++;
indexes.add(i+1);
}
}
if(count > 2)
return false;
System.out.println("yes");
System.out.println("swap " + indexes.get(0) + " " + indexes.get(1));
return true;
}
private static boolean IsSorted(int[] arr)
{
int length = arr.length;
for (int i = 0; i < length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
return false;
}
}
return true;
}
}
For the following code, pass in A as the original array and B as the sorted array.
CheckSingleSwap:
Instead of adding the indices to another list, store the first swap you encounter, and keep going; if you find the corresponding other swap, then store it and record the finding; if you find a different swap, exit with false. At the end if you've recorded the finding, print the corresponding indices.
private static boolean CheckSingleSwap(int[] A, int[] B)
{
int L = A.length;
int firstSwap = -1, secondSwap = -1;
for(int i = 0; i < L; i++)
{
if(A[i] != B[i])
{
if (firstSwap == -1)
firstSwap = i;
else if (secondSwap == -1 && A[i] == B[firstSwap] && A[firstSwap] == B[i])
secondSwap = i;
else
return false;
}
}
if (firstSwap != -1 && secondSwap != -1)
{
System.out.println("yes");
System.out.println("swap " + (firstSwap + 1) + " " + (secondSwap + 1));
return true;
}
System.out.println("array is already sorted!");
return false; // or whatever you decide to do; maybe even an exception or enumerated type
}
CheckSingleReverse:
You are doing WAY too much here! You seem to be brute forcing every single possible case (at first glance).
What you can do instead is to find the region where all the numbers are different. If there are more than two of these, or two which are separated by more than one element, then return false immediately.
The reason for the "more than one" thing above is because of odd-number length regions - the middle element would be the same. If you find such two regions, treat them as one. Then you can proceed to find out if the region is reversed.
private static boolean CheckSingleReverse(int[] A, int[] B)
{
// find region
int L = A.length;
int diffStart = -1, diffEnd = -1; boolean mid = false, found = false;
for (int i = 0; i < L; i++)
{
if (A[i] != B[i])
{
if (found)
{
if (i - diffEnd == 2 && !mid)
{
mid = true;
found = false;
diffEnd = -1;
}
else
return false;
}
else if (diffStart == -1)
diffStart = i;
}
else
if (diffStart != -1 && diffEnd == -1)
{
found = true;
diffEnd = i - 1;
}
}
if (diffEnd == -1)
{
if (A[L - 1] != B[L - 1])
diffEnd = L - 1;
else if (!found)
{
System.out.println("array is already sorted!");
return false;
}
}
// find out if it's reversed
int count = (diffEnd - diffStart + 1) / 2;
for (int i = 0; i < count; i++)
{
int oneEnd = diffStart + i, otherEnd = diffEnd - i;
if (!(A[oneEnd] == B[otherEnd] && A[otherEnd] == B[oneEnd]))
return false;
}
System.out.println("yes");
System.out.println("reverse " + (diffStart + 1) + " " + (diffEnd + 1));
return true;
}
Just to give you an idea of the performance boost, on ideone.com, with an array length of 150, the original implementation of CheckSingleReverse took 1.83 seconds, whereas the new one took just 0.1 seconds. With a length of 250, the original actually exceeded the computational time limit (5 seconds), whereas the new one still took just 0.12 seconds.
From this it would seem that your implementation takes exponential time, whereas mine is linear time (ignoring the sorting).
Funnily enough, with an array size of 3 million I'm still getting around 0.26 seconds (ideone's execution time fluctuates a bit as well, probs due to demand)

Zigzag conversion

Question is : The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
I have written below code, appearantly it works fine, but I might miss some corner cases. Could you help me to find all the corner cases for this question on my answer?
public static String zigZagConversion(String s , int rowNum){
if (s == null){
throw new IllegalArgumentException();
}
if (rowNum == 1){
return s;
}
StringBuilder str = new StringBuilder();
int step = 2 * rowNum - 2 ;
for (int i = 0 ; i < rowNum ; i++){
if( i == 0 || i == rowNum -1){
for (int j = i ; j < s.length() ; j +=step){
str.append(s.charAt(j));
}
}
else{
int step2 = 2* (rowNum - i - 1);
int step3 = step - step2;
int k = i;
boolean flag = true;
while (k < s.length()){
str.append(s.charAt(k));
if(flag){
k += step2;
flag = false;
}
else{
k +=step3;
flag = false;
}
}
}
}
return str.toString();
}
It gives incorrect output for "PAYPALISHIRING", 4
P I N
A L S I G
Y A H R
P I
So the correct answer should be PINALSIGYAHRPI.
But your program gives PINALIGYAIHRNPI:
an "S" is missing, one extra "I" and one extra "N".
Your revised version is still incorrect, it gives PINALSIIGYAHNPI.
The problem is in the while loop in the middle.
You need to alternate the step counting,
setting the flag on and off.
Your mistake was to only set it off once, and never back on again.
str.append(s.charAt(k));
if (flag) {
k += step2;
flag = false;
} else {
k += step3;
flag = true;
}
With this correction, I believe your solution is correct. (I also added a minor improvement there, extracting the common str.append(s.charAt(k)); from the if-else branches.
My solution on leetcode forum:
https://leetcode.com/problems/zigzag-conversion/discuss/549451/Java-Solution-O(n)-with-algorithm
The mathematic algorithm for zigzag is:
originalDiff = numRows * 2 - 2;
If -> 'currRow' equals First or last lines
use the originalDiff (numRows * 2 - 2)
Else ->
For each new line:
upperDiff += 2,
lowerDiff -=2
Examples:
numRows =2 -> originalDiff = 2
PYAIHRN
APLSIIG
3 -> 4
P A H N
A P L S I I G
Y I R
numRows = 4 -> originalDiff = 6
P I N
A L S I G
Y A H R
P I
numRows = 5 -> originalDiff = 8
P H
A SI
Y I R
P L I G
A N
*/
My solution:
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1) {
return s;
}
String newString = "";
int originalDiff = numRows * 2 - 2;
int diff = originalDiff;
int upperDiff = 0;
boolean isGoingDown = true;
int currIndex = 0;
int currRow = 0;
int startingIndex = 0;
for(int i = 0; i < s.length(); i++) {
System.out.println(currIndex);
newString += s.charAt(currIndex);
if(currRow == 0 || currRow == numRows - 1) {
currIndex += originalDiff;
} else {
if(isGoingDown) {
currIndex += diff;
isGoingDown = !isGoingDown;
} else {
currIndex += upperDiff;
isGoingDown = !isGoingDown;
}
}
if(currIndex >= s.length()) {
currRow++;
diff -= 2;
upperDiff += 2;
currIndex = currRow;
isGoingDown = true;
}
if(currRow == numRows) {
i = s.length();
}
}
return newString;
}
}
Zigzag conversion from leetcode in Javascript
Solution
const zigzag = (str, num) => {
if (num === 1) {
return str;
}
let check = true;
let result = [];
let i = 0;
while (i < str.length) {
result.push([]);
let j = 0;
while (j < num) {
if (check){
result[result.length-1].push(str[i]);
i++;
} else {
if (j == 0) {
result[result.length-1].push(null);
} else if (j === num-1) {
result[result.length-1].unshift(null);
} else {
result[result.length-1].unshift(str[i]);
i++;
}
}
j++;
}
check = !check;
}
let zigzag = [];
for (let k = 0; k < num; k++){
for(let l = 0; l < result.length; l++) {
zigzag.push(result[l][k]);
}
}
return zigzag.join("");
}
Example Input
zigzag("ABCD", 3)
Output
ABDC
Run
https://repl.it/#VinitKhandelwal/zigzag-conversion-javascript
Using HashMap
public String convert(String s, int numRows) {
if (numRows == 1){
return s;
}
StringBuilder result = new StringBuilder();
Map<Integer, StringBuilder> map = new HashMap<>();
for (int i = 0; i < numRows; i++) {
map.put(i,new StringBuilder());
}
int it = 0;
boolean flip = true;
for (int i = 0; i < s.length(); i++) {
if (flip) {
if(it<s.length()){
map.get(it).append(s.charAt(i));
it++;
}
} else {
map.get(it).append(s.charAt(i));
it--;
}
if (it + 1 == numRows || it == 0)
flip = !flip;
}
for (Map.Entry entry: map.entrySet()) {
result.append(entry.getValue());
}
return result.toString();
}
My Solution is traversing the string in the same way it is said in the problem, it is better to make string array of size numrows and the rest is storing the string character as it is in the logic,
you can keep the index and when that index is 0 i.e at the starting then we have to go till the end of the row and then except for first and last row, every array will have diagonal element.
So after traversing till the end then assign index = numrows - 2 and save in the respective array string and decrease and do the same till index >0 and then again traverse till the end row, do this and when we reach the end of the string then break from the loop.
and then concate all the string of string array in a new res string.
class Solution {
public String convert(String s, int n) {
if(n==1 || n>=s.length())
return s;
String[] a = new String[n]; //string array
int ind=0; // index for the string array
boolean flag=true;
int cnt=0; //to keep the counter till where we have traversed the string
while(true && flag)
{
if(ind==0)
{
for(int i=0;i<n;i++)
{
a[i] += s.charAt(cnt);
cnt++;
if(cnt==s.length())
{
flag=false;
break;
}
} // here it has reached the end so we assign here
ind = n-2;
}
else if(ind>0 && ind<n && flag)
{
a[ind] += s.charAt(cnt);
cnt++;
if(cnt==s.length())
{
flag=false;
break;
}
ind--; // to move diagonally up
}
}
String res = new String("");
for(int i=0;i<a.length;i++)
{
// System.out.println(a[i].substring(4));
res += a[i].substring(4);
}
return res;
}
}
Following is the simple solution.
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows <= 1:
return s
res = ""
p = numRows * 2 - 2
temp = p
for i in range(0,numRows):
index = i
flag = 0
while index < len(s):
res = res + s[index]
if i == 0 or i == numRows-1:
index = index + p
else:
if flag == 0:
index = index + temp
flag = 1
else:
index = index + p-temp
flag = 0
temp = temp - 2
return res
zigzag-conversion Complete JavaScript-based solution
Created an Array of an array of row lengths. The main motive is to arrange characters in 2D array form and concat string row-wise.
var convert = function(s, numRows) {
let array =[],c=0,str='';
for(let row =0; row<numRows ; row++) {
array[row] = new Array();
}
while(c < s.length) {
for(let row =0; row<numRows ; row++) {
if((row+1)%numRows ==0) {
array[row].push(s[c]);
c++;
break;
} else {
array[row].push(s[c]);
c++;
}
}
for(let rr = numRows-2 ; rr>0;rr--) {
array[rr].push(s[c]);
c++;
}
}
for(let row =0; row<numRows ; row++) {
for(let i=0;i<array[row].length;i++){
if(array[row][i]){
str+=array[row][i]
}
}
}
return str
};
convert("PAYPALISHIRING",3)

Java nested while loops

I need nested while loops to print so that the outter loop k makes one decrement iteration every time that inner loop "I" finishes an iteration. K has to start at 5 and count back to 1 and I has to starts at 0 and count to 10 by 2's. So it would the out put would look like this:
K = 5 I = 0
K = 5 I = 2
K = 5 I = 4
K = 5 I = 6
K = 5 I = 8
K = 5 I = 10
K = 4 I = 0
I have been stumped for hours and tried everyway to I can think of to make it work. Can someone please help?
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display(){
while(k > 1){
while(i >=10){
i = i+2;
System.out.println("K = " + k + " I = " + i);
}
if (i >= 10){
k=k-1;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Display();
}
}
There are a few errors. Follow the comments
while(k >= 1){ // Make it >= instead of >
i = 0; // reset i
while(i <=10){ // Make it i<= (less than)
System.out.println("K = " + k + " I = " + i); //print before incrementing
i = i+2;
}
Rest of the code is correct. And the output is as expected
K = 5 I = 0
K = 5 I = 2
K = 5 I = 4
K = 5 I = 6
K = 5 I = 8
K = 5 I = 10
K = 4 I = 0
K = 4 I = 2
K = 4 I = 4
K = 4 I = 6
.
.
.
You need to initialize i before the start of the inner loop, inside the outer loop, so it gets reset each time
while(k > 1) {
i = 0;
while( i <= 10) {
Print
i += 2;
}
k--;
}
Your inner while loop condition was incorrect. And you were adding to i too soon so you would never print for 0.
Something like this
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display(){
while(k > 0){
i = 0;
while(i <= 10){
System.out.println("K = " + k + " I = " + i);
i+=2;
}
k--;
}
}
public static void main(String[] args) {
Display();
}
}
Replace your display method with this..
public static void Display(){
while(k > 1){
i=0; //initialise i back to 0
while(i <=10){ //Change >= to <=
i = i+2;
System.out.println("K = " + k + " I = " + i);
}
k--;
//comment or delete below if block
/*if (i >= 10){
k=k-1;
}*/
}
}
use the following code.
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display() {
while (k >= 1) { // use >=1 if you wanna print till 1
i = 0; // set i=0
while (i <= 10) {
System.out.println("K = " + k + " I = " + i); // add print
// statement
i = i + 2;
}
k--; // no need to use if (i >= 10){ }
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Display();
}
}
You can do it like this:
for(int k = 5;k>0;k--;){
for(int i = 0;i<10;i+=2;)
System.out.println(k+ "" +i)
}

How to write an "all these numbers are different" condition in Java?

OK, I have this problem to solve but I can’t program it in Java correctly. See the picture below, you’ll see a 6 pointed star were every point and intersection of lines is a letter.
The assignment is to position the numbers 1 to 12 in such a way that the sum of all lines of four balls is 26 and the sum of all the 6 points of the star is 26 as well.
This comes down to:
(A+C+F+H==26)
(A+D+G+K==26)
(B+C+D+E==26)
(B+F+I+L==26)
(E+G+J+L==26)
(H+I+J+K==26)
(A+B+E+H+K+L==26)
So I started programming a program that would loop through all options brute forcing a solution. The loop is working, however, it now shows solutions where one number is used more than once, which is not allowed. How can I make it in the code that it also checks whether all variables are different or not?
if ((A!= B != C != D != E != F != G != H != I != J != K != L)
I tried the above, but it doesn't work, because it says:
incomparable types: boolean and int.
How can I make a check within 1 or a small statement for whether or not all the numbers are different?
(instead of making a nested 12*12 statement which checks every variable combination)
This is my code so far:
public class code {
public static void main(String[] args){
for(int A = 1; A < 13; A++){
for(int B = 1; B < 13; B++){
for(int C = 1; C < 13; C++){
for(int D = 1; D < 13; D++){
for(int E = 1; E < 13; E++){
for(int F = 1; F < 13; F++){
for(int G = 1; G < 13; G++){
for(int H = 1; H < 13; H++){
for(int I = 1; I < 13; I++){
for(int J = 1; J < 13; J++){
for(int K = 1; K < 13; K++){
for(int L = 1; L < 13; L++){
if ((A+C+F+H==26) && (A+D+G+K==26) && (B+C+D+E==26) && (B+F+I+L==26) && (E+G+J+L==26) && (H+I+J+K==26) && (A+B+E+H+K+L==26)){
if ((A= C != D != E != F != G != H != I != J != K != L)){
System.out.println("A: " + A);
System.out.println("B: " + B);
System.out.println("C: " + C);
System.out.println("D: " + D);
System.out.println("E: " + E);
System.out.println("F: " + F);
System.out.println("G: " + G);
System.out.println("H: " + H);
System.out.println("I: " + I);
System.out.println("J: " + J);
System.out.println("K: " + K);
System.out.println("L: " + L);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
If I get it correctly, you want to check if all A to L are unique. So just put them in a set and find the size of the set:
if ((new HashSet<Integer>(
Arrays.asList(A, B, C, D, E, F, G, H, I, J, K, L)))
.size() == 12) {
//do your stuff
}
I strongly advise using recursion instead, which would vastly simplify the code. Do something like this:
function generate(set used, array list):
if list.size() == 12:
if list matches criteria:
yield list as solution
else:
for next = 1; next < 13; next++:
if next not in used:
used.add(next)
generate(used, list + next)
used.remove(next)
However, to answer you question directly: You can throw all the values into a set and check that it's size is equal to the number of items you threw in. This works because a set will count duplicates as one.
Before looking for a good solution for you, I would like to help with the error you get.
if ((A= C != D != E != F != G != H != I != J != K != L)){
This line does not makes much sense. The first thing the compiler will check is:
if (A=C)
You probably wanted to code if (A!=C), but let's consider what you really type. A=C is an attribution, so A will receive C value.
Then, the compiler will go on. After attributing C's value to A, it will check the comparison:
if (A=C != D)
This will compare A's value to D, which will result in a boolean -- let's say that the result is false.
The next comparison would be:
if (false != E)
At this point, there is a comparison between a boolean and an int, hence the error incomparable types: boolean and int..
Well, as you need to check wheter your numbers are unique, a nice solution would be the one proposed by #abhin4v.
Your nested loops will execute 12^12 = 8.91610045E12 IF-Statements, many of them invalid because of wrong combinations of numbers. You need permutations of 1,2,3,..,12 as candidates of your bruteforcing approach. The number of permutations of 12 Elements is 12!= 479 001 600, so the bruteforcing will be much faster I guess. With only generating valid permutations you don't need any check for valid combinations.
Here is some sample code, the code in nextPerm() is copied and modified from Permutation Generator :
import java.util.Arrays;
public class Graph26 {
private static final int A = 0;
private static final int B = 1;
private static final int C = 2;
private static final int D = 3;
private static final int E = 4;
private static final int F = 5;
private static final int G = 6;
private static final int H = 7;
private static final int I = 8;
private static final int J = 9;
private static final int K = 10;
private static final int L = 11;
private final static boolean rule1(final int[] n) {
return n[A] + n[C] + n[F] + n[H] == 26;
}
private final static boolean rule2(final int[] n) {
return n[A] + n[D] + n[G] + n[K] == 26;
}
private final static boolean rule3(final int[] n) {
return n[H] + n[I] + n[J] + n[K] == 26;
}
private final static boolean rule4(final int[] n) {
return n[B] + n[C] + n[D] + n[E] == 26;
}
private final static boolean rule5(final int[] n) {
return n[B] + n[F] + n[I] + n[L] == 26;
}
private final static boolean rule6(final int[] n) {
return n[E] + n[G] + n[J] + n[L] == 26;
}
private final static boolean rule7(final int[] n) {
return n[A] + n[B] + n[E] + n[H] + n[K] + n[L] == 26;
}
private final static boolean isValid(final int[] nodes) {
return rule1(nodes) && rule2(nodes) && rule3(nodes) && rule4(nodes)
&& rule5(nodes) && rule6(nodes) && rule7(nodes);
}
class Permutation {
private final int[] o;
private boolean perms = true;
public boolean hasPerms() {
return perms;
}
Permutation(final int[] obj) {
o = obj.clone();
}
private int[] nextPerm() {
int temp;
int j = o.length - 2;
while (o[j] > o[j + 1]) {
j--;
if (j < 0) {
perms = false;
break;
}
}
if (perms) {
int k = o.length - 1;
while (o[j] > o[k]) {
k--;
}
temp = o[k];
o[k] = o[j];
o[j] = temp;
int r = o.length - 1;
int s = j + 1;
while (r > s) {
temp = o[s];
o[s] = o[r];
o[r] = temp;
r--;
s++;
}
}
return o.clone();
}
}
public static void main(final String[] args) {
int[] nodes = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
final Graph26 graph = new Graph26();
final Permutation p = graph.new Permutation(nodes);
int i = 0;
while (p.hasPerms()) {
if (isValid(nodes)) {
System.out.println(Arrays.toString(nodes));
}
i++;
nodes = p.nextPerm();
}
System.out.println(i);
}
}

Categories