I have an assignment to create a class in which I create an array of size 10, called source, and assign random integers in the range 0-10 to all indexes in it, and then call a method that creates a new array in reverse order. I tried the code below:
public class Exercise7_4 {
// reverse array method
public static int[] reverseArray(int[] arr) {
int[] reverse = new int[arr.length];
for (int i = 0; i < reverse.length - 1; i++) {
reverse[i] = arr[arr.length - 1 - i];
}
return reverse;
}
// print array in ascending order
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
System.out.printf("%d\t", arr[i]);
}
System.out.println();
}
public static void main(String[] args) {
int[] source = new int[10];
for (int i = 0; i < source.length - 1; i++) {
source[i] = (int) (Math.random() * 10 + 1);
}
int[] reverse = reverseArray(source);
printArray(source);
printArray(reverse);
}
}
The problem is that the output i get looks like this:
7 1 3 7 10 9 6 2 6
0 6 2 6 9 10 7 3 1
meaning, the reverseArray method doesn't work properly on reverse[0] for some reason.
I would like to know why this is happening and how I can fix it.
Thanks in Advance!
change all your for-loops from
for (int i = 0; i < source.length - 1; i++)
to
for (int i = 0; i < source.length; i++)
Your reverse method is completely correct (if you change the loop). The mistake you made is that you created an array of size 10, filled it with 9 random values (the value of index 10 will therefore be 0).
You could check wich index are consulted in each iteration of your for loop.
This is your solution
for (int i = 0; i < reverse.length - 1; i++) {
System.out.println("" + i + " " + (reverse.length - 1 - i));
}
And it prints:
0 9
1 8
2 7
3 6
4 5
5 4
6 3
7 2
8 1
The 'i' don't get the value 9, and the (reverse.length - 1 - i) don't get the value 0.
Changing the testing condition for this:
i < reverse.length
gives you the last position:
9 0
Change reverseArray function as follows:
public static int[] reverseArray(int[] arr) {
int[] reverse = new int[arr.length];
for (int i = 0; i < reverse.length; i++) {
reverse[i] = arr[arr.length - i];
}
return reverse;
}
You need not to -1 from arr.length.
Change another for loop also:
for (int i = 0; i < source.length; i++) {
source[i] = (int) (Math.random() * 10 + 1);
}
Here, also you do not need to do -1 from source.length.
package com.test;
public class SortArray {
private int[] getSortedArry(int[] arr){
int arrLen = arr.length;
int reversedArry[] = new int[arrLen];
System.out.println("array lenght: " +arr.length);
int j = 0;
for(int i=arrLen-1; i>=0; i--){
reversedArry[j] = arr[i];
j++;
}
System.out.print("\n");
return reversedArry;
}
public static void main(String[] args){
int arr[] = {10,2,3,4,5,12,23,43,45,65};
SortArray sortArray = new SortArray();
int reversedArry[] = sortArray.getSortedArry(arr);
for(int i=0;i<reversedArry.length;i++){
System.out.print(reversedArry[i] + " ");
}
}
}
Related
I am new in Java and I am trying to implement an algorithm that, only using While and For loops, selects six random numbers between 1 and 49, puts them in an array, and prints them. If there are duplicates, the random process should start again and substitute the duplicates with other numbers and, in the end, sort all numbers in the array. The first step was pretty easy and it seems to work:
import java.util.*;
public class RandomArray {
public static void main(String[] args) {
Random rand = new Random();
int[] arr = new int[6];
for (int i = 1; i < arr.length; i++) {
arr[i] = rand.nextInt(50);
System.out.println(arr[i]);
}
}
}
Indeed, I am struggling to think about how to make the to loops work. I tried to create two loops, one of them (i) iterating before j and removing the duplicates but it is not working:
import java.util.*;
public class RandomArray2 {
/**
* #param args
*/
public static void main(String[] args) {
Random rand = new Random();
int[] arr = new int[6];
int j = 0;
while (j < arr.length) {
j++;
arr[j] = rand.nextInt(50);
Arrays.sort(arr, 0, 7);
System.out.println(arr[j]);
for (int i = j + 1; i < arr.length; i++) {
if (arr[i] == arr[j]) {
arr[i] = rand.nextInt(50);
Arrays.sort(arr, 0, 7);
System.out.println(arr[i]);
}
}
}
}
}
Output:
0
0
0
0
11
11
36
44
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 7
at RandomArray2.main(RandomArray2.java:29)
I am not expecting to get a solution for the problem but I would be thankful for any advice on what I am doing wrong.
My advice is to check for duplicate before adding to array.
Generating a new random instead of duplicate cannot guarantee that is not duplicate per all array.
Eq: (1,1,2) but and if regenerate 1 and will be 2 then (1,2,2) is not valid.
public class RandomArray {
public static void main(String[] args) {
Random rand = new Random();
int[] arr = new int[7];
for (int i = 0; i < arr.length; i++) {
int random = rand.nextInt(50);
//check previous values in order to add only distinct
for (int j = 0; j < i; j++) {
if (random == arr[j]) {
System.out.println("arr[" + j + "]=" + random +
" ... compute new one for arr[" + i + "]");
random = rand.nextInt(50);
j = 0;
}
}
arr[i] = random;
}
System.out.println("### Initial");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
Arrays.sort(arr);
System.out.println("### Sorted");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Possible Output:
arr[0]=1 ... compute new one for arr[3]
arr[2]=42 ... compute new one for arr[6]
### Initial
1
3
42
12
44
6
32
### Sorted
1
3
6
12
32
42
44
If you want to know if a array contains an element, you should use myList.contains(3). It returns a boolean.
I am trying to implement a Perfect Shuffle method where it will split a deck into 2 and then interweave the cards so you have one from each deck being placed into the new deck. When I try to run my current program, the output I would get is:
Results of 3 consecutive perfect shuffles:
1: 0 4 1 5 2 6 3
2: 0 2 4 6 1 3 5
3: 0 1 2 3 4 5 6
I do not understand why I get 0 as my first value for each time I shuffle the deck. Can anyone tell me what I am doing wrong? This is my code:
class Ideone {
/**
* The number of consecutive shuffle steps to be performed in each call
* to each sorting procedure.
*/
private static final int SHUFFLE_COUNT = 3;
/**
* The number of values to shuffle.
*/
private static final int VALUE_COUNT = 7;
/**
* Tests shuffling methods.
* #param args is not used.
*/
public static void main(String[] args) {
System.out.println("Results of " + SHUFFLE_COUNT +
" consecutive perfect shuffles:");
int[] values1 = new int[VALUE_COUNT];
for (int i = 0; i < values1.length; i++) {
values1[i] = i;
}
for (int j = 1; j <= SHUFFLE_COUNT; j++) {
perfectShuffle(values1);
System.out.print(" " + j + ":");
for (int k = 0; k < values1.length; k++) {
System.out.print(" " + values1[k]);
}
System.out.println();
}
System.out.println();
}
public static void perfectShuffle(int[] values) {
int[] temp = new int[values.length];
int halfway = (values.length +1)/2;
int position = 0;
for (int j = 0 ; j < halfway; j++)
{
temp[position] = values[j];
position +=2;
}
position = 1;
for (int k = halfway; k < values.length; k++)
{
temp[position] = values[k];
position +=2;
}
for (int k = 0; k < values.length; k++)
values[k] = temp[k];
}
}
array index begin at 0 and not 1.
for (int i = 0; i < values1.length; i++) {
values1[i] = i;
}
you are copying 0 in values1 in this for loop in your main method which you then pass to perfectShuffle
You fill the "deck" starting at 0 and then shuffle, but your shuffle always puts the "0" card first so it never really gets shuffled in. You can see the same thing with the #1 using:
for (int i = 1; i < values1.length+1; i++) {
values1[i-1] = i;
}
Also, with an even number of cards, your last card will never change either.
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 7 years ago.
I filled an array with the numbers 1 to 10 using a for-loop.
Now I need to fill a second array with the values of the first array, but upside down. So the second array has to be filled with 10 to 1.
I tried something but it fills the second array with just 1.
output is:
1
2
3
4
5
6
7
8
9
10
1
1
1
1
1
1
1
1
1
1
and it should be 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1
package FillandTurn;
import java.util.Scanner;
/**
*
* #author Quinten
*/
public class FillandTurn {
/**
* #param args the command line arguments
*/
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
// TODO code application logic here
FillandTurn fill = new FillandTurn();
fill.start();
}
public void start(){
FillandTurn turn = FillandTurn();
int[] array = turn.vullen();
int[] array2 = turn.draaien(array);
}
public int[] fill(){
int[] array = new int[10];
int j = 0;
for(int i = 0; i < array.length; i++ ){
j++;
array[i] = j;
}
for(int p = 0; p <= array.length-1; p++ ){
System.out.println(array[p]);
}
return array;
}
public int[] turn(int[] array){
int[] array2 = new int[10];
for(int x = 0; x < array2.length; x++){
for(int y = array.length-1; y >=0; y--){
array2[x] = array[y];
}
}
for(int p = 0; p <= array2.length-1; p++ ){
System.out.println(array2[p]);
}
return array2;
}
}
Any helps is appreciated!
Have a for loop to fill the first array as stated, but then have a seperate for loop for the second array, which starts at the size of the first array, and decrements on each iteration, putting the elements into the new array
Have you tried reading the array from the back to the front?
public int[] reverseArray(int[] array1) {
int[] array2 = new int[array1.length];
int pos = 0;
for(int neg = array1.length; neg >= 0; neg--) {
array2[pos] = array1[neg];
}
return array2;
}
This is a simple way, there is probably better ways to do this.
When you copy an array you only need one loop. Using a nested loop means you are copying each value N times, or in fact the first value overwrites all the others.
You can do
class FillAndTurn {
public static void main(String... args) {
int[] array = new int[10];
fill(array);
int[] array2 = turn(array);
IntStream.of(array).forEach(System.out::println);
IntStream.of(array2).forEach(System.out::println);
}
static void fill(int[] array) {
for (int i = 0; i < array.length; i++)
array[i] = i + 1;
}
static int[] turn(int[] array) {
int[] array2 = new int[array.length];
for(int i = 0; i < array.length; i++)
array2[array2.length - i - 1] = array[i];
return array2;
}
}
Write a method
public static ArrayList merge(ArrayList a, ArrayList b)
that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elements from the longer array list. For example, if a is
1 4 9 16
and b is
9 7 4 9 11
then merge returns the array list
1 9 4 7 9 4 16 9 11
What I tried doing was writing a for loop with if statements such that a number is added to the merge array list from array list a when i is an even number (i%2==0) and from array list b when i is an odd number. I am however not sure how to deal with the fact that one array list can be longer than the other. Could anyone please help me out?here is my code so far
package test;
import java.util.Scanner;
public class Arraybig {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int m = scan.nextInt();
int n = scan.nextInt();
int[] A = new int[m];
for (int k = 0; k < m; k++) {
A[k] = scan.nextInt();
}
int[] B = new int[n];
for (int k = 0; k < n; k++) {
B[k] = scan.nextInt();
}
int[] C = new int[m + n];
int max = Math.max(m, n);
int a = 0, b = 0;
for (int i = 0; i < m+n; i++) {
if (i % 2 == 0 && a < A.length) {
C[i] = A[a];
a++;
} else if (i % 2 != 0 && b < B.length) {
C[i] = B[b];
b++;
} else if (a < A.length) {
C[i] = A[a];
a++;
} else {
C[i] = B[b];
b++;
}
}
for (int j = 0; j < C.length; j++) {
System.out.println(C[j] + " ");
}
}
}
A more cleaner approach can be something like this..
list<Integer> a1=//1st list
list<Integer> a2=//2nd list
list<Integer> a3=new Arraylist<Integer>();
int length=(a1.size()<=a2.size())?a1.size():a2.size();
for(int i=0;i<length;i++){
a3.add(a1.get(i));
a3.add(a2.get(i));
}
for(int i=length;i<a1.size();i++){
a3.add(a1.get(i));
}
for(int i=length;i<a2.size();i++){
a3.add(a2.get(i));
}
Hint: How long is the array you want to fill? And how many iterations does your main for loop run? Why is it not the same number?
I am trying to write a method in Java that receives an array and returns a new array where each number is printed that number of times. Here is an example input and output: "1 2 3 0 4 3" ---> "1 2 2 3 3 3 4 4 4 4 3 3 3". I am stuck and my program will not compile. Does anyone see where I am going wrong?
public static int [] multiplicity(int [] nums) {
for (int i = 0 ; i < nums.length ; i++) {
int size = nums.length + 1;
int newNums[] = new int [size];
for (int j = 0 ; j < nums.length ; j++) {
int value = nums[j];
for (int v = 0 ; v < value ; v++) {
newNums[j + v] = value;
}
}
}
return newNums;
}
Your current code does not size your new array correctly, you could fix your compiler errors easily enough like
int size=nums.length+1;
int newNums [] = new int [size];
for (int i=0; i<nums.length; i++)
{
// int size=nums.length+1;
// int newNums [] = new int [size];
But that clearly won't allow you to populate all of your values. Instead (assuming you can't use a dynamic data-type like a Collection), you'll need to iterate the array once to get the final count of elements and then populate your array. Something like,
public static int[] multiplicity(int[] nums) {
// first pass
int count = 0;
for (int num : nums) {
for (int i = 0; i < num; i++) {
count++;
}
}
int[] ret = new int[count];
count = 0;
// second pass
for (int num : nums) {
for (int i = 0; i < num; i++) {
ret[count++] = num;
}
}
return ret;
}
Then you could test it like,
public static void main(String arg[]) {
int[] in = { 1, 2, 3, 0, 4, 3 };
int[] out = multiplicity(in);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < out.length; i++) {
if (i != 0) {
sb.append(' ');
}
sb.append(out[i]);
}
String expected = "1 2 2 3 3 3 4 4 4 4 3 3 3";
System.out.println(expected.equals(sb.toString()));
}
Output is
true
Once you initialise your int[] newNums, you can't dynamically resize it. Initialising it again will discard the previous array.
Here's another way to solve the problem:
public static int [] multiplicity (int [ ] nums)
{
// create a list to contain the output
List<Integer> newNums = new ArrayList<Integer>();
// for each incoming int
if(nums != null) {
for (final int i : nums)
{
// repeat adding the value
for(int j = 0; j < i; j++) {
newNums.add(i);
}
}
}
// now copy from the List<Integer> to the result int[]
int[] result = new int[newNums.size()];
for(int i=0; i < newNums.size(); i++) {
result[i] = newNums.get(i);
}
// return the result
return result;
}
You can't know the new array size until you explore the whole input array.
So you can
Explore the whole array and compute the lengh, then, re-explore the input array and fill the new. You need only 1 memory allocation (only 1 new int[])
Create a vector and fill it. Then use the .toarray method
Exemple to fill the array (check he had the right size)
int k = 0
for(int i: nums) {
for(int j = 0; j < i; j++) {
newArray[k] = i;
k++;
}
}