I have written the java code but it is not giving any output.Could anyone help me with the solution.thank you.I have provided the input and the output.
Here is the code-
Input-
5 4
OXOO
OOOX
OOXO
XOOO
XXOO
Output-
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1
0 0 0 1
import java.util.*;
public class ratMaze {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
char[][] ch = new char[N][M];
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
ch[i][j]=sc.next().charAt(0);
}
}
int[][] visited = new int[N][M];
boolean res=ratmaze(ch,0,0,visited);
if(res)
print(visited,N,M);
else
System.out.print("-1");
}
private static boolean ratmaze(char[][]ch,int row,int col,int[][] visited)
{
if(row==ch.length-1 && col==ch[0].length-1)
return true;
if(row==ch.length || col==ch[0].length || ch[row][col]=='X' || visited[row][col]==1)
return false;
visited[row][col]=1;
//Right
ratmaze(ch,row,col+1,visited);
//Down
ratmaze(ch,row+1,col,visited);
visited[row][col]=0;
return true;
}
private static void print(int[][] visited,int row,int col)
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.print(visited[row][col]+" ");
}
System.out.println();
}
}
}
There are two issues with your code. First comes from the way you read input characters. Scanner.next() returns a whole token. In this context, a token is a "word" - something limited by whitespaces or start/end of a line. In your example input "OXOO" is one token. You need to modify your your reading in such a way that token is read in the outer loop and then access characters at specific positions. You could do something like this:
for (int i = 0; i < N; i++) {
String token = sc.next();
for (int j = 0; j < M; j++) {
ch[i][j] = token.charAt(j);
}
}
It "worked" the way you did it but required each character to be separated by whitespace.
After fixing that you will get an ArrayIndexOutOfBoundsException in print() method. You should use i and j while printing the array, not row and col.
This will result in some output. I'm not sure if it is the output you expected.
Related
I want it to take 10 values from the keyboard and find out if any of the 10 inputs contain 0 or 1 and if so, What position is in the array?
example
Input = 9 15 91 1 0 22 31 67 88 33
output = 4 found number 1, at position 2 3 4 7
1 found number 0, at position 5
5 found others, at position 1 6 8 9 10
I can't write any further because I still don't understand. Advise me please
I tried to write it but the output is still not correct.
public static int SequentialSearch(int number[], int key_1, int key_0) {
int looker;
for (looker = 0; looker < number.length; looker++) {
if (number[looker] == key_1)
return looker;
if (number[looker] == key_0)
return looker;
}
return -1;
}
public static void Loopcheck(int number[]) {
int key_1, key_0, others_key;
for (int count_check = 0; count_check < number.length; count_check++) {
if (number[count_check] / 10 == 1 || number[count_check] % 10 == 1) {
key_1 = 1;
break;
} else if (number[count_check] / 10 == 0 || number[count_check] % 10 == 0) {
key_0 = 0;
break;
}
}
}
public static int Print(int number[], int location) {
for (int loop = 0; loop < number.length; loop++)
if (location > -1)
System.out.print(" 0 : " + location);
return 0;
}
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
int value1, value0, location, key1;
int[] number = new int[10];
for (int count = 0; count < number.length; count++) {
number[count] = Sc.nextInt();
}
int item1 = 1;
int item0 = 0;
location = SequentialSearch(number, item1, item0);
Loopcheck(number);
Print(number, item1);
}
}
you can use a method like this,
public void haszero(int numbers[])
{
int position;
for(position = 0; position < numbers.size; position++)
{
while(numbers[position] > 0)
{
if(numbers[position] % 10 == 0)
system.out.print("0 at " position)
number=number/10;
}
}
}
and then you can use same method as this for 1.
or the you can also do something like this
for(int position = 0; position < array.size; position++)
{
if (String.valueOf(array[position]).contains("0"))
system.out.print("0 at " position);
}
Since you are looking for a specific character, I would recommend working on String or char array instead. Some code you can consider that will probably give you an idea how to solve a problem:
//part 1
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
// part 2
String Input = String.join(" ",Integer.toString(a),Integer.toString(b),Integer.toString(c));
System.out.println(Input);
// part 3
int i = 0;
while(i<Input.length()){
if(Input.charAt(i)=='0') System.out.println(String.join(" ","0 at position",Integer.toString(i+1)));
if(Input.charAt(i)=='1') System.out.println(String.join(" ","1 at position",Integer.toString(i+1)));
i++;
}
The most impactful advice I would provide is:
store your input as string or char[] instead of int[].
To solve: Create a collection(like a list, or array) to hold your valid indexes, and iterate through your input one letter at a time, adding valid indexes to your collection as they satisfy your condition. Implement a 'PrettyPrint()' that converts your collection into a nice output.
I went ahead a coded a solution that used int arrays. Here are the test results from one of my later tests.
Type 10 values: 0 1 2 3 4 5 6 7 8 9
1 found number 1, at position 2
1 found number 0, at position 1
8 found others, at position 3 4 5 6 7 8 9 10
Type 10 values: 12 23 34 45 127 21 84 0 73 364
3 found number 1, at position 1 5 6
1 found number 0, at position 8
6 found others, at position 2 3 4 7 9 10
Type 10 values:
To exit the program, you just press the Enter key.
My process was to maintain three int arrays. One held the indexes of all the ones. One held the indexes of all the zeros. One held the indexes of all the other values.
I wrote this code step by step, testing each step along the way. I probably ran two or three dozen tests, each testing one small part of the code.
The first thing I did was to get the input loop working correctly. I didn't test for non-numeric input, but that test could be added easily. I didn't limit the input to 10 numbers either. You can type 15 or 20 numbers if you want. Finally, I didn't limit the input to two-digit numbers. The code that looks for a digit should work for any positive integer value.
Next, I wrote a method to determine whether a number contained a particular digit. The method works with any digit, not just zero or one.
After that, it was a matter of getting the output to look correct.
Here's the complete runnable code.
import java.util.Scanner;
public class ZeroAndOne {
public static void main(String[] args) {
new ZeroAndOne().processInput();
}
public void processInput() {
Scanner scanner = new Scanner(System.in);
String line;
do {
System.out.print("Type 10 values: ");
line = scanner.nextLine().trim();
String[] parts = line.split("\\s+");
if (!line.isEmpty()) {
int[] input = new int[parts.length];
for (int index = 0; index < parts.length; index++) {
input[index] = Integer.valueOf(parts[index]);
}
System.out.println(processArray(input));
}
} while (!line.isEmpty());
scanner.close();
}
private String processArray(int[] input) {
int[] zeros = new int[input.length];
int[] ones = new int[input.length];
int[] other = new int[input.length];
int zeroIndex = 0;
int oneIndex = 0;
int otherIndex = 0;
for (int index = 0; index < input.length; index++) {
boolean isOther = true;
if (isDigit(input[index], 0)) {
zeros[zeroIndex++] = index;
isOther = false;
}
if (isDigit(input[index], 1)) {
ones[oneIndex++] = index;
isOther = false;
}
if (isOther) {
other[otherIndex++] = index;
}
}
StringBuilder builder = new StringBuilder();
builder.append(oneIndex);
builder.append(" found number 1, at position ");
builder.append(appendIndexes(ones, oneIndex));
builder.append(System.lineSeparator());
builder.append(zeroIndex);
builder.append(" found number 0, at position ");
builder.append(appendIndexes(zeros, zeroIndex));
builder.append(System.lineSeparator());
builder.append(otherIndex);
builder.append(" found others, at position ");
builder.append(appendIndexes(other, otherIndex));
builder.append(System.lineSeparator());
return builder.toString();
}
private boolean isDigit(int value, int digit) {
if (value == 0 && digit == 0) {
return true;
}
while (value > 0) {
int temp = value / 10;
int remainder = value % 10;
if (remainder == digit) {
return true;
}
value = temp;
}
return false;
}
private StringBuilder appendIndexes(int[] array, int length) {
StringBuilder builder = new StringBuilder();
for (int index = 0; index < length; index++) {
builder.append(array[index] + 1);
if (index < (length - 1)) {
builder.append(" ");
}
}
return builder;
}
}
Assuming that your input is a line containing integer numbers separated by space, you could read them all and then loop the String items via:
String input = Sc.readLine().split(" ");
int positions[] = new int[input.length];
int zeros = 0;
String zeroString = "";
int ones = 0;
String oneString = "";
int others = 0;
String otherString = "";
for (String item : input) {
boolean isOther = true;
String appendix = " " + item;
if (item.indexOf("0") >= 0) {
isOther = false;
zeros++;
zeroString += appendix;
}
if (item.indexOf("1") >= 0) {
isOther = false;
ones++;
oneString += appendix;
}
if (isOther) {
others++;
otherString += appendix;
}
}
System.out.println(ones + " found number 1, at position " + oneString);
System.out.println(zeros + " found number 0, at position " + zeroString);
System.out.println(others + " found others, at position " + otherString);
How can I do in order to delete prime numbers not including 0 and 1 and I want to find just prime numbers excluding 0 and 1?Now if I have{0,1,3,5,8}----> after compiling it will find 0 and 1 as prime numbers ."Prime Number Found=0 Prime Number Found=1 Prime Number Found=3 Prime Number Found=5" Here's my program:
Thank you for your help.
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int i,j,size;
boolean status;
System.out.print("Enter size of array=");
size=s.nextInt();
int arr[]=new int[size];
int tmp[]=new int[size];
System.out.println("Enter Elements in array...");
for(i=0;i<size;i++)
{
arr[i]=s.nextInt();
}
for( i=0;i<size;i++)
{
status=true;
for(j=2;j<arr[i]-1;j++)
{
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
}
if(status==true)
{
System.out.println("Prime Number Found="+arr[i]);
}
}
System.out.println("New Array....");
for(i=0;i<size;i++)
{
System.out.println(tmp[i]);
}
}
}
Your code was full of problems, but in the code below I did fix the following major problems:
you were not handling the base case of 0 and 1 being not prime correctly
your loop for scanning for possible whole number divisors had the wrong bounds
you were not writing the found prime numbers correctly to the output array which you were printing at the end of the main() method.
Have a look at the code below for a sample of what you probably intended to do.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean status;
System.out.print("Enter size of array=");
int size = s.nextInt();
int arr[] = new int[size];
int tmp[] = new int[size];
System.out.println("Enter Elements in array...");
int primerCounter = 0;
for (int i=0; i < size; i++) {
arr[i] = s.nextInt();
}
for (int i=0; i < size; i++) {
status = true;
if (arr[i] == 0 || arr[i] == 1) {
status = false;
}
else {
for (int j=2; j <= arr[i]-1; j++) {
if (arr[i] % j ==0) {
status = false;
break;
}
}
}
if (status == true) {
tmp[primerCounter++] = arr[i];
System.out.println("Prime Number Found="+arr[i]);
}
}
System.out.println("New Array....");
for (int i=0; i < primerCounter; i++) {
System.out.println(tmp[i]);
}
}
For an input of the numbers from 0 to 20 inclusive, I got the following output:
{2, 3, 5, 7, 11, 13, 17, 19}
Your question is not very clear, but I am assuming your problem is that the code you posted considers 0 and 1 as prime numbers, and you don't want that. If that's the case. the error is that the check
(arr[i]==0)||arr[i]==1)
is within the for loop
for(j=2;j<arr[i]-1;j++)
In fact, when arr[i] is equal to 0 or 1, the condition
j<arr[i]-1
will evaluate to false immediately, because j=2 and arr[i]-1 evaluates to either -1 or 0. As a consequence, the code
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
will never be executed, and in the following loop
status==true
will evaluate to true.
One solution is to remove the check
arr[i]==0)||arr[i]==1
from where it is now and put it in the same if as the one whose condition is
status==true
after changing == with !=.
In a nutshell,
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
should become
if(arr[i]%j==0)
{
status=false;
tmp[i]=arr[i];
break;
}
and
if(status==true)
{
System.out.println("Prime Number Found="+arr[i]);
}
should become
if(status==true || arr[i]!=0 || arr[i]!=1)
{
System.out.println("Prime Number Found="+arr[i]);
}
There's another mistake in the code you posted: you use the same index i to iterate over arr and to select the elements of tmp to whom assign values. As not every element of arr is prime and will not therefore be copied to tmp, this results in an array tmp with some "holes", i.e, unassigned elements. You should keep a different index k initialized to 0 to access the elements of tmp and increment it manually:
tmp[k]=arr[i];
k++;
instead of
tmp[i]=arr[i];
Also, when you eventually iterate over tmp bear in mind that its size won't be the same as arr, but smaller (for the reason I have just explained). Thus,
for(i=0;i<size;i++)
{
System.out.println(tmp[i]);
}
should be replaced with
for(i=0; i < actual-size-of-tmp; i++)
{
System.out.println(tmp[i]);
}
below is my code and I don't know where I got wrong
It compiled well works well but, doesn't print the right result;;;
if N is 4 , the result should be
2 4 1 3
However, It printed
1 3 0 0
I guess there are something wrong in for-loop because when I do it with another value like 5 it also printed only two numbers
this is the result from N=5;
1 4 0 0 0
import java.util.Scanner;
public class NQueens{
public static int N ;
public static int [] cols;
public static void printcols(){
for(int i =1; i<=N; i++){
System.out.print(cols[i] + " ");
}
System.out.print("\n");
}
public static boolean promising(int level){
for(int i =1; i<level ; i++){
if(cols[i] == cols[level]){
return false;
}else if(level-i == Math.abs(cols[level]- cols[i]))
return false;
}
return true;
}
public static boolean queens(int level){
if(!promising(level)){
printcols();
return false;
}
else if(level == N){
printcols();
return true;
}
for(int i =1; i<N; i++){
cols[level+1] = i;
if(queens(level+1)){
return true;
}
}
return false;
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
cols = new int [N+1];
queens(0);
}
}
It does not just print 1 3 0 0, but prints every backtracking step, and at the end it doesn't find any solutions. The problem is that you are mixing 0-based and 1-based indices, and eventually made an error.
In the following line:
for(int i =1; i<N; i++){
you are iterating over only N-1 possibilities, leaving i == N out. So the fix is just to allow equality too:
for(int i =1; i<=N; i++){
With this modification the program works as intended.
Hi here's my problem i cant seem to print my outputs correctly i guess i'm having a logical error in my code, it doesn't print when i put an ascending number then a descending. i'm kind of new to programming too.
Code:
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
int n, i, k, j;
int asc = 0,
Scanner x = new Scanner(System.in);
do {
System.out.print("How many numbers to process : ");
k = x.nextInt();
if(k<=1) {
System.out.println("Enter a number greater than 1");
}
} while(k<=1);
System.out.printf("Please enter %d numbers: ",k);
n = x.nextInt();
for(i=0; i<n-1; i++) {
j = x.nextInt();
if( j < n) {
asc++; // is this right?
} else {
asc--;
}
}
if (asc==k) {
System.out.print("Not Growing Up.");
}
if (asc!=k) {
System.out.print("Growing Up.");
}
}
}
Here are the outputs
Example outputs (what i'm trying to get)
How many numbers to process : 4
Please enter 4 numbers : 1 2 3 4
Growing up.
How many numbers to process : 4
Please enter 4 numbers : 4 3 2 1
Not Growing up.
This is my problem :
How many numbers to process : 4
Please enter 4 numbers : 1 2 1 3
Growing up. // it should be not growing up.
There is no need to iterate through all numbers. You can just check if the previous number is lower (if growing). If not, print and return. Check my example code.
Replace
n = x.nextInt();
for (i=0; i<n-1; i++) {
j = x.nextInt();
if( j < n) {
asc++; // is this right?
} else {
asc--;
}
}
if (asc==k) {
System.out.print("Not Growing Up.");
}
if (asc!=k) {
System.out.print("Growing Up.");
}
With
int prev = x.nextInt();
for (i=0; i<k-1; i++) {
j = x.nextInt();
if (j < prev) { System.out.print("Not Growing Up."); return; }
prev = j;
}
System.out.print("Growing Up.");
String numbers = "1 2 3 4"; // Let's take this input for example
int temp = 0; // This use to compare previous integer
boolean isAsc = false; // This store whether the digits is growing up or not
StringTokenizer st = new StringTokenizer(numbers); // Declare StringTokenizer
while (st.hasMoreTokens()) {
int next = Integer.parseInt(st.nextToken()); // Put the first integer in next (1)
if(next > temp){ // if (1) > 0
temp = next; // Assign 1 to temp, next time digit 2 will compare with digit 1
isAsc = true; // Assign the ascending to true
} else
isAsc = false;
}
if(isAsc)
System.out.print("Growing up.");
else
System.out.print("Not growing up.");
}
Your can store the user input as a string like the variable numbers I've declared and break them into each token for compare purpose.
import java.lang.reflect.Array;
import java.util.*;
public class A1 {
public static void main(String[] args) {
int a[]={2,5,0,1};
Arrays.sort(a);
int b= a.length;
for(int i=0;i<a.length;i++)
{
System.out.println(+a[i]+"\t"+a[b-1]);
b--;
}
}
}
Hey guys. I've been strugling with a backtraking problem for hours. Can anyone lend me a hand? Here is the problem:
n camels numbered from 1 to n are the arranged order. I want to rearrange so that each camel has a diferent camel in front.
This is what I have so far:
import java.util.*;
public class NCamile{
static int size;
static int count;
static char[] arrN= new char[100];
public static void main(String[] args){
System.out.print("Enter word: ");
String numar = getInt();
size = numar.length();
count=0;
for(int i=0; i < size ; i++){
arrN[i] = numar.charAt(i);
}
backtraking(size);
}
public static void backtraking(int newsize){
if (newsize == 1){
return;
}
for(int i=0 ; i < newsize; i++){
backtraking(newsize - 1);
if(newsize == 2 ){
display();
}
rotate(newsize);
}
}
public static void rotate(int newsize){
int position = size - newsize;
for(int i = position + 1; i < newsize; i++){
char gigi;
gigi = arrN[i - 1];
arrN[i - 1] = arrN [i];
arrN[i] = gigi;
}
}
public static void display(){
if (count < 9){
System.out.print(" ");
}
System.out.print(++count+ ")" + " ");
for(int i = 0 ; i < size ; i++)
System.out.print(arrN[i]);
System.out.print(" ");
if(count % 10 == 0){
System.out.println(" ");
}
}
public static String getInt(){
Scanner scan = new Scanner(System.in);
String s = scan.next();
return s;
}
}
With this, the algorithems show me every posible solution to rearrange a string, but it dosen't respect the last condition of the problem. I've tried ading this:
for(int j = 0 ; j < size ; j++){
if (array[j] !=[array[j + 1] )
display()
}
But after I added it I got about 10 times more displayed words then it should have shown me
Can anyone give me an idea on what should I do?
If you're only asked to insure that
i) a single new arrangement is produced, and
ii)that new arrangement must satisfy the condition that each camel follows a camel different from the one it followed in the original arrangement,
then you can easily satisfy this just by reversing the list of camels.
Surely this is not optimized solution, but for simply gettin result I would consider checking all of the permutations. Method producing every permutation wouldn't be hard to write (see e.g. String permutation) and checking if some camel has the same backtraced won't be any effort at all.
--- edit
So... Few things mended, few not:
I worked on String, not char array. Char array is completely misunderstand in this problem. It's better to use String object (cause in fact, String is char array) or int array (this have been hard to me, cause I haven't found any permutation method to be applied with such parameter). So the main method looks now:
private static String word;
public static void main(String[] args)
{
System.out.print("Enter word: ");
Scanner scan = new Scanner(System.in);
word = scan.next();
permutation(word);
}
I deleted your class variables (length, count, etc...) cause they are unnecessary right now. Writing out String is quite simple and if you would like to change output format - use String.length property instead.
Permutation method is copied from mentioned source, and little modified. It looks following:
public static void permutation(String s)
{
permutation("", s);
}
private static void permutation(String prefix, String s)
{
int n = s.length();
if (n == 0)
{
if (camelFit(prefix))
System.out.println(prefix);
}
else
{
for (int i = 0; i < n; i++)
permutation(prefix + s.charAt(i),
s.substring(0, i) + s.substring(i + 1, n));
}
}
if you would uncomment line checking if (camelFit (prefix)) it would display every permutation of input String. But! We would like to print only these camel chains, which fits problem conditions. How do we check if given chain is so? Simple method:
private static boolean camelFit(String prefix)
{
for (int i = 0; i < word.length() - 1; i++)
{
char camel = word.charAt(i);
char camelFollow = word.charAt(i+1);
for (int j = 0; j < prefix.length() - 1; j++)
{
if (prefix.charAt(j)==camel && prefix.charAt(j+1)==camelFollow)
{
return false;
}
}
}
return true;
}
Maybe not so simple, because we have to check every pair of input chain (every follower and followed) with every pair of output chain. If there isn't any match between any two pairs - given chain is fine.
Please notice, that this solution is absolutely non-optimized. Finding permutations is O(n!) complexity and checking pairs is O(n^2) complexity. Final complexity is O(n^2)*O(n!) so very, very high.