Sudoku with Java Arrays
I am building a 9x9 2D array and trying to fill it by inputting a random 9 digits integer for each row. I want to insert each digit of that number as an element along the rows [0][0-8],[1][0-8]... I tried to convert the integer into a string and insert each character but I can't seem to figure it out.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
int Choise = scan.nextInt();
char c =(char)Choise;
int soduko[][] = new int[9][9];
for (int i = 0; i< soduko.length; i++){
for(int j =0; j< soduko.length; j++){
soduko[i][j]=c;
}
}
i have tried another way that still uses the number as an int, by taking the remainder of that number to the last cell in the row, and dividing the number by 10 each time in the loop. although its not working when i try to divide by 10 to get the next remainder.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
Choise = scan.nextInt();
for (int i =0; i <= soduko.length -1; i++){
for(int j = soduko.length -1; j > 0; j--){
int ChoiseDigit = Choise % 10;
soduko[0][j] = ChoiseDigit;
Choise = (int)(Choise / 10);
}
}
Building on your string conversion idea, you might benefit from using the split() method, which splits up a string based on a string you pass as an argument, and then returns an array of the split-up strings. So when you do split(""), the string is split up into single characters. Then you can parseInt to turn each string into an int. I would also recommend putting the scanner input in the loop, to make sure the user has to input a string 9 times.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
int soduko[][] = new int[9][9];
for (int i = 0; i< soduko.length; i++){
//reading a string of input 9 times and splitting them by "" into 1-character strings
String Choise[] = scan.nextLine().split("");
for(int j =0; j< soduko[i].length; j++){
//Integer.parseInt converts each string to an int so we can save it to the 2d array
soduko[i][j]= Integer.parseInt(Choise[j]);
}
}
Related
I want to read in a 6 digit number e.g 123456 using the scanner and store each digit in an array of digits.
System.out.println("Please enter a 6 digit code");
int code = keyboard.nextInt();
And then somehow put that into:
int [] array = {1,2,3,4,5,6};
I need the array to be int type because I am going to find the product when I add together the odd numbers in the sequence (1+3+5) and add the even numbers (2+4+6) (as per specifications of the program) I then have some conditions that tell me which number to concatenate onto the end.
I can achieve this by pre-defining an array of numbers but I want this number to come from the user.
Unless there is another way of doing this without using arrays? I appreciate any pointers.
Here is my code when i have pre-defined the array and it's values.
int code[] = {1,2,3,4,5,6};
//add the numbers in odd positions together
int sum_odd_position = 0;
for (int i=0; i<6; i+=2)
{
sum_odd_position += code[i];
}
//convert the initial code into strings
String string_code = "";
String seven_digit_code = "";
//add numbers in even positions together
int sum_even_position=0;
for (int i=1; i<6; i+=2)
{
sum_even_position += code [i];
}
//add them both together
int sum_odd_plus_even = sum_odd_position + sum_even_position;
//calculate remainder by doing our answer mod 10
int remainder = sum_odd_plus_even % 10;
System.out.println("remainder = "+remainder);
//append digit onto result
if (remainder==0) {
//add a 0 onto the end
for (int i=0; i<6; i+=2)
{
string_code += code [i];
}
}
else {
//subtract remainder from 10 to derive the check digit
int check_digit = (10 - remainder);
//concatenate digits of array
for (int i=0; i<6; i++)
{
string_code += code[i];
}
//append check digit to string code
}
seven_digit_code = string_code + remainder;
System.out.println(seven_digit_code);
}
}
Start by reading in a string from the user. Create an array to put the digits into. Iterate through the string character by character. Convert each character to the appropriate int value and put it into the array.
String line = keyboard.nextLine();
int[] digits = new int[line.length()];
for (int i = 0; i < digits.length; ++i) {
char ch = line.charAt(i);
if (ch < '0' || ch > '9') {
throw new IllegalArgumentException("You were supposed to input decimal digits.");
}
digits[i] = ch - '0';
}
(Note also that there are various ways to parse a char as an int if ch-'0' does not suit your purposes.)
To send messages to the user:
System.out.println("Hello, please enter a 6 digit number: ");
To ask for input, make a scanner once and set the delimiter:
// do this once for the entire app
Scanner s = new Scanner(System.in);
s.useDelimiter("\r?\n");
Then to ask for stuff:
int nextInt = s.nextInt();
String nextString = s.next();
Pick whatever data type you want, and call the right nextX() method for this.
This sounds like you should be asking for a string and not a number (Because presumably 000000 is valid input, but that isn't really an integer), so you'd use next().
To check if it's 6 digits, there are many ways you can go. Presumably you need to turn that into an array anyway, so why not just loop through every character:
String in = s.next();
if (in.length() != 6) throw new IllegalArgumentException("6 digits required");
int[] digits = new int[6];
for (int i = 0; i < 6; i++) {
char c = in.charAt(i); // get character at position i
int digit = Character.digit(c, 10); // turn into digit
if (digit == -1) throw new IllegalArgumentException("digit required at pos " + i);
digits[i] = digit;
}
If you want to be less english/western-centric, or you want to add support for e.g. hexadecimal digits, there's some utility methods in Character you can use instead:
if (digit == -1) throw new IllegalArgumentException("digit required");
First, allocate a scanner and an array for the digits
Scanner input = new Scanner(System.in);
int[] digits = new int[6];
Prompt for the integer.
Use Math.log10 to check for proper number of digits
otherwise, re-prompt
then using division and remainder operators, fill array with digits. Filling is done in reverse to maintain order.
for (;;) {
System.out.print("Please enter six digit integer: ");
int val = input.nextInt();
// a little math. Get the exponent of the number
// and assign to an int. This will determine the number of digits.
if ((int) Math.log10(val) != 5) {
System.out
.println(val + " is not six digits in size.");
continue;
}
for (int i = 5; i >= 0; i--) {
digits[i] = val % 10;
val /= 10;
}
break;
}
System.out.println(Arrays.toString(digits));
For input of 123456 Prints
[1, 2, 3, 4, 5, 6]
[SOLVED]
The title of this question is vague but hopefully this will clear things up.
Basically, what I am looking for is a solution to rotating this set of data. This data is set up in a specific way.
Here is an example of how the input and output would look like:
Input:
3
987
654
321
Output:
123
456
789
The '3' represents the number of columns and rows that will be used. If you input the number '4', you will be allowed to input 4 sets of 4 integers.
Input:
4
4567
3456
2345
1234
Output:
1234
2345
3456
4567
The goal is to find a way to rotate the data only if needed. You have to make sure the smallest corner number is at the top left. For example, for the code above, you rotated it so 1 is at the top left.
The problem I have is that I don't know how to rotate the data. I am only able to rotate the corners but not the sides. This is what my code does so far:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
I just do not know how to compare those characters and in the end rotate the data.
Any help would be appreciated! Any questions will be answered.
A detailed description of the problem is here(problem J4).
This is just a challenge I assigned myself for practice for next year's contest, so giving me the answer won't "spoil" the question, but actually help me learn.
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = kb.nextInt();
int maxSqrt = (max * max);
int num[] = new int[max];
String num_string[] = new String[max];
char num_char[] = new char[maxSqrt];
int counter = 0;
int counter_char = 0;
for (counter = 0; counter < max; counter++) {
num[counter] = kb.nextInt();
}
for (counter = 0; counter < max; counter++) {
num_string[counter] = Integer.toString(num[counter]);
}
int varPos = 0, rowPos = 0, charPos = 0, i = 0;
for (counter = 0; counter < maxSqrt; counter++) {
num_char[varPos] = num_string[rowPos].charAt(charPos);
i++;
if (i == max) {
rowPos++;
i = 0;
}
varPos++;
if (charPos == (max - 1)) {
charPos = 0;
} else {
charPos++;
}
}
//
for(int a = 0 ; a < max ; a++){
for(int b = 0 ; b < max ; b++)
{
num_char[counter_char] = num_string[a].charAt(b);
counter_char++;
}
}
//here is where the code should rotate the data
}
}
This is a standard 90 degree clockwise rotation for a 2D array.
I have provided the solution below, but first a few comments.
You said that you're doing this:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
Firstly youre essentially turning a int matrix into a character matrix. I do not think you need to do this, since even if you do want to compare values, you can use the ints provided.
Secondly, there is no need to compare any 2 data elements in the matrix, since the rotation does not depend on any value.
Here is an adapted solution for java, originally written in C# by Nick Berardi on this question
private int[][] rotateClockWise(int[][] matrix) {
int size = matrix.length;
int[][] ret = new int[size][size];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
ret[i][j] = matrix[size - j - 1][i]; //***
return ret;
}
If you wanted to do a counterCW rotation, replace the starred line with
ret[i][j] = matrix[j][size - i - 1]
I'm trying to make a program that will make square matrices based on user input. I know that arrays exist, but I wanted to make a matrix from scratch so that I could better understand the basic concept of it and further extend my understanding of loops. So far I have been able to make a square matrix that will accept one number as an input into that matrix, for example I input a square 2x2 matrix and while I want it to look like this 1 2 3 4 with 1 and 2 being above 3 and 4. I have only gotten it to accept one user input that it places in all four slots. For example, if my user input is 1 then the matrix looks like this 1 1
1 1
My code looks like this thus far:
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
for (int k = 0; k < number; k = k +1)
{
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.print(matrix_number);
}
System.out.println();
}
}
I believe that my problem lies in my first for loop where I have the user input the matrix number. Any helpful suggestions on how I can better write this so that the user can input a different number for each slot in the matrix?
It looks like you are trying to create a matrix and then populate it with values read from the user.
To create an N x N matrix of integers
int[][] matrix = new int[n][n]();
To assign a value to a matrix cell [i, j]:
matrix[i][j] = someValue;
Obviously, if you want to read a different value for each cell, you need to call nextInt() multiple times; i.e. once for each value you want to read.
(Note to other readers: I'm not coding this for the OP, because he will learn more by coding it himself.)
You can create a matrix using 2 dimensional arrays:
int[][] matrix = new int[row][column]; //row is the number of matrix rows
//column is the number of matrix columns
To access the elements of the matrix and define it after the declaration, you can use a nested for loop:
for (i = 0; i < row; i++ )
for (j = 0; j < column; j++)
{
scores[i][j] = value; // value is your chosen integer for that index
}
}
As you mention in your question, user has to input only onces and that it places in all four slots.
For example, if user input is 1 then the matrix looks like this 1 1 1 1.
Then no need for first for loop, just remove it.
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.print(matrix_number);
}
System.out.println();
}
You want the user to say the size of the square matrix, then you want the user to tell you every number in the matrix. You only need two loops here:
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
System.out.print(matrix_number);
}
System.out.println();
}
If you don't want your matrix polluted by "What are the numbers in your matrix?" questions, then you're going to need to learn how to store user input into some sort of data structure. As you said in your question, arrays are a great way to do this (as are 2d arrays).
If you were willing to learn file input or file output, then you could do what you seek without "storing" the numbers in an array. Either read the numbers in from a file and output them to the screen, or have the user type them as user input and output the matrix to a file.
Edit: You could try to erase the "What are the numbers in your matrix?" system out by printing backspace characters on linux systems. More here:
How to delete stuff printed to console by System.out.println()?
I have to input 5 int arrays, in less than 3 sec, means execution time should be less than 3,and i was using Scanner class or that,but it is making the execution time more,so is there any other possible way,i have to get input as
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
And have to input 1 2 3 in one line ?how would i do it..?
i was taking initially string as input ,and then using split(" ") method for separating it,then parsing it using wrapper classes? any other way to do it?
Try the following snippet, I guess its what you may be looking for inputting 2d array without splitting the string using Scanner..
int[][] array = new int[5][2];
Scanner scan = new Scanner(System.in);
int i=0;
int k=0;
while(scan.hasNextInt()){
array[i][k] = scan.nextInt();
k++;
if(k == 2) {
k = 0;
i++;
}
if(i == array.length){
break;
}
}
for(int p=0; p < array.length; p++) {
for(int j=0;j < 2; j++) {
System.out.print(array[p][j] + " ");
}
}
Given the 2d array:
double[][] table;
table = new double[4][5];
I know how to print the array with 20 0's using:
for (int ii = 0 ; ii < table.length ; ii++)
{
for (int jj = 0 ; jj < table[0].length ; jj++)
{
System.out.print(table[ii][jj] + "\t");
}
System.out.println("");
}
I would like to ask the user to input "1,2,3" where 1 is the row, 2 is the column and 3 is the value that goes in the cell. Please help me how to do this using the string split method. Thank you!
String numString = "1,2,3";
String[] splitString = numString.split(",");
int num1 = Integer.parseInt(splitString[0]);
int num2 = Integer.parseInt(splitString[1]);
int num3 = Integer.parseInt(splitString[3]);
table = new double[4][5];
table[num1][num2] = num3;
That's easy if you go step by step:
use Scanner class on System.in to read a line through nextLine()
split the String according to the given delimiter (",")
check if amount of tokens is correct
convert each token to an int through Integer.parseInt(..)
set the correct value through table[x][y] = v