I wrote a program that reads an array of integers and two numbers n and m. The program check that n and m never occur next to each other (in any order) in the array.
import java.util.*;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner (System.in);
int len = scanner.nextInt();
int [] array = new int [len];
boolean broken = false;
for (int i = 0; i < len; i++){
array [i] = scanner.nextInt();
}
int n = scanner.nextInt();
int m = scanner.nextInt();
for (int j = 1; j < len; j++){
if((array[j]==n)&&(array[j+1]==m) || (array[j]==n)&&(array[j-1]==m) || (array[j]==m)&&(array[j+1]==n) || (array[j]==m)&&(array[j-1]==n)){
broken = true;
break;
}
}
System.out.println(broken);
}
}
Test input:
3
1 2 3
3 4
Correct output: true
My output is blank. What am I doing wrong?
Your code will throw ArrayIndexOutOfBoundsException as you are using array[j+1] whereas you have loop condition as j < len. The condition should be j < len -1.
The following works as expected:
for (int j = 1; j < len - 1; j++) {
if ((array[j] == n && array[j + 1] == m) || (array[j] == n && array[j - 1] == m)
|| (array[j] == m && array[j + 1] == n) || (array[j] == m && array[j - 1] == n)) {
broken = true;
break;
}
}
A sample run:
3
1 2 3
3 4
true
Your code will throw ArrayIndexOutOfBoundsException because of array[j+1] where j can be len-1. Actually you don't need to check both sides(previous and next element), checking combination with previous is enough since in the next iteration combination with next element will be checked.
for (int j = 1; j < len; j++){
if((array[j]==n && array[j-1]==m) || (array[j]==m && array[j-1]==n)){
broken = true;
break;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int len = scan.nextInt();
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int i = 0, prv = 0; i < len; i++) {
int num = scan.nextInt();
if (!map.containsKey(num))
map.put(num, new HashSet<>());
if (i > 0)
map.get(prv).add(num);
prv = num;
}
int n = scan.nextInt();
int m = scan.nextInt();
boolean res = !map.containsKey(n) || !map.containsKey(m) || !map.get(n).contains(m) && !map.get(m).contains(n);
System.out.println(res);
}
Related
I have to write a code as a task for my university and we have to recreate Minesweeper with java and it has to be runned in the command line.
For the matchfield we have to make an array that looks in the end like this picture:
Example how it sould look in the end
And to choose the field we have to use the scanner.
For example if you want to chose field C3, you have to type into the scanner C3.
At the moment im struggleing a little bit with the field.
I had 2 ideas but both didn't work out very well.
in the first try i tried to create everything with 2 for loops and 1 array but my problem was that I couldn't add 2 charrs, so I had the chars 0 to 9 and the charrs A to J.
In the second try I created 3 array, one with the numbers 0 to 9 and anothe array A to J and in the third array i wanted to combine both arrays. And now I'm wondering if this it's possible if I can acctually combine them in the way I want and if it's possible could somebody give me some help?
import java.util.Scanner;
import java.util.Arrays;
public class Minesweeper {
public static void main (String[] args) {
char c = 'A';
char d = '0';
char e = '9';
char f = 'J';
char[][] feldz = new char[11][11];
char[][] feldb = new char[11][11];
char[][] feld = new char[11][11];
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldz[i][j] = ' ';
System.out.print(feldz[i][j] + " |");
}
if (d > e) {
d = '0';
}
if (d <= e && i > 0){
feldz[i][j] = d;
System.out.print(feldz[i][j] + " |");
}
if (i > 0 && j == 10) {
d++;
}
}
System.out.println("");
}
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (i > 0 && j == 0){
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (c > f) {
c = 'A';
}
if(c <= f && j > 0){
feldb[i][j] = c;
System.out.print(feldb[i][j] + " |");
c++;
}
if (j == 10){
System.out.println("");
}
}
}
}
}
You don't actually need array to print the maze , nested loops is enough for that. 2d Array is only required to store the input. Please try the below code:
int size = 10;
int [][] maze = new int[size][size];
while (true){
System.out.print(' ');
for (int i = 0; i < size; i++) {
System.out.print('|');
System.out.print((char) ('A' + i));
}
for (int i = 0; i < size; i++) {
System.out.println("");
System.out.print(i);
for (int j = 0; j < size; j++) {
System.out.print('|');
if(maze[i][j] > 0) {
System.out.print(maze[i][j]);
} else {
System.out.print(' ');
}
}
}
int row = -1;
int col = -1;
System.out.println("\nEnter CoOrdinates");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.length() == 2) {
char charAt = input.charAt(0);
if(charAt >= 'A' && charAt <= 'A'+size-1) {
col = charAt-'A';
}
charAt = input.charAt(1);
if(charAt >= '0' && charAt <= '0'+size-1) {
row = charAt-'0';
}
if(row != -1 && col != -1) {
System.out.println("Enter Action");
input = scanner.nextLine();
int action = Integer.parseInt(input);
maze[row][col] = action;
} else {
System.out.println("Incorrect Input");
}
}
}
The problem is to generate prime in between two interval, detail problem is given in this link. SPOJ Prime Generator.
Let me explain the magic numbers and the algorithm I followed.
I have used modified Sieve Eratosthenes algorithm (modified in sense because I used the basic idea.) for implementation.
Starting number of interval, m and End number of the interval n are <= 10^9 and the difference is <=10^5 (1 <= m <= n <= 1000000000, n-m<=100000)
There is no even prime number except 2, so I considered max m and n (10^9)/2
and sqrt(max number) is around 32000 (considering both odd and even), finally 32000/2= 16,000 is the size of odd numbers list input_aray.
Finally total number range is divided into 3 regiions.
m and n both >= 32000 in this case the size of the input_aray is (n-m+1)/2 from 16001 index of array, numbers between m and n is stored (only odd numbers).
m and n <32000 in this case size of input_aray is upto n/2.
m <32000 and n>32000 in this case size of input_aray is (n-32000+1)/2.
Boolean array bol of same size as input_aray is kept to track which number is visited so that two number can't be considered twice.
for (int j = 1; j < 16001; j++) {
int flag = input_aray[j];
This loop choose n index from input_aray and check if there is any number in this array that is divisible, if so then same index of bol is initialized into false.
for (int k = j + flag; k <= 16000; k = k + flag)
This loop check for prime numbers upto 32000.
for (int k = 16001; k < input_aray.length; k++)
This one checks in between ** m and n** (when m&n >=32000)
*This is the fastest approach I could implement, but still get Time Limit Exceed. What could be the probable cause?
public static void main(String args[]){
Scanner take= new Scanner(System.in);
ArrayList<String> arrayList= new ArrayList<>();
int m,n;
int temp= take.nextInt();
take.nextLine();
if(temp>=0 && temp<=10){
for(int i=0;i<temp;i++) {
String temp1 = take.nextLine();
arrayList.add(temp1);
}
}
for(int i=0;i<arrayList.size();i++){
String[] temp_aray= arrayList.get(i).split(" ");
m= Integer.parseInt(temp_aray[0]);
n= Integer.parseInt(temp_aray[1]);
if(m>0 && n>0 && m<=10E8 && n<=10E8 && n-m<= 10E4 ) {
if (m >= 32000 && n >= 32000) {
//m & n > 32000
int start;
int[] input_aray = new int[16001 + ((n - m + 1) / 2) + 1];
boolean[] bol = new boolean[16001 + ((n - m + 1) / 2) + 1];
Arrays.fill(bol, true);
input_aray[0] = 2;
input_aray[1] = 3;
for (int j = 2; j < 16001; j++) {
input_aray[j] = input_aray[j - 1] + 2;
}
if (m % 2 == 0) {
start = m + 1;
} else {
start = m;
}
for (int j = 16001; j < input_aray.length; j++) {
input_aray[j] = start;
start += 2;
}
for (int j = 1; j < 16001; j++) {
int flag = input_aray[j];
for (int k = j + flag; k <= 16000; k = k + flag) {
if (input_aray[k] % flag == 0 && bol[k] == true) {
bol[k] = false;
}
}
for (int k = 16001; k < input_aray.length; k++) {
if (input_aray[k] % flag == 0) {
bol[k] = false;
}
}
}
int num = 1;
for (int j = 16001; j < bol.length; j++) {
if (bol[j] == true) {
System.out.println(input_aray[j]);
num++;
}
}
System.out.println();
}
if(m<32000 && n< 32000){
int[] input_aray = new int[(n/2)+1];
boolean[] bol = new boolean[(n/2)+1];
Arrays.fill(bol, true);
input_aray[0] = 2;
input_aray[1] = 3;
for (int j = 2; j < input_aray.length; j++) {
input_aray[j] = input_aray[j - 1] + 2;
}
for (int j = 1; j < Math.sqrt(n); j++) {
int flag = input_aray[j];
for (int k = j + flag; k<input_aray.length; k = k + flag) {
if (input_aray[k] % flag == 0 && bol[k] == true) {
bol[k] = false;
}
}
}
int num = 1;
for (int j = 0; j < bol.length; j++) {
if (bol[j] == true && input_aray[j] >=m && input_aray[j]<=n) {
System.out.println(input_aray[j]);
num++;
}
}
System.out.println();
}
if(m<32000 && n>32000){
int start;
int[] input_aray = new int[16001 + ((n - 32000 + 1) / 2) + 1];
boolean[] bol = new boolean[16001 + ((n - 32000 + 1) / 2) + 1];
Arrays.fill(bol, true);
input_aray[0] = 2;
input_aray[1] = 3;
for (int j = 2; j < 16001; j++) {
input_aray[j] = input_aray[j - 1] + 2;
}
start=32001;
for (int j = 16001; j < input_aray.length; j++) {
input_aray[j] = start;
start += 2;
}
for (int j = 1; j < 16001; j++) {
int flag = input_aray[j];
for (int k = j + flag; k <= 16000; k = k + flag) {
if (input_aray[k] % flag == 0 && bol[k] == true) {
bol[k] = false;
}
}
for (int k = 16001; k < input_aray.length; k++) {
if (input_aray[k] % flag == 0) {
bol[k] = false;
}
}
}
int num = 1;
for (int j = 0; j < bol.length; j++) {
if (bol[j] == true && input_aray[j]>=m && input_aray[j]<=n) {
System.out.println(input_aray[j]);
num++;
}
}
System.out.println();
}
}
}
}
So I want to skip the first and last elements of the array to initialize. What am I doing wrong?
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Columns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Here is my output:
Input Rows:
3
Input Columns:
3
Entered Values:
0 0 0
0 0 0
0 0 0
You need to change the if condition inside the loop like following:
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 && j==0) || (i == m -1 && j == n -1)) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
In this line:
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
You are testing for the equality of values within your array. You should be comparing whether the indices you are looking at are the beginning or end of the array.
That is to say, you want to compare whether (in pseudo code):
i==0 and j==0, OR i==max index in its dimension and j==max index in its dimension
I have deliberately omitted the literal answer, because this looks a tiny bit like homework.
You compare the value of arr[i][j] with the value of arr[0][0]. You should instead compare i==0 && j==0 || i==m -1 && j==n -1
As your array was empty, and as you start the loop, arr[i][j] was equal to arr[0][0], skipping the first element. but for the next loop, arr[i][j] was still empty, and as you compare it to a non-initialised value, it's always true, skipping in each step
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Coloumns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i==0 && j==0 || i==m-1 && j==n-1) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
You don't need to check whether the array items are equal, you just want to check whether the row and column are equal to the last and first.
I am taking a Java class at school. Java looks simple but complicated for me.
I am having a trouble with sorting a two-dimensional array. Please Please Please help me.
Here is what I coded. I don't know why it doesn't work.
public static void selectionSort(int[][] list) {
for (int k = 0; k < list.length;k++){
for (int i = 0; i < list[k].length;i++) {
int currentMin = list[k][i];
int currentMinIndexRow = k;
int currentMinIndexColumn = i;
if (k == 3 && i == 3) continue;
for (int m = k; m < list.length; m++) {
for (int j = i; j < list[k].length; j++) {
if (m == k && i == j) continue;
if (currentMin > list[m][j]) {
currentMin = list[m][j];
currentMinIndexRow = m;
currentMinIndexColumn = j;
}
}
}
if (currentMinIndexRow != k && currentMinIndexColumn != i) {
list[currentMinIndexRow][currentMinIndexColumn] = list[k][i];
list[k][i] = currentMin;
}
}
}
}
Thank you so much guys!!!!!
I am trying to write a program that prompts the user to enter two lists of integers and displays whether the two are identical.
Such as,
"Enter list1: 51 25 22 6 1 4 24 54 6
Enter list2: 51 22 25 6 1 4 24 54 6
The two arrays are identical
Enter list1: 51 5 22 6 1 4 24 54 6
Enter list2: 51 22 25 6 1 4 24 54 6
The two arrays are not identical
Here is what I wrote.
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[][] list1 = new int[3][3];
int[][] list2 = new int[3][3];
System.out.print("Enter list1: ");
for (int row=0 ;row < list1.length ;row++){
for (int column=0;column<list1[row].length; column++){
list1[row][column] = input.nextInt();
}
}
System.out.print("Enter list2: ");
for (int row=0 ;row < list2.length ;row++){
for (int column=0;column<list2[row].length; column++){
list2[row][column] = input.nextInt();
}
}
selectionSort(list1);
selectionSort(list2);
if (equals(list1, list2) == true)
System.out.println("The two arrays are identical");
else
System.out.println("The two arrays are not identical");
}// void main
public static boolean equals(int[][] m1, int[][] m2){
boolean result = true;
for (int row=0 ;row < m1.length ;row++){
for (int column=0 ;column<m1[row].length ; column++){
if (m1[row][column] != m2[row][column]) {result = false; break;}
}
}
return result;
}// boolean equals
public static void selectionSort(int[][] list) {
for(int k = 0; k < list.length;k++){
for(int i = 0; i < list[k].length;i++) {
int currentMin = list[k][i];
int currentMinIndexRow = k;
int currentMinIndexColumn = i;
if(k == 3 && i == 3) continue;
for(int m = k; m < list.length; m++){
for (int j = i; j < list[k].length; j++) {
if (m == k && i == j) continue;
if (currentMin > list[m][j]) {
currentMin = list[m][j];
currentMinIndexRow = m;
currentMinIndexColumn = j;
}
}
}
if (currentMinIndexRow != k && currentMinIndexColumn != i) {
list[currentMinIndexRow][currentMinIndexColumn] = list[k][i];
list[k][i] = currentMin;
}
}
}
}
Thank you for your comments.
Thank you so much guys!!!!
I figured out why I was wrong.
There was a really really really simple error.
if (currentMinIndexRow != k || currentMinIndexColumn != i) {
list[currentMinIndexRow][currentMinIndexColumn] = list[k][i];
list[k][i] = currentMin;
}
The above code is what I corrected. Thank you.
I have this problem, I need to generate from a given permutation not all combinations, but just those obtained after permuting 2 positions and without repetition. It's called the region of the a given permutation, for example given 1234 I want to generate :
2134
3214
4231
1324
1432
1243
the size of the region of any given permutation is , n(n-1)/2 , in this case it's 6 combinations .
Now, I have this programme , he does a little too much then what I want, he generates all 24 possible combinations :
public class PossibleCombinations {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Entrer a mumber");
int n=s.nextInt();
int[] currentab = new int[n];
// fill in the table 1 TO N
for (int i = 1; i <= n; i++) {
currentab[i - 1] = i;
}
int total = 0;
for (;;) {
total++;
boolean[] used = new boolean[n + 1];
Arrays.fill(used, true);
for (int i = 0; i < n; i++) {
System.out.print(currentab[i] + " ");
}
System.out.println();
used[currentab[n - 1]] = false;
int pos = -1;
for (int i = n - 2; i >= 0; i--) {
used[currentab[i]] = false;
if (currentab[i] < currentab[i + 1]) {
pos = i;
break;
}
}
if (pos == -1) {
break;
}
for (int i = currentab[pos] + 1; i <= n; i++) {
if (!used[i]) {
currentab[pos] = i;
used[i] = true;
break;
}
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
currentab[++pos] = i;
}
}
}
System.out.println(total);
}
}
the Question is how can I fix this programme to turn it into a programme that generates only the combinations wanted .
How about something simple like
public static void printSwapTwo(int n) {
int count = 0;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n - 1;i++)
for(int j = i + 1; j < n; j++) {
// gives all the pairs of i and j without repeats
sb.setLength(0);
for(int k = 1; k <= n; k++) sb.append(k);
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, tmp);
System.out.println(sb);
count++;
}
System.out.println("total=" + count+" and should be " + n * (n - 1) / 2);
}