Printing the contents of the upper / second half of an array - java

I want to print the contents of the second half of an array, or copy it to another new array.
I have this method:
public static void evaluateF3(int[] anArray) {
int[] array2 = new int[anArray.length/2];
for( int i = 0; i<array2.length; i++) {
for(int j= (anArray)/2; j<anArray.length;j++) {
array2[i]= anArray[j];
System.out.print(" "+ array2[i]);
}
}
}
However it prints the same number of times as the inside for loop, when I only want to print once. I've tried taking the statement outside of the for loop, but then it just says it cannot find 'i'. How do I solve this problem?

Why don't you put it outside the inner loop, but still inside the outer loop, then it should print out properly.
Btw: you got a compile error in your second loop. Either you meant to say j= anArray.length; or j = anArray.length/2. In either case you forgot the .length
I figured out your problem you dont need the second loop
public static void evaluateF3(int[] anArray) {
int[] array2 = new int[anArray.length / 2];
for (int i = 0; i < array2.length; i++) {
array2[i] = anArray[i + (array2.length)];
System.out.print(" " + array2[i]);
}
}
Let me know!

Maybe you're looking to do something like this?
public static void evaluateF3(int[] anArray) {
int[] array2 = new int[anArray.length/2];
for(int i = 0, j= array2.length; j<anArray.length;i++, j++) {
array2[i]= anArray[j];
System.out.print(" "+ array2[i]);
}
}
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8 };
evaluateF3(a); // 5 6 7 8
int[] a = { 0, 1, 1, 0, 0, 0, 2, 2 };
evaluateF3(a); // 0 0 2 2

You cannot divide an array int[] over 2: (anArray)/2

I believe an example of the code you're looking for is as follows:
public static void evaluateF3(int[] array1) {
int[] array2 = new int[array1.length / 2];
System.arraycopy(array1, array1.length / 2, array2, 0, array2.length);
for (int i = 0; i < array2.length; i++)
{
System.out.println(array2[i]);
}
}

I think(1) you want to copy the upper half of elements into a new array. Then you just need one for loop (if you want to do it with loops):
public static void evaluateF3(int[] anArray) {
// assuming that anArray.size() is even!!
int[] array2 = new int[anArray.length/2];
for(int i = 0; i < array2.length; i++) {
array2[i]= anArray[i + anArray.length/2];
System.out.print(" "+ array2[i]);
}
}
(1) Just read your comment to another answer, I think I got it right

for( int i = 0; i<array2.length; i++)
{
for(int j= (anArray.length)/2; j<anArray.length;j++)
{
array2[i]= anArray[j];
}
System.out.print(" "+ array2[i]);
}
That would print the value of each index in the array2. Do you want it to print once after both of the loops?

Related

Expanding an array to represent an index as many times as the magnitude of original value

Example: expand(new int[]{3, 2, 5}) -> {0, 0, 0, 1, 1, 2, 2, 2, 2, 2}
I am trying to have it make a a new array to print the index of say 3, 3 times. So 3 would be 0,0,0.
public static int[] expand(int[] input) {
int c = 0;
int[] myArray = new int[sum(input)];
if(input.length == 0){
return new int[0];
}
for(int i = 0; i < input.length; i++) {
int a = input[i];
for(int j = c; j < a; j++) {
c += j;
myArray[j] = i;
}
}
return myArray;
}
Currently this only partially works and I cant seem to figure out how to go through the full array properly. In addition, index zero seems to get skipped.
You were close! It seems that you just need to modify your nested for-loop slightly:
for (int j = 0; j < a; j++) {
myArray[c++] = i;
}
Seeing as you're using c to keep track of the current index, this simply sets the element at index c to i and increments c. You can also remove a and use input[i] in place of it.
Note: It is easier to start j from 0 rather than from c.
Functional method
public class Main {
public static void main(final String... args) {
int[] items = expand(new int[]{3, 2, 5});
System.out.println(Arrays.toString(items));
}
public static int[] expand(int[] input) {
return IntStream.range(0, input.length)
.flatMap(p -> IntStream.generate(() -> p).limit(input[p]))
.toArray();
}
}
This makes a stream of the index, and for each item takes that many of the index, putting all of them into an array

Java sorting program, getting a confusing output

