Unable to get 2D array to shuffle - java

I'm working on Murach's Java Programming textbook exercise 11-4, and I've got the first two methods to work properly; however my shuffle method isn't working at all. Nothing happens.
public static String[] suits = {"C", "S", "H", "D"};
public static int[][] cards = new int[4][13];
public static int used[] = new int[13];
public static void loadCards() {
for(int i = 0; i < cards.length; i++) {
for(int j = 0; j < cards[i].length; j++){
cards[i][j] = j+1;
}
}
}
public static void writeCards() {
for(int i = 0; i < cards.length; i++) {
System.out.print(suits[i] +" ");
for (int j = 0; j < cards[i].length; j++) {
System.out.print(cards[i][j]+ " ");
}
System.out.println("");
}
}
public static void shuffle() {
for (int i = 0; i < cards.length; i++) {
shuffle:
for (int j = 0; j < cards[i].length; j++) {
double d = Math.random() * 13;
int random = (int) d;
for(int test = 0; test<used.length;test++){
if(random == used[test]) {
break shuffle;
}
}
cards[i][j] = random;
}
}
}
public static void main(String[] args) {
loadCards();
writeCards();
System.out.println("");
shuffle();
writeCards();
}
I feel like I'm starting to dig myself into a hole of wrong with the shuffle() method. Is there an easy fix I'm not seeing/am I trying something that's just absolutely wrong?

Can't write the shuffle code for you, but you can use something like bogo sort to shuffle how you want. The algorithm is used both for scrambling or shuffling, and for educational purposes to show why the efficiency of sorting algorithms is so important.

Solved it, thanks to Fred Larson for pointing me in the right direction.
public static void shuffle() {
for (int i = 0; i < cards.length; i++) {
for (int j = cards[i].length - 1; j > 0; j--) {
double d = Math.random() * 13;
int random = (int) d;
int a = cards[i][random];
cards[i][random] = cards[i][j];
cards[i][j] = a;
}
}
}

Related

How can I check if every single int in a randomly generated array is even and make it create another random array if it's not?

So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}

My matrix doesn’t change when I try to perform scalar multiplication

we're supposed to multiply every element in the matrix by a number, in this case "k". not sure what i'm doing wrong but it wont work. HELP! i have edited and added the whole project so far.
public class Matrix {
private int r;//rows
private int c;//columns
private int[][] neo; //2D array
public static void main(String[] args) {
Matrix m1 = new Matrix(3,4);
Matrix m2 = new Matrix(3,4);
System.out.println(m2);
try {
Matrix m3 = m1.multiply(m2);
} catch (Exception e) {
e.printStackTrace();
}
m2.scaleMult(k);
}//main
public Matrix(int row, int column) {
r = row;
c = column;
neo = new int[r][c];
for(int i = 0; i < neo.length; i++) {
for (int j = 0; j < neo[i].length; j++) {
neo[i][j] = (int) (1 + Math.random() * 100);
}//forLoop
}//forLoop
System.out.println(Arrays.toString(neo));
}//Matrix
public Matrix copyMatrix(Matrix m) {
Matrix copy = new Matrix(m.r, m.c);
for (int i = 0; i < r; i++) {
System.arraycopy(this.neo[i], 0, copy.neo[i], 0, this.neo[i].length);
}//forLoop
return copy;
}//copyMatrix
public void scaleMult(int k){
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
this.neo[i][j] * k;
}//scaleMult
public boolean equals(Matrix m2) {
if (this.r != m2.r || this.c != m2.c) {
return false;
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (this.neo[i][j] != m2.neo[i][j]) {
return false;
}
}
}
return true;
}//equalsMethod
public Matrix multiply(Matrix m2) throws Exception {
if (this.c != m2.r) {
throw new RuntimeException();
}//if
Matrix m3 = new Matrix(this.r, m2.c);
for (int i = 0; i < this.r; i++) {
for (int j = 0; j < m2.c; j++) {
m3.neo[i][j] = 0;
for (int k = 0; k < this.c; k++) {
m3.neo[i][j] += this.neo[i][k] * m2.neo[k][j];
}//forK
}//forJ
}//forI
return m3;
}//multiplyMethod
}//class
Change your scaleMult method to this and it should work:
public void scaleMult(int k) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
this.neo[i][j] *= k;
// you forgot to assign the value, basically we multiply neo[i][j] by k and make neo[i][j] receive that value
// making this.neo[i][j] = this.neo[i][j] *k; would work as well
}
}
}//scaleMult
Also, based on the example you provided on your main method, your code will launch an exception on the multiply method, because as you specified, you can only multiply two matrixes if one's columns amount is equal to the other's row amount. Other than that, I would advise on creating a new class just for your main method.
If your question is multiply a matrix by a number, then here is a very simple example.
public static void main(String []args){
int[][] a = {{1,2,3},{4,5,6}};
int[][] b=new int[2][3];
int i,j,k=2;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
b[i][j]=a[i][j]*k;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
System.out.println(b[i][j]);
}
There must be some array variable on left which should be assigned the multiplied value.
Do this helped? If not, please post your complete code.

