Comparing elements in row and columns, in this case 1 and 0 - java

I've created a 2 dimensional array with the same length and it is randomly filled with 1 and 0 for example.
0100
0010
1110
1111
How do I code the program to find the rows,columns and diagonals with all 1s and 0s
This is my code so far:
public class Test2dArray {
public static void main(String[] args) {
int row,column;
System.out.print("Enter the lenghth of matrix:");
Scanner input = new Scanner(System.in);
Random rand = new Random ();
int mSize = input.nextInt();
int [][] mArray = new int [mSize][mSize];
for (row=0; row < mSize; row++){
for(column=0; column < mSize; column++){
mArray[row][column]=rand.nextInt(2);
System.out.print(mArray[row][column]+ " ");
}
System.out.println();
}
}
}

Code isn't perfect (I'm sure it can be optimized) but it works
public static void main (String[] args) throws java.lang.Exception {
int row = 5;
int column = 5;
int [][] mArray = fillArray(row, column);
System.out.println("Rows: " + findRows(mArray));
System.out.println("Columns: " + findColumns(mArray));
System.out.println("Diags: " + findDiags(mArray));
}
private static ArrayList<Integer> findRows(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < mArray.length; i++){
boolean isRow = true;
for(int j = 0; j < mArray[0].length; j++){
if (j > 0 && mArray[i][j] != mArray[i][j - 1]) {
isRow = false;
break;
}
}
if (isRow) result.add(i);
}
return result;
}
private static ArrayList<Integer> findColumns(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int j = 0; j < mArray[0].length; j++){
boolean isColumn = true;
for(int i = 0; i < mArray.length; i++){
if (i > 0 && mArray[i][j] != mArray[i - 1][j]) {
isColumn = false;
break;
}
}
if (isColumn) result.add(j);
}
return result;
}
private static ArrayList<Integer> findDiags(int [][] mArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 1; i < mArray.length; i++) {
boolean isDiag = true;
for (int j = 0; j < i; j++) {
if (mArray[i - j][j] != mArray[i - j - 1][j + 1]) {
isDiag = false;
break;
}
}
if (isDiag) result.add(i);
}
for (int i = 0; i < mArray.length - 2; i++) {
boolean isDiag = true;
for (int j = i + 1; j < mArray.length - 1; j++) {
if (mArray[mArray.length - j + i][j] != mArray[mArray.length - j + i - 1][j + 1]) {
isDiag = false;
break;
}
}
if (isDiag) result.add(mArray.length + i);
}
return result;
}
private static int[][] fillArray(int row, int column) {
int [][] mArray = new int [row][column];
Random rand = new Random();
for (int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
mArray[i][j] = rand.nextInt(2);
System.out.print(mArray[i][j] + " ");
}
System.out.println();
}
return mArray;
}

Iterate and for each row and columns and sum the values into rowSum and columSum.
So:
if (rowSum == mSize)
System.out.print("The row "+i+"is full of ones");
if (rowSum == 0)
System.out.print("The row "+i+"is full of zeros");
And the same, obviously, for the columns and diagonals.

Related

printing a symmetrical 2d array