public static void main(String[] args) throws Exception {
// declarations
int i, z, x, greatest;
int[] array = { 2, 3, 4, 55, 6 };
int[] copyarray = { 0, 0, 0, 0, 0 };
int zz;
greatest = array[0];
for (zz = 0; zz < 5; zz++) {
for (x = 0; x < 5; x++) {
if (array[x] > greatest) {
greatest = array[x];
}
}
copyarray[zz] = greatest; // this will contain the sorted array
// part of the nested loop
for (z = 0; z < 5; z++) {
if (greatest == array[z]) {
array[z] = 0;
}
}
}
// not part of the nested loop
for (i = 0; i < 5; i++) {
System.out.println("sorted array: " + copyarray);
}
}
Output:
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
This is just a basic little program and I'm trying to get the logic right. I can't improve it or make it into a class or method because I'm not even getting the output right.
If you are trying to use your own algorithm, i would suggest you try using IDE and debug the code.
If you want to use algorithm that JDK provides, you could use:
Arrays.sort(array);
Regarding the output, you are trying to print array and array is an object without toString implementation in java. Hence you should change your print statement to :
System.out.println("sorted array: "+Arrays.toString(copyarray));//without surrounding for loop to get what its after each step of sorting elements.
Or if you want to keep your for loop then you could use index based access to array like:
System.out.print(copyarray[i] + " ");
Actually, none of the answers here are right.
The heart of the problem is that you are not re-initializing the variable greatest for each iteration. It is set to array[0]; in the beginning and it is never changed again. This should go inside the loop.
public static void main(String[] args) throws Exception {
// declarations
int i, z, x, greatest;
int[] array = { 2, 3, 4, 55, 6 };
int[] copyarray = { 0, 0, 0, 0, 0 };
int zz;
// greatest = array[0]; <---- Don't do it here
for (zz = 0; zz < 5; zz++) {
greatest = array[0]; // <--- Initialize greatest here and not before the loop
for (x = 0; x < 5; x++) {
if (array[x] > greatest) {
greatest = array[x];
}
}
copyarray[zz] = greatest; // this will contain the sorted array
// part of the nested loop
for (z = 0; z < 5; z++) {
if (greatest == array[z]) {
array[z] = 0;
}
}
}
// not part of the nested loop
for (i = 0; i < 5; i++) {
System.out.println("sorted array: " + copyarray[i]);
}
}
As a side note, you are printing the array incorrectly, you should use copyarray[i] and not copyarray.
Whit these two changes, here's the output:
sorted array: 55
sorted array: 6
sorted array: 4
sorted array: 3
sorted array: 2
You are printing the reference not the value
use:
for(int i = 0; i < copyarray.length; i++ ) {
System.out.println("Value : " + copyarray[i]);
}
i would also recommend using Arrays.sort(array);
just write
private int[] values = { 9,2,5,3,1,7,0 };
public void printSorted() {
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
System.out.println("Value: " + values[i]);
}
}

Counter not incrementing

I have an assignment to count the assignments and comparisons in a selection sort. For some reason my assignment counter isn't incrementing. I've tried adding it above the swap and I've tried incorporating into the swap method - to no avail. Any ideas why it's not working?
Update: The counter doesn't work for this
Integer[] test = {1, 0, 4, 2};
selectionSort(test);
But it does work for this:
selectionSort(new Integer[] {1, 0, 4, 2});
Anyone know why?
public static void selectionSort(Integer[] array)
{
int assignmentCounter = 0;
int comparisonCounter = 0;
int i, j;
for(i = 0; i < array.length; i++)
{
int minIndex = i;
for(j = i + 1; j < array.length; j++)
{
comparisonCounter++;
if(array[j].compareTo(array[minIndex]) < 0)
{
minIndex = j;
assignmentCounter++;
swap(array,minIndex,i);
}
}
}
System.out.println("Selection Sort Comparisons: " + comparisonCounter + "\nSelection Sort Assignments: " + assignmentCounter);
for(int k = 0; k < array.length; k++)
{
System.out.print(array[k] + ", ");
}
System.out.println("\n\n ");
}
Thank you!
When I run this
public static void main(String[] args) {
selectionSort(new Integer[] { 1, 0, 4, 2 });
}
I get the output
Selection Sort Comparisons: 6
Selection Sort Assignments: 2
0, 1, 2, 4,
Are you possibly expecting a static or other local variable also called assignmentCounter to be changed?
The variable assignmentCounter declared in selectionSort is local to that method. Nothing outside of it can see it.

Sort an array such a way that First half should be in ascending order Second half should be in descending order in java