Hi, trying to print a certain amount of character based on array values. Java

so my question is how could I print a certain amount of characters based on a array value?
So currently I have an array declared globally like this
static float timesOccured [] = {5,3,7,3,1};
In a method called draw I've tried a few things to try and get it so the output would be something along the line like this
|||||
|||
|||||||
|||
|
Could anyone help me out?
Much appreciated.
You would need to use nested for loops as I have done below:
for (int i = 0; i < timesOccured.length; i++) {
for (int j = 0; j < timesOccured[i]; j++) {
// print characters here
}
}
Loop through the timesOccured array and get each entry; and use the entry (i.e. timesOccured[i]) to print your lines in the nested for loop.
I hope this helps.
public class PrintChar {
static float timesOccured [] = {5,3,7,3,1};
public static void draw(){
for(int i=0; i<timesOccured.length;i++){
for(int j=0; j< timesOccured[i]; j++){
System.out.print("!");
}
System.out.println();
}
}
public static void main(String[] args) {
draw();
}
}
Here are seven ways to do it:
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Strings;
public class StringRepeat {
static int timesOccured[] = { 5, 3, 7, 3, 1 };
static String s = "|";
static String t = "||||||||||||||||||";
public static String repeat(int j) {
return (t.substring(0, j));
}
public static void main(String[] args) {
System.out.println("Using native Java String.substring");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(repeat(timesOccured[i]));
}
System.out.println("\nUsing native Java char.replace");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(new String(new char[timesOccured[i]]).replace("\0", s));
}
System.out.println("\nUsing native Java String.format.replace");
String result = "";
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(String.format(String.format("%%0%dd", timesOccured[i]), 0).replace("0",s));
}
System.out.println(result);
System.out.println("\nUsing native Java StringBuilder.append");
for (int i = 0; i < timesOccured.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < timesOccured[i]; j++) { sb.append(s); };
System.out.println(sb.toString());
}
System.out.println("\nUsing native Jave double for loops");
for (int i = 0; i < timesOccured.length; i++) {
String u = "";
for (int j = 0; j < timesOccured[i]; j++) {
u = u + s;
}
System.out.println(u);
}
System.out.println("\nUsing org.apache.commons.lang.StringUtils.repeat");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(StringUtils.repeat(s, timesOccured[i]));
}
System.out.println("\nUsing com.google.common.base.Strings.repeat");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(Strings.repeat(s, timesOccured[i]));
}
}
}

how do i write this equation in 2D java code

I have a problem to write this equation in java code.
I want to make it in a for loop and I also want to count the iteration.
k[1][1]=|f[1][1]-f[2][1]|+|f[1][1]-f[3][1]|;
k[2][1]=|f[2][1]-f[1][1]|+|f[2][1]-f[3][1]|;
k[3][1]=|f[3][1]-f[1][1]|+|f[3][1]-f[2][1]|;
public class deviation2 {
public static void main(String [] args){
double[][] k = new double[4][2];
double[][] f = {{0.0,0.0},
{0.0,5.4,},
{0..0,4.0},
{0..0,1.5}};
int m,i,j;
for (j = 1; j < 2; j++) {
m = 0;
for (i=1 ; i<3 ; i++) {
m++;
}
}
}
}
for (j = 1; j < 1; j++) {...} can not work.

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}

Categories