I want to randomly generate a symmetrical 10x10 table with "*" symbols but It all basically prints in two long rows. I know I'm doing something wrong but I'm looking at it too hard and cant see the issue.
public class Main {
public static void main(String[]args) {
int n = 10;
char[][] array = new char[n][n];
Random rd = new Random();
for(int i = 0; i < n; i++) {
for(int j = 0; j < i; j++) {
char value;
if (Math.random()> .5) {
value = '*';
}
else {
value = ' ';
}
array[i][j] = value;
array[j][i] = value;
System.out.print(array[i][j]);
System.out.println();
System.out.print(array[j][i]);
}
}
}
}```
I don't see your context here. But you can try this
public class Main {
public static void main(String[] args) {
int n = 10;
char[][] array = new char[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
char value;
if (Math.random() > .5) {
value = '*';
} else {
value = ' ';
}
array[i][j] = value;
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
you're not printing row by row, also missing the diagonal element. Fixing those and some other minor changes
int n = 10;
char[][] matrix = new char[n][n];
Random rd = new Random();
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
char value = rd.nextBoolean() ? '*':' ';
matrix[i][j] = value;
matrix[j][i] = value;
}
}
for(char[] row : matrix) {
System.out.println(row);
}

Using for loop to find an element that appears multiple times in a random, unsorted array

My goal is to print out a user input value (and its corresponding index) if it appears 1 or more times in a random generated array of 50 integers. If I search the array for a value, and it happens to appear more than once, however, only one location of the element is printed, and then the if-else statement is executed. If I remove the break at the end of the third for loop, the whole thing falls apart. I've attached an image but here is the part of it that is giving me an issue. Apologies if the code is not clean, I'm very new.
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate 50 random integer unsorted list.\n");
Scanner stdin = new Scanner(System.in);
int[] randomNumbers = new int[50];
for(int index = 0; index < randomNumbers.length; index++) {
randomNumbers[index] = (int) (Math.random()*100);
}//end for
int count = 0;
for(int i = 0; i < randomNumbers.length; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if(count == 10) {
System.out.println();
count = 0;
}
}//end for
System.out.println("\nSearch value?");
int x = stdin.nextInt();
int i;
for(i = 0; i < randomNumbers.length; i++) {
if(randomNumbers[i] == x)
break;}
if (i != randomNumbers.length) {
System.out.println("\nFound " + x + " in array [" + i + "]");}
else {
System.out.println(x + " is not in the list");}
{int temp;
int size = randomNumbers.length;
for(i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(randomNumbers[i]>randomNumbers[j]){
temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
System.out.println("\nSmallest element of the array is: " + randomNumbers[0]);}
System.out.println("\n3. Sort the list:");
int size = randomNumbers.length;
for(i=0; i<size; i++)
{
for(int j=i+1; j<size; j++)
{
if(randomNumbers[i] > randomNumbers[j])
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
System.out.print("Now the Array after Sorting is :\n\n");
int count1 = 0;
for(i=0; i<size; i++)
{
System.out.print(randomNumbers[i]+ ",");
count++;
if(count == 10) {
System.out.println();
count = 0;
}
}
}
}
if statement in for loop
Implementing the comments to your question:
import java.util.Scanner;
public class NumCount {
private static final int RANDOM_NUMBER_COUNT = 50;
private static void display(int[] randomNumbers) {
int count = 0;
for (int i = 0; i < RANDOM_NUMBER_COUNT; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
}
private static int[] generateRandomNUmbers() {
int[] randomNumbers = new int[RANDOM_NUMBER_COUNT];
for (int index = 0; index < RANDOM_NUMBER_COUNT; index++) {
randomNumbers[index] = (int) (Math.random() * 100);
}
display(randomNumbers);
return randomNumbers;
}
private static int search(int[] randomNumbers, int x) {
int i;
int count = 0;
for (i = 0; i < randomNumbers.length; i++) {
if (randomNumbers[i] == x) {
System.out.println("\nFound " + x + " in array [" + i + "]");
count++;
}
}
return count;
}
private static int[] sort(int[] randomNumbers) {
int size = randomNumbers.length;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (randomNumbers[i] > randomNumbers[j]) {
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
return randomNumbers;
}
/**
* Start here.
*/
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate " + RANDOM_NUMBER_COUNT + " random integer unsorted list.\n");
int[] randomNumbers = generateRandomNUmbers();
System.out.print("\n2. Search value? ");
Scanner stdin = new Scanner(System.in);
int x = stdin.nextInt();
int count = search(randomNumbers, x);
if (count == 0) {
System.out.println(x + " is not in the list");
}
System.out.println("\n3. Sort the list:");
sort(randomNumbers);
System.out.print("Now the Array after Sorting is :\n\n");
display(randomNumbers);
}
}
Of-course there is no need to search for the smallest number because it will be the first element in the sorted array. Hence I removed that part of your code.

Ranking array Java

I am trying to rank my array in my assignment but I don't understand how to do it. Can someone help me? Thank you in advance
I added an image of the full assignment instructions.
Here is an image of my assignment:
And here is my code:
public class Assignment_3_Question_1 {
// Here, I predefined my data set.
static int referenceScore[][]={{39,40,17,35,42,6},{40,41,27,41,42,36},{42,40,26,42,42,35}};
static int finalScore[][]={{39,40,17,35,42,6},{40,41,27,41,42,36},{42,40,26,42,42,35}};
static int scoreAmongOthers[][]=new int[3][6];
static int max;
static int rank = 1;
static int count = 0;
static int total = 0;
public static void main(String[] args) {
for (int k = 0; k < 10; k++){
max = referenceScore[0][0];
for (int team = 0; team < 3; team++){
for (int position = 0; position < 6; position++){
if (max < referenceScore[team][position]){
max = referenceScore[team][position];
}
}
}
for (int x = 0; x < 3; x++){
for(int y = 0; y < 6; y++){
if(referenceScore[x][y]==max){
scoreAmongOthers[x][y]=rank;
referenceScore[x][y]=0;
count++;
}
}
}
rank = count + 1;
}
// Print out the
System.out.println("\tP1\tP2\tP3\tP4\tP5\tP6\tTotal\tRank");
// Prints out the results and the rank for each team
for(int teamNb = 0; teamNb<3; teamNb++){
System.out.print("Team"+(teamNb+1));
for(int p=0; p<6; p++){
total = total + finalScore[teamNb][p];
System.out.print("\t" + finalScore[teamNb][p]+"("+ scoreAmongOthers[teamNb][p]+") ");
}
System.out.print("\t"+ total);
total = 0;
System.out.println();
}
}
}
So I understand that the point of the exercise is to practice working with arrays. You have outlined the required algorithm in your comment. Here is my implementation.
public class RankScores {
private static int getRank(int[][] scores, int rowIndex, int columnIndex) {
int count = 0;
int score = scores[rowIndex][columnIndex];
for (int row = 0; row < scores.length; row++) {
for (int col = 0; col < scores[row].length; col++) {
if (scores[row][col] > score) {
count++;
}
}
}
return count + 1;
}
private static int getTeamRank(int[] scores, int index) {
int count = 0;
int score = scores[index];
for (int i = 0; i < scores.length; i++) {
if (scores[i] > score) {
count++;
}
}
return count + 1;
}
public static void main(String[] args) {
int referenceScore[][]={{39,40,17,35,42,6},{40,41,27,41,42,36},{42,40,26,42,42,35}};
int ranks[][] = new int[referenceScore.length][];
int totals[] = new int[referenceScore.length]; // total score for each team
int teamRanks[] = new int[referenceScore.length];
for (int row = 0; row < ranks.length; row++) {
ranks[row] = new int[referenceScore[row].length];
totals[row] = 0;
for (int col = 0; col < ranks[row].length; col++) {
ranks[row][col] = getRank(referenceScore, row, col);
totals[row] += referenceScore[row][col];
}
}
for (int team = 0; team < teamRanks.length; team++) {
teamRanks[team] = getTeamRank(totals, team);
}
System.out.println(" P1 P2 P3 P4 P5 P6 Total Rank");
for (int row = 0; row < ranks.length; row++) {
System.out.print("Team " + (row + 1) + " ");
for (int col = 0; col < ranks[row].length; col++) {
System.out.printf("%2d(%2d) ", referenceScore[row][col], ranks[row][col]);
}
System.out.println(" " + totals[row] + " " + teamRanks[row]);
}
}
}
Running the above code produces the following output.
P1 P2 P3 P4 P5 P6 Total Rank
Team 1 39(11) 40( 8) 17(17) 35(13) 42( 1) 6(18) 179 3
Team 2 40( 8) 41( 6) 27(15) 41( 6) 42( 1) 36(12) 227 1
Team 3 42( 1) 40( 8) 26(16) 42( 1) 42( 1) 35(13) 227 1

How can I read numbers from a .txt file and put them into a 2-D array?

This is for a school project. I need to read numbers from a .txt file and put them into an array. After they're in an array, I need to pass it into a different class to do the math and compare the numbers. The only problem is, I can't get the code to read the .txt file or make it into an array.
I need to use
if (sq.isMagicSquare())
to pass the array to class Square, but it gives the error:
required: int[][]
found: no arguments
reason: actual and formal lists differ in length
public class MagicSquareTester
{
public static void main() throws IOException
{
Square sq = null;
System.out.println("Enter the name of your data file (magicData.txt):");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.nextLine(); // input data file name from keyboard
Scanner inFile = new Scanner(new File (fileName));
int sqSize = inFile.nextInt(); // read the size
while (sqSize != -1)
{
sq = new Square(sqSize, inFile);
if (sq.isMagicSquare()) //will return true or false
System.out.println("\tWe have a Magic Square!");
else
System.out.println("\tThis is NOT a Magic Square.");
System.out.println(sq);
System.out.println();
sqSize = inFile.nextInt();
}
System.out.println("Of the " + sq.getTotalTested() + " squares tested " + sq.getMagicCount() + " were magic square(s)" );
}
}
public class Square
{
Scanner scan = new Scanner(System.in); //has been imported correctly, btw
int tested = 0, areMagic = 0, sqSize;
boolean magic;
int[][] Square;
public Square(int sqSize, Scanner inFile)
{
Square = new int [sqSize] [sqSize];
}
public void readSquare(Scanner inFile)
{
for(int row = 0; row < sqSize; row++)
for(int col = 0; col < sqSize; col++)
{
Square[row][col] = inFile.nextInt();
tested++;
}
}
public boolean isMagicSquare(int[][] array)
{
Sums testMagic = new Sums();
int rows = testMagic.sumRows(array);
int cols = testMagic.sumCol(array);
int diagonals = testMagic.sumDiagonal(array);
if((rows == cols) && (cols == diagonals) && (diagonals == rows))
{
magic = true;
areMagic++;
}
else
magic = false;
return magic;
}
public int getMagicCount()
{
return areMagic;
}
public int getTotalTested()
{
return tested;
}
}
public class Sums
{
int sum = 0, lastSum = 0, counter1, counter2, counter3;
boolean magic = true;
public int sumRows(int [][] array)
{
for (int row = 0; row < array.length; row++)
{
sum = 0;
for (int col = 0; col < array.length; col++)
{
sum += array[row][col];
System.out.print(sum + " ");
if (lastSum == sum)
{
lastSum = sum;
counter1++;
}
else if (lastSum != sum)
{
magic = false;
System.out.println("This is not a magic square");
row = array.length;
col = array.length;
}
}
}
return counter1;
}
public int sumCol(int [][] array)
{
for (int col = 0; col < array.length; col++)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
sum += array[row][col];
System.out.print(sum + " ");
if (lastSum == sum)
{
lastSum = sum;
counter2++;
}
else if (lastSum != sum)
{
magic = false;
System.out.println("This is not a magic square");
row = array.length;
col = array.length;
}
}
}
return counter2;
}
public int sumDiagonal(int [][] array)
{
int diagonal1 = 0, diagonal2 = 0;
for (int col = 0; col < array.length; col++)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
if(row == col)
{
sum += array[row][col];
System.out.print(sum + " ");
diagonal1 = sum;
}
}
}
for (int col = 0; col < array.length; col--)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
if((row + col) == array.length - 1)
{
sum += array[row][col];
System.out.print(sum + " ");
diagonal2 = sum;
}
}
}
if(diagonal1 == diagonal2)
{
magic = true;
counter2 = counter3;
}
else
counter3 = 0;
return counter3;
}
}
Also, apologies if my code looks weirdly formatted. I've never posted here before and I'm doing my best.
I suggest you use java.io.file and separate the squaring and parsing operations from the file reading operations.
Possibly like follows:
public class MathSquareTester {
public static void main (String[] args) throws IOException {
List<Integer> squaredNums = new ArrayList<Integer>();
FileInputStream in = new FileInputStream(file_name);
BufferedReader reader = new BufferedReader(new FileReader(in));
String line = reader.readLine();
while (line != null) {
//Assuming each line represents a separate integer
squaredNums.add((int)Math.pow(Integer.parseInt(line)), 2);
line = reader.readLine();
}
int[] numsArray = new int[squaredNums.size];
squaredNums.toArray(numsArray);
//All of your numbers are now stored in numsArray
}
}

How to change an array of ints to an array of strings?

Ok, the title might be deceiving. All i want to do is take my Bingo program and when the second bingo card is printed, i want to replace all the "0"'s with "X"'s. I was thinking i would have to go and change the array to an string, but i'm not surer where to start.
Here is the Bingo program:
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Bingo
{
public static final int ROWS = 5;
public static final int COLS = 5;
public static final int VERTICAL = 1;
public static final int DIAGONAL = 2;
public static final int HORIZONTAL = 3;
public static int winFound;
public static int currPick = 0;
public static int randomPick = 0;
public static int WinFound;
public static void main(String[] args)
{
int Totcards;
int[][] card = new int[ROWS][COLS];
int[] picks = new int[25];
fillCard (card);
printCard(card);
playGame(card);
printCard(card);
finalCard(card);
}
private static void fillCard (int[][] card)
{
// FileReader fileIn = new FileReader("Bingo.in");
// Bufferreader in = new Bufferreader(fileIn);
try {
Scanner scan = new Scanner(new File("bingo.in"));
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
card[i][j] = scan.nextInt();
}
}
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
}
private static void printCard (int[][] card)
{
System.out.println("\n\tYOUR BINGO CARD : ");
System.out.println("\n\tB I N G O");
System.out.println("\t----------------------");
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
System.out.print("\t" + card[i][j]);
}
System.out.print("\n");
}
}
private static void playGame (int[][] card)
{
int numPicks = 0;
System.out.println("\n\tBINGO NUMBERS PICKED AT RANDOM FROM BIN: ");
while (true)
{
markCard (card); // Generate a random num & zero-it out
winFound = checkForWin(card); // Look for zero sums
numPicks++;
if (winFound != 0)
{
if (winFound == 1)
{
System.out.print("\n\n\tYOU WIN WITH A VERTICAL WIN AFTER " + numPicks + " PICKS\n");
}
else if (winFound == 2){
System.out.print("\n\n\tYOU WIN WITH A DIAGONAL WIN AFTER " + numPicks + " PICKS\n");
}
else if (winFound == 3){
System.out.print("\n\n\tYOU WIN WITH A HORIZONTAL WIN AFTER " + numPicks + " PICKS\n");
}
announceWin (numPicks);
return;
}
}
}
private static void markCard (int[][] card)
{
int randomPick = (int) (Math.random() * 74) + 1;
for (int j = 0; j < ROWS; j++){
for (int k = 0; k < COLS; k++){
if (card[j][k]==randomPick)
card[j][k] = 0;}
}
System.out.print("\t " + randomPick + " ");
System.out.print("");
}
private static int checkForWin(int[][] card)
{
int sum=0;
for (int i = 0; i < ROWS; i++)
{
sum = 0;
for (int j = 0; j < COLS; j++)
sum += card[i][j];
if (sum == 0)
return HORIZONTAL;
}
for (int j = 0; j < COLS; j++)
{
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][j];
if (sum == 0)
return VERTICAL;
}
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][ROWS-i-1];
if (sum == 0)
return DIAGONAL;
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][i];
if (sum == 0)
return DIAGONAL;
return WinFound;
}
private static void makeCard(int[][] card, int[] picks)
{
int count = 100;
int currPick = 0;
for (int i=0; i<count; i++){
currPick = (int)(Math.random() * 74) + 1;
System.out.print(" " + currPick + "\n");
picks[i] = currPick;
}
}
private static void announceWin(int numPicks)
{
}
private static boolean duplicate (int currPick, int[] picks, int numPicks)
{
for (int i = 0; i < numPicks; i++){
if (picks[i] == currPick){
return true;}
}
return false;
}
private static void finalCard (int[][] card)
{
Arrays.sort(card);
final String stringRep = Arrays.toString(card);
final String[] out =
stringRep.substring(1, stringRep.length() - 1).split("\\s*,\\s*");
System.out.println(Arrays.toString(out));
}
}
Try this:
System.out.print("\t" + (card[i][j] == 0 ? "X" : card[i][j]))
Why don't you just use a String[][] for the fields from the beginning? You can still compare String values with ints (with Integer.valueOf for instance) and this way you don't have to switch types runtime...

Categories

Resources