I have searched a lot in google but I didnt get any kind of solution I could use. Suppose input of array is:
{3,1,2,4,9,8,7,6,5,10}
then output must be like this:
{1,2,3,4,5,10,9,8,7,6}
by using Basic Java .
Your array: {3,1,2,4,9,8,7,6,5,10}
Sort it in ascending order: {1,2,3,4,5,6,7,8,9,10}
Break this array into two half arrays: {1,2,3,4,5}{6,7,8,9,10}
Sort the second array in descending order or reverse it: {10, 9,8,7,6}
Add the second array to the first array & you get: {1,2,3,4,5,10,9,8,7,6}
This would be the minimal code which uses an array of primitive ints:
static final int[] xs = {3,1,2,4,9,8,7,6,5,10};
static void sortAndReverse() {
Arrays.sort(xs);
for (int i = xs.length/2; i < dest(i); i++) {
int tmp = xs[i]; xs[i] = xs[dest(i)]; xs[dest(i)] = tmp;
}
System.out.println(Arrays.toString(xs));
}
static int dest(int i) { return 3*xs.length/2-i-1; }
If you're not ashamed of using wrapper objects, then this is unbeatable:
final Integer[] xs = {3,1,2,4,9,8,7,6,5,10};
final List<Integer> list = Arrays.asList(xs);
Collections.sort(list);
Collections.reverse(list.subList(list.size()/2, list.size()));
System.out.println(Arrays.toString(xs));
Please find the below code
import java.util.Arrays;
public class fre {
public static void main(String[] args) {
int[] vals = { 3, 1, 2, 4, 9, 8, 7, 6, 5, 10 };
Arrays.sort(vals); // Sorts the basic first array
int[] vals2 = Arrays.copyOfRange(vals, vals.length / 2, vals.length); // Gets the las values of the arrays i.e. it devies the array in multiple same part and another array is created
// Below loop will reverse the second array
for (int i = 0; i < vals2.length / 2; i++) {
int temp = vals2[i];
vals2[i] = vals2[vals2.length - 1 - i];
vals2[vals2.length - 1 - i] = temp;
}
vals = Arrays.copyOfRange(vals, 0, vals.length / 2);
// Final array array1and2 will be created where we will append first array with second array
int[] array1and2 = new int[vals.length + vals2.length];
System.arraycopy(vals, 0, array1and2, 0, vals.length);
System.arraycopy(vals2, 0, array1and2, vals.length, vals2.length);
// Prints the final result array
System.out.println(Arrays.toString(array1and2));
}
}
Output
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
You can use the java features to do this too ... Use
public static <T> void sort(T[] a,
int fromIndex,
int toIndex,
Comparator<? super T> c)
But the elements need to be objects ... The comparator needs to be changed while sorting the first half and second half of the array.
Should be a bit simpler than manually reversing each item in the second half.
Integer [] array = { 3,1,2,4,9,8,7,6,5,10 };
Arrays.sort(array);
Arrays.sort(array, array.length/2, array.length, new Comparator<Integer>(){
#Override
public int compare(Integer o1, Integer o2)
{
return -o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(array));
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
IPSOS isn't it?
int m;
if(array.length%2==0)
m=array.length/2;
else
m=(array.length+1)/2;
for(int i=0; i<array.length; ++i){
if(i<m){
int min = i;
for(int j=i+1; j<m;++j){
if(array[min]>array[j]){
min=j;
}
int tem = array[i];
array[i]=array[min];
array[min]=tem;
}
}
else {
int max = i;
for(int k=i+1; k<array.length; ++k){
if(array[max]<array[k]){
max=k;
}
int te = array[i];
array[i]=array[max];
array[max]=te;
}
}
}
for(int i=0;i<array.length;++i){
System.out.print(array[i] + " ");
}
1. Sort the array input_Array[]
2. j = lenght(input_Array)-1
3. loop i = lenght(input_Array)/2 to j
swap(input_Array[i] , input_Array[j-i])
input: 3,1,2,4,9,8,7,6,5,10
output: 1 3 5 7 9 10 8 6 4 2 (uniform acceding and descending )
public class AscendingDecending {
public static void main(String[]args) {
int a[]= {2,3,2,5,7,5,6,3};
int i,j,temp;
//Traverse the element of array
System.out.println("Input:");
for(i=0; i<a.length; i++) {
System.out.print(" "+ a[i]);
}
//lets move for ascending function
System.out.println("");
System.out.println("Output:");
//Create a Swap Function for sorting
for(i=0; i<a.length; i++) {
for(j=i+1; j<a.length; j++) {
if(a[i]>a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
//For Descending
for(i=0; i<a.length; i++) {
for(int j=i+1; j<a.length; j++) {
if(a[i]<a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
System.out.println(" ");
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
}
}
I hope this piece of code will help:
static void printarray(int[] arr, int len)
{
Arrays.sort(arr);
for (int i = 0; i < len / 2; i++)
System.out.println(arr[i]);
for (int j = len - 1; j >= len / 2; j--)
System.out.println(arr[j]);
}

Please help with my twodimensional array source code

Here is what i have done but i have some questions:
class masivins {
public static void main (String args[]) {
int mas[][] = {{0, 2, 7, 0, 8, 5, 3},
{0, 4, 0, 6, 0, 0, 0},
{0, 0, 0, 0, 3, 0, 0},
{7, 0, 0, 9, 1, 0, 7},
{5, 0, 4, 0, 0, 2, 0}};
int nulmas[] = new int [7];
int nul=0;
for(int j=0; j<7; j++) {
nul=0;
for(int i=0; i<5; i++) {
if(mas[i][j]==0) {
nul++;
}
}
nulmas[j]=nul;
}
for(int i=0; i<5; i++) {
for(int j=0; j<7; j++) {
System.out.println(mas[i][j]);
}
System.out.println();
}
System.out.println();
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println();
}
}
so my questions are:
Why after running project there are only 5 "Zeros in each array column....." shown?
What and where i need to change in this code to get out the number of column in which zeros are least?
Question 1 - look at your code:
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
In particular, look at the loop. How many lines do you expect it to print out?
Question 2: You could keep a "least number of 0s in an array column so far" and "column in which the least number of 0s appeared" - then update those variables at the end of the inner loop where you set nulmas[j].
1) because you loop from 0 to 4:
for(int i=0; i<5; i++) {
If you looped until 7, all values would be printed out:
for(int i=0; i<7; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
2) you could keep an index and a minimum counter. The min counter stores the minimum number of zeros, the index the column where this is found:
int nulmas[] = new int [7];
int nul=0;
int minNuls=5;
int minIndex=0;
for(int j=0; j<7; j++) {
nul=0;
for(int i=0; i<5; i++) {
if(mas[i][j]==0) {
nul++;
}
}
nulmas[j]=nul;
if (nul < minNul) {
minNul = nul;
minIndex = j;
}
}
You seem to be very close to answering the question. It looks to me like you've set up the nul_mas array to contain the number of zeros in each column, so the question becomes "which index of nul_mas has the smallest value?". You can do this with two variables - one for the smallest value seen so far, one for the index where it was seen - and a loop through that array to look at each element in turn. (Then, when you've got it working, consider what happens if there is a tie.)
Try:
int leastZeroIndex = 0;
for(int i=0;i<5;i++) {
if (nul_mas[i] < nul_mas[leastZeroIndex])
leastZeroIndex = i;
}
System.out.print(leastZeroIndex);
Though there is no check if there are multiple rows with the lowest amount of zeros.
It looks to me as if you need to create some new arrays, so create an array for each column, and then put the numbers for the column in there. After that, just iterate over that array of arrays which represent the columns and count the numbers (you could use a method for doing this, i.e., int count(int num, int[] arr). I think this'll give the least amount of code.
int[][] mas = ...; // (you have this already), it's [NO_OF_ARRS][NO_OF_COLS] with the data
int[][] colsarrs = new int[NO_OF_COLS][NO_OF_ARRS];
for (int i = 0; i < NO_OF_ARRS; i++) {
for (int j = 0; j < NO_OF_COLS; i++) {
colsarrs[j][i] = mas[i][j];
}
}
int[] resultarr = new int[NO_OF_COLS];
for (int i = 0; i < NO_OF_COLS; i++) {
resultarr[i] = count(0, colsarrs[i]);
}
int count(int num, int[] arr) {
int count;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) ++count;
}
return count;
}
Store the amount of zeros in an additional array (resultarr) gathered from this function for each column. After this, go over the array and find the lowest number, and grab the index of it. That's your column with the lowest amount of zeroes.
int lowestcurr = 0;
for (int i = 0; i < NO_OF_COLS; i++) {
if (resultarr[i] < resultarr[lowestcurr]) {
lowestcurr = i;
}
}
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println(); place there it
change it on :
int minElement = 0;
for(int i=0; i<7; i++) {
if (nulmas[i] < nulmas[minElement]) minElement = i;
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println(nulmas[minElement]);
better use "\n" to skip one line in console

Categories

Resources