Having trouble with an element switch - java

So I am trying to do an element switch. Basically switch two elements in a 2D array. I am not getting any errors but it just doesn't work out right, and doesn't even print all of the elements. What am I doing wrong. Here is the code.
public class ArrayTheory
{
public static void printArray(int[][]args)
{
for(int i=0;i<args.length; i++)
for(int j=0;j<args.length; j++) {
System.out.print(args[i][j]);
}
System.out.println();
}
public static void arraySwitch(int c1, int c2, int [][]args)
{
for(int i=0;i<args.length; i++)
for(int j=0;j<args.length; j++) {
int temp = args[i][c1];
args[i][c1] = args[i][c2];
args[i][c1] = temp;
}
}
}
And here are the elements
public class TestArray {
public static void main(String[] args){
int[][] test = {{1,2,3,4},
{1,2,3,4},
{1,2,3,4}};
int[][] carData = {{16,2008,4},
{45,2011,4},
{26,2010,7},
{18,2009,8}};
ArrayTheory.arraySwitch(0,2,test);
ArrayTheory.printArray(test);
}
}

Since the array isn't square you you need to index the second dimension with args[0].length or args[i].length if each row doesn't have the same length.

You have a bug in your code in the inner loop of arraySwitch
int temp = args[i][c1];
args[i][c1] = args[i][c2];
args[i][c1] = temp; <<<<<<< bug
That should be
args[i][c2] = temp;

Your question is not very clear. If you are trying to swap two specific elements, then you need four coordinates (a1, a2) and (b1, b2) to address each element. Your code seems to be trying to swap two rows. Your print method looks fine, except your outer loop does not have braces. So your println() will only execute once, after the entire contents of the 2D array have been printed.

Related

How to copy a matrix row to an array and modify the array?

I'm kinda new to Java myself and I was doing some excercises, I find myself stuck in an excersise that asks me to copy the third sequence from a preloaded 4 Row * 20 Column Matrix of characters from a to z, to an array that has the same size (4*20), everytime it copies data from the Matrix it has to be stored from left to right without any wildcard or space on the new array. The excercise gives this code to begin. (The commented methods should be taken as already implented)
public class second_excercise {
public static final int MAXROW = 4;
public static final int MAXCOLUMN = 20;
public static final int MAX = MAXROW*MAXCOLUMN;
public static void main(String[] args) {
char [] arrchar;
char [][] matchar;
arrchar = new char[MAX];
matchar = new char[MAXROW][MAXCOLUMN];
//load_array_char(arrchar);
//load_random_char_matrix(matchar);
//Solve the problem in the following method: solve_second_excercise(...)
solve_second_excercise(matchar, arrchar);
}
public static void solve_second_excercise(char [][] matchar, char [] arrchar){
}
I have tried some methods myself:
public static char grab_sequence_beginning(char[] arr, char begin){
while ((begin < MAX)&&(arr[begin]==0))
begin++;
return begin;
}
public static char grab_end_sequence(char[] arr, char end){
while ((end < MAX)&&(arr[end]!=0))
end++;
return end-1;
}
public void add_elements_to_new_array(char [] arrchar, char element){
for(int i=0; i<array.length; i++)
{
if(array[i] == 0)
{
System.arraycopy(array, 0, array, 1, i);
array[0] = element;
return;
}
public static void print_array(char [] arr){
for (int pos = 0; pos < MAX; pos++){
System.out.println("array["+pos+"]=>: "+arr[pos]);
}
}
Nothing managed to work and I'm kinda lost, the main idea I have is that I need to copy an specific part (the third sequence of chars to be precise) to a new array but I don't really know how to do that, cause the things I tried myself didn't seem to work. I would like some help and indepth explanations are always welcome, thank you in advance.

java arrays reverse not understanding the logic

I was trying to use this code I made to reverse a array. I don't understand why I was getting [I#7a84639c as my output in my console.
And for some reason why doesn't this method actually save my reversed array into the array? If i add a print at the bottom of x[i]=c[i]; it shows the array reversed but when i add a call for example karn[0] it shows that my array isn't actually reversed. I want to solve this by staying true to the code i made.
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[]karn={1,2,3};
rev(karn);
System.out.println(karn.toString());
}
public static void rev(int[]x){
int[]c=new int[x.length];
for(int i=x.length-1;i>-1;i--){
c[i]=x[i];
x[i]=c[i];
}
}
}
in your rev method you are using a local variable for c. So this value will not be transferred over to your main method. You must return your array and assign the value to your old array:
public static int[] rev(int[]x){
//Creates new array this array is different from karn and local to the method.
//nothing outside of this method can see this array.
int[]c=new int[x.length];
for(int i = 0; i < c.length; i++){
//Here is where we are swapping the values by placing the first
//value at the last spot of the array and so on
c[c.length - i - 1] = x[i];
}
//we must return the new array we made and assign it to karn so our
//changes will be saved and seen outside of the method
return c;
}
In main method you must assign the changes of the rev method to karn. You can assign the value and display it like so:
karn = rev(karn);
//for each loop
for(int i : karn)
System.out.println(i);
//traditional for loop
for(int i = 0; i < karn.length; i++)
System.out.println(karn[i]);
Arrays do not have a default toString() method. That is why you are seeing the values of the array as you would like. You need to iterate through the array to display them to the console.
Your initial approach looked almost correct, you can do this in-place or through a copy. I posted a comment showing a copy, so I thought I might expand on in-place. I would start with a simple swap method, like
private static void swap(int[] x, int i, int j) {
if (i != j) {
int t = x[i];
x[i] = x[j];
x[j] = t;
}
}
Then you only need to iterate the first half of the array, swapping each element with the same index (but from the other half). Like,
public static void rev(int[] x) {
for (int i = 0; i < x.length / 2; i++) {
swap(x, i, x.length - i - 1);
}
}
Then you might call it like
public static void main(String[] args) throws IOException {
int[] karn = { 1, 2, 3 };
rev(karn);
System.out.println(Arrays.toString(karn));
}
for an output of
[3, 2, 1]

Shuffling elements in an Array (Java)

I need a shuffle method to shuffle elements of an array which holds objects from another class. At the moment I wrote this code to test with integers first, but it seems to not working perfectly. Most of the elements are being duplicated.
Can someone please spot the mistake?
And also come up with a more efficient method for this.
I am not sure if I can use collections.shuffle because I have further use of my shuffled array later.
public static void shuffle()
{
int[] a = new int[52];
int count = 0;
int random = 0;
while (count!=51){
random = (int)(Math.random() * 52);
for (int i=0; i <=count; i++){
if (a[count] != b[random])
result = true;
}
if (result){
a[count] = b[random];
count++;
}
b = Arrays.copyOf(a, a.length);
}
}
First you should not define shuffle() in this way. I would treat b as a parameter and pass it into shuffle() instead of a static field (as your shuffle() is declared as static, your b is also static right? It looks strange to share b between all instances), and result is declared as a local variable.
This part
for (int i=0; i <=count; i++){
if (a[count] != b[random])
result = true;
}
checks whether any one of a[0], a[1] until a[count] is not equal to b[random]. If yes, then assign b[random] to a[count] and increase count by 1. As a[] is not initialized, it is only an array of 0. (a[count] != b[random]) appears to be always true and hence result is true.
Then, for this part,
if (result){
a[count] = b[random];
count++;
}
say for example random=5, then at the first round of the while loop a[0]=b[5], count=1 (due to count++), and b becomes an array of b[5] and a series of 0. (Due to
b = Arrays.copyOf(a, a.length);
all other elements are replaced by 0.)
Edit: Here I provide a simple method, not thoroughly tested, but should work:
public static int[] shuffle(int[] array) {
int[] a = new int[array.length];
//convert int[] to ArrayList<Integer>
ArrayList<Integer> list = new ArrayList<>();
for (int i: array)
list.add(i);
//now shuffle:
for (int i=0; i<array.length; i++) {
int rand = (int)(Math.random()*list.size());
a[i] = list.remove(rand);
}
return a;
}
The array returned is shuffled. Actually I can't say the method "shuffles" the array. It simply creates an empty array, and repeatedly selects an element randomly and put it at the front.
Edit2: This really "shuffles", and this is another approach: does not return a new array. It shuffles the array, 100 times.
public static void shuffle(int[] array) {
for (int i=0; i<100; i++) {
int r1 = (int)(Math.random()*array.length);
int r2 = (int)(Math.random()*array.length);
int tmp = array[r1];
array[r1] = array[r2];
array[r2] = tmp;
}
}
import java.util.Random;
public class Shuffle {
public static void main(String[] args) {
Integer[] a = new Integer[52];
for (Integer i=0;i<a.length;i++) a[i] = i+1;
// Let's shuffle
Random rd = new Random();
for (Integer i=0;i<a.length;i++){
Integer changeBy = rd.nextInt(a.length);
Integer aux=a[i];
a[i]=a[changeBy];
a[changeBy] = aux;
}
// Now show the shuffled array
for (Integer i=0;i < a.length; i++) System.out.print(a[i]+",");
}
}
Hope this small algorithm helps you. As you can see from 2 different runs, it really shuffles your array:
11,1,24,13,28,15,25,48,5,22,12,32,29,42,34,7,33,31,47,18,51,40,8,17,41,20,6,36,21,45,27,52,38,10,30,14,23,19,43,4,50,46,44,3,49,37,35,2,9,26,16,39
3,10,37,26,41,15,28,52,6,24,20,43,33,21,51,32,25,40,50,8,7,5,4,35,13,16,49,17,29,47,12,14,36,39,45,30,2,42,23,38,31,19,27,46,34,11,18,1,22,48,9,44
Why no you HashSet for shuffle?
Elements in java.lang.HashSet are shuffling by their hashcode.
public static void shuffle()
{
int [] b; // you origin array
Set<Integer> temp = new HashSet<Integer>();
for (int i : b) {
temp.add(i);
}
Integer [] a = new Integer[b.length];
a = temp.toArray(a); // new shuffle array
}

ArrayList giving problems in java. positive integers solution to x+y+z+w = 13

So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.

recursion resulting in extra unwanted data

I'm writing a module to handle dice rolling. Given x die of y sides, I'm trying to come up with a list of all potential roll combinations.
This code assumes 3 die, each with 3 sides labeled 1, 2, and 3. (I realize I'm using "magic numbers" but this is just an attempt to simplify and get the base code working.)
int[] set = { 1, 1, 1 };
list = diceroll.recurse(0,0, list, set);
...
public ArrayList<Integer> recurse(int index, int i, ArrayList<Integer> list, int[] set){
if(index < 3){
// System.out.print("\n(looping on "+index+")\n");
for(int k=1;k<=3;k++){
// System.out.print("setting i"+index+" to "+k+" ");
set[index] = k;
dump(set);
recurse(index+1, i, list, set);
}
}
return list;
}
(dump() is a simple method to just display the contents of list[]. The variable i is not used at the moment.)
What I'm attempting to do is increment a list[index] by one, stepping through the entire length of the list and incrementing as I go.
This is my "best attempt" code. Here is the output:
Bold output is what I'm looking for. I can't figure out how to get rid of the rest. (This is assuming three dice, each with 3 sides. Using recursion so I can scale it up to any x dice with y sides.)
[1][1][1] [1][1][1]
[1][1][1] [1][1][2] [1][1][3] [1][2][3]
[1][2][1] [1][2][2] [1][2][3] [1][3][3]
[1][3][1] [1][3][2] [1][3][3] [2][3][3] [2][1][3]
[2][1][1] [2][1][2] [2][1][3] [2][2][3]
[2][2][1] [2][2][2] [2][2][3] [2][3][3]
[2][3][1] [2][3][2] [2][3][3] [3][3][3] [3][1][3]
[3][1][1] [3][1][2] [3][1][3] [3][2][3]
[3][2][1] [3][2][2] [3][2][3] [3][3][3]
[3][3][1] [3][3][2] [3][3][3]
I apologize for the formatting, best I could come up with.
Any help would be greatly appreciated. (This method was actually stemmed to use the data for something quite trivial, but has turned into a personal challenge. :)
edit: If there is another approach to solving this problem I'd be all ears, but I'd also like to solve my current problem and successfully use recursion for something useful.
edit2:
Running code including the "easy fix." Beware unused variables and weird hacks, I haven't cleaned it up yet.
package code.testing;
import java.util.ArrayList;
public class CodeTesting {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
int[] set = { 1, 1, 1 };
list = recurse(0,0, list, set);
}
public static ArrayList<Integer> recurse(int index, int i, ArrayList<Integer> list, int[] set){
if(index < 3){
// System.out.print("\n(looping on "+index+")\n");
for(int k=1;k<=3;k++){
// System.out.print("setting i"+index+" to "+k+" ");
set[index] = k;
if (index==2){
dump(set);
}
recurse(index+1, i, list, set);
}
}
return list;
}
static void dump(int[] arr) {
for (int s : arr) {
System.out.format("[%s]", s);
}
System.out.println();
}
}
I'm sorry I had to rewrite the code, but it's pretty much the same algorithm as yours with some corrections:
public class DiceRolls {
static void recurse(int diceNumber, int[] values, final int MAX) {
if (diceNumber == values.length) {
System.out.println(java.util.Arrays.toString(values));
} else {
for (int v = 1; v <= MAX; v++) {
values[diceNumber] = v;
recurse(diceNumber + 1, values, MAX);
}
}
}
public static void main(String[] args) {
recurse(0, new int[3], 4);
}
}
This is a standard tuplet recursive generator. If you want to add all the int[] into a List, then make sure to add(values.clone()) so they are independent int[] objects.
But what's with the extra output?
The problem is that you were dumping prematurely, before you're done throwing all the dices. In pseudocode, this is what you're doing:
if we're not done yet
trying all possibilities for this dice
dump result so far // premature dumping!
recurse for next dice
An easy fix to your code is to do the following:
if we're not done yet
trying all possibilities for this dice
recurse for next dice
else, we're done, so
dump result // timely!
So back to the Java implementation, the fix is merely moving dump(set); to an else case for the if (index < 3) statement.
Call dump() only when index == 2.
Incidentally, i and list seem unused. And the verb is "recur". :)
Here is a non-recursive alternative. Change the two constants to calculate all combinations for different dices and different numbers of dice.
package utils;
public class Dice {
private static int FACES = 3;
private static int NUMBER_OF_DICE = 3;
public static void main(String[] args) {
int start = createPair(1);
int end = createPair(FACES);
for (int i = start; i <= end; i++) {
String combination = Integer.toString(i, FACES+1);
if (combination.indexOf('0') < 0)
System.out.println(combination);
}
}
private static int createPair(int number) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < NUMBER_OF_DICE; i++) {
sb.append(number);
}
return Integer.parseInt(sb.toString(), FACES+1);
}
}

Categories