Arrays stringing numbers - java

package javaapplication1;
/**
*
* #author
*/
public class JavaApplication1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int[] scores = {1,2,3,4,5,6};
int[] fin = extractAllEvens(scores);
for(int i =0; i<fin.length; i++) {
System.out.println(fin[i]);
}
}
public static int[] extractAllEvens(int[]scores) {
int evenCount = 0;
for (int i =0; i<scores.length; i++) {
if (scores[i] % 2 ==0) {
evenCount++;
}
}
int[] newScores = new int[evenCount];
int j = 0;
for(int i = 0; i<scores.length; i++) {
if(scores[1] % 2 ==0) {
newScores[1] = scores[i];
j++;
}
}
return newScores;
}
}
I'm trying to output 2, 4, 6.
But I keep getting results such as 0,6,0.
I think I messed up somewhere with the variables with i or j or the number 1 and possibly their locations... can anyone help lead me in the right direction?

scores[1] % 2 == 0 and newScores[1] = scores[i]?
You have hard-coded to use only index 1 (the second element) of newArray.
You probably should be using j as the index instead of 1.

Your last loop uses 1 as fixed loop index.
Change that to i instead.

Change the second for loop like this -
for (int i = 0; i < scores.length; i++) {
if (scores[i] % 2 == 0) {
newScores[j] = scores[i];
j++;
}
}
Cheers!

instead of
if(scores[1] % 2 ==0) {
newScores[1] = scores[i];
It should be
if(scores[i] % 2 ==0) {//← i here
newScores[j] = scores[i];//← j here
O/P : 2 4 6

Related

Loop not properly modifying array elements

The loop causing issues is the second for loop.
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int controlValue;
int i;
controlValue = scnr.nextInt();
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
}
for (i = 0; dataPoints[i] < controlValue; ++i) {
dataPoints[i] = dataPoints[i] * 2;
}
for (i = 0; i < dataPoints.length; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
}
}
Currently when i run the test, this is what pops up.
Testing with inputs: 10 2 12 9 20
Output differs.
Your output
4 12 9 20
Expected output
4 12 18 20
the first number in the list of inputs is the maximum number it should multiply by 2. Since 20 is > 10, it is not multiplied. However 9 should be multiplying to 18, but it is not. If anyone could give some insight into anything i might be doing wrong when forming this loop, I would greatly appreciate it. Thank you!
Your second for loop is exiting because of the condition and the order of your input data, and will stop when a control value is reached. For example, if you instead had an input of 10 1 2 3 4, you would get the results you expect (ie. 2 4 6 8), but your for loop is exiting when the condition dataPoints[i] < controlValue is reached (in your case at 12).
Instead you should loop through the entire dataPoints array, as you do in your 3rd loop, and check the controlValue before doubling the values.
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int controlValue;
int i;
controlValue = scnr.nextInt();
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
}
for (i = 0; i < dataPoints.length; ++i) {
if (dataPoints[i] < controlValue) {
dataPoints[i] = dataPoints[i] * 2;
}
}
// This could be combined into the loop above...
for (i = 0; i < dataPoints.length; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
}
}
You could also do all of this in a single loop if you wanted to, for example:
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
if (dataPoints[i] < controlValue) {
dataPoints[i] = dataPoints[i] * 2;
}
System.out.print(dataPoints[i] + " ");
}

Function takes a martix (2d array) and prints the max number of the even numbers in each line

I am defining a function to accept a matrix (2d array), for example x[][]; and the function should print the biggest even number in each line
public static void biggestEvenNumOfEachLine(int x[][]){
int even,t=0,max;
int arr[] = new int [x.length];
for(int i = 0; i < x.length;i++){
for(int j = 0; j < x[i].length;j++,t++){
if(x[i][j] % 2 == 0){
even = x[i][j];
arr[j] = even;
}
}
}
}
What am I missing?
I would start by finding the biggest even number in a single line array. Start with the smallest possible value, and then iterate the array. Test for even, and then set the max (and then return it). Something like,
private static int biggestEvenNum(int[] x) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
if (x[i] % 2 == 0) {
max = Math.max(max, x[i]);
}
}
return max;
}
But, in Java 8+, I would prefer to filter for even values and get the max like
private static int biggestEvenNum(int[] x) {
return IntStream.of(x).filter(v -> v % 2 == 0).max().getAsInt();
}
Then your method is as simple as iterating the line(s) in your matrix, printing the result. Like,
public static void biggestEvenNumOfEachLine(int[][] x) {
for (int[] line : x) {
System.out.println(biggestEvenNum(line));
}
}
public static void biggestEvenNumOfEachLine(int x[][])
{
int arr[] = new int [x.length];
for(int i = 0; i < x.length;i++)
for(int j = 0; j < x[i].length;j++)
if(x[i][j] % 2 == 0 && x[i][j] > arr[i]){
arr[i] = x[i][j];
System.out.println(arr[i]);
}
}
This will work but if there is no even number at particular line then corresponding number to that line will be zero.

Java: Shuffling Cards in a Deck using Arrays

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.

Print all the combinations of elements in matrix of size m * n

Print all the combinations of elements in matrix of size m * n
Sample Example:
1 3 5
2 6 7
Expected Output:
1 , 3 , 5
1 , 3 , 7
1 , 6 , 5
1 , 6 , 7
2 , 3 , 5
2 , 3 , 7
2 , 6 , 5
2 , 6 , 7
Rules:
Every combination starts from left of matrix and proceeds towards right. It may switch rows though.
Every combination should have number of elements equal to number of columns.
A combination can't have an element from the same column present twice.
Number of columns and rows could vary. So solution has to be generic.
import java.util.Scanner;
class Combination {
public static void main(String args[]) {
int row, col, i, j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix:\n");
row = in.nextInt();
col = in.nextInt();
int first[][] = new int[row][col];
System.out.println("Enter the elements if matric m*n:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
first[i][j] = in.nextInt();
}
}
System.out.println("Matrix:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
System.out.print(first[i][j] + "\t");
}
System.out.println();
}
// Final Logic from here...
System.out.println("\nOut Matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
System.out.println(first[i][0] + "," + first[j][1] + ","
+ first[k][2]+"\n");
}
}
}
/* while (i < 2) {
j = 0;
while (j < 2) {
k = 0;
while (k < 2) {
System.out.println(first[i][0] + "," + first[j][1] + ","
+ first[k][2]);
k++;
}
j++;
}
i++;
}*/
in.close();
}
}
Works good for specific input but not able to do it dynamic....Need Help..
Thanks in Advance......
You could use recursion as follows:
...
// Final Logic from here...
System.out.println("\nOut Matrix:\n");
int[] outputRow = new int[col];
print(0, row, col, first, outputRow);
}
private static void print(int j, int row, int col, int[][] first, int[] outputRow) {
for (int i = 0; i < row; i++) {
outputRow[j] = first[i][j];
// recursively continue to populate outputRow until we reach the last column (j == col -1)
if (j < col - 1) {
print(j + 1, row, col, first, outputRow);
}
// we have reached the last column (j == col -1) so now we could print current permutation
if (j == col - 1) {
for (int k = 0; k < col; k++) {
System.out.print(" " + outputRow[k]);
}
System.out.println();
}
}
}
Here we process one column per recursion call starting with j==0.
outputRow stores the current permutation and is updated recursively.
When we recursively reach the last column then it's time to print the current permutation.
This is a possible approach
void printCombos(){
visit(0,-1,"");
}
void visit(int r,int c,String s){
if(c!=a[0].length-1)
for(int i=0;i<a.length;i++)
visit(i,c+1,s+" - "+a[i][c+1]);
else
System.out.println(s);
}
considering the matrix as a tree to deep-visit. Given an imaginary root * these are the edges (*,1) - (*,2) - (1,3) - (1,6) - (2,3) - (2,6) and so on
* --- 1 -- 3 -- 5
\ \/ \/
\ /\ /\
\ 2 -- 6 -- 7
with 5 and 7 being the leaves.
First create one more method :
private static void increasePointerArray(int[] poinerArray, int row)
{
for (int i = poinerArray.length-1; i >= 0; i--) {
if(poinerArray[i] == row-1) {
continue;
}
else {
poinerArray[i] = poinerArray[i] +1;
for (int j = i+1; j < poinerArray.length; j++) {
poinerArray[j] = 0;
}
break;
}
}
}
Now in final logic section put below code :
int[] poinerArray = new int[col];
int[] MaxArray = new int[col];
List<int[]> resultList = new ArrayList<int[]>();
Arrays.fill(poinerArray, 0);
Arrays.fill(MaxArray, row-1);
while(!Arrays.equals(poinerArray, MaxArray)) {
resultList.add(poinerArray.clone());
increasePointerArray(poinerArray, row);
}
resultList.add(poinerArray.clone());
System.out.println("Printing desired result : ");
for (int[] ks : resultList) {
StringBuffer sb = new StringBuffer();
for (j = 0; j < col; j++) {
sb.append(first[ks[j]][j]+"\t");
}
System.out.println(sb.toString());
sb = null;
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Permutations{
public static String strings="";
public static ArrayList<String> out=new ArrayList<String>();
public static void gen(ArrayList<ArrayList<String>> x,int index){
for(int i=0;i<x.size();i++){
if(i>0){
String[] parts=strings.split(",");
strings="";
for(int k=0;k<parts.length;k++){
if(k==index)
break;
strings=strings+parts[k]+",";
}
}
if(index==x.get(0).size()-1){
strings=strings+(x.get(i).get(index));
out.add(strings);
}
else
strings=strings+(x.get(i).get(index))+",";
if(index+1<=x.get(0).size()-1)
gen(x,index+1);
}
}
public static void main(String[] args) throws IOException{
ArrayList<ArrayList<String>> x=new ArrayList<ArrayList<String>>();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line;
while(true){
line=br.readLine();
if(line.contentEquals("")) break;
String[] parts=line.split(" ");
x.add(new ArrayList<String>());
for(int i=0;i<parts.length;i++){
x.get(x.size()-1).add(parts[i]);
}
}
gen(x,0);
for(int i=0;i<out.size();i++){
System.out.println(out.get(i));
}
}
}
This code is works. Its very generic and quite simple to understand. I did column wise permutations on the 2D Array.

Mirrored Triangle generation in java

I happened to appear for a test and got the following as question. I am unable to figure out how to proceed. The scenario is to write a java program that prints the following with respective N. If suppose N=3, it must have 2*N rows and output must be,
1
2*3
4*5*6
4*5*6
2*3
1
Output must consist only numbers and asterisk. N varies between 0 to 100. Also, given
public static void main(String[] args){
int rows=2;
mirrorTriangle(rows);
}
public void mirrorTriangle(int n){
//Logic
}
I don't understand why is that rows declared as 2 if rows are supposed to be varying with N. Please explain the logic.
Please find the solution to your problem, with explanation comments.
public static void main(String[] args) throws Exception
{
// initialize n
int n = 4;
// initialize x to 1 from where our printing will start.
int x = 1;
/* We will store our generated numbers in an array.
* For example, the array after we generate
* the numbers would look like:
* [1,0,0,
2,3,0,
4,5,6,
4,5,6,
2,3,0,
1,0,0]
*
* When n = 3, there are going to be 3*2 i.e, n*2 rows.
* in our case 6 rows.
* visualize with the above values.
* The first n/2 rows will be the numbers we print,
* the next n/2 will be the mirror image of the first n/2 rows.
* no. of columns in each row will be equal to n, in our example:3
*/
int arr[][] = new int[n*2][n];
/*
* Start populating the matrix
* Each row will contain number of elements eaual to the row number,
* so 1st row -> 1 element, 2nd - > 2,.. and so on.
*/
for(int row=0;row<n;row++)
{
int col = 0;
while(col < row+1)
{
arr[row][col] = arr[n*2-row-1][col] = x++;
col++;
}
}
/*
* Now our task is just to read out the array.
* The tricky part is adding the astricks.
* We notice that row1 will have 1-1 asticks, row2 -> 2-1 astricks ,.. and so on.
* So in between the numbers while reading out,
* for each row we maintain the number of astricks.
*/
for(int i=0;i<arr.length;i++)
{
StringBuilder build = new StringBuilder();
for(int j=0;j<arr[i].length;j++)
{
if(arr[i][j] > 0)
{
build.append((arr[i][j])).append("*");
}
}
System.out.print(build.delete(build.length()-1,build.length()).toString());
System.out.println();
}
}
o:p for n=4:
1
2*3
4*5*6
7*8*9*10
7*8*9*10
4*5*6
2*3
1
def N = 3
def i = 0
def j = 0
int[][] numbers = new int[N][]
// Generate, print, and store numbers
while( i < numbers.length ){
numbers[i] = new int[i+1]
j = 0
while( j < numbers[i].length ){
numbers[i][j] = j+1
++j
print j
}
println ""
i++
}
// Print them again, in reverse order
i = numbers.length - 1
while( i >= 0 ){
j = 0
while( j < numbers[i].length ){
print numbers[i][j]
j++
}
println ""
i--
}
Output:
1
12
123
123
12
1
The code is pretty self-explanatory. You need just N rows but print 2N because, wait for it ... symmetry. If you have 6 rows, first 3 are new while the other 3 are just mirrored images so why waste the memory space when you can just print them again?
Is there an explicit requirement for recursion? It is implied by the structure of the problem not mentioned anywhere.
int rows=2 is an example probably, for the purposes of the problem you can't do anything 'smart' like using pointers ...
I will also assume that you are not permitted to use values '> 100' so that you can overload the meaning of the n value - same goes for 2's complement.
If you allow for looping, as a substitute for recursion you can generate the triangle without having to save state outside of the stack:
public static void main(String[] args){
int rows=3;
mirrorTriangle(rows);
}
public static void mirrorTriangle(int n){
for (int i = 0 ; i < n + 1 ; i++) {
renderLine(i);
}
for (int i = n ; i > 0 ; i--) {
renderLine(i);
}
}
private static void renderLine(int n) {
int j = n * (n - 1) / 2 + 1;
int k = j + n;
while (j < k) {
System.out.print(j);
j++;
if (j < k) System.out.print('*');
}
System.out.println();
}
Try this fresh code:
public class String4 {
public static void main(String[] args) {
int rows = 3;
mirrorTriangle(rows);
}
private static void mirrorTriangle(int rows) {
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(i);
if(j>0&&j<i)
System.out.print("*");
}
System.out.println();
}
for(int k=rows;k>0;k--)
{
for(int l=1;l<=k;l++)
{
System.out.print(k);
if(l>0&&l<k)
System.out.print("*");
}
System.out.println();
}
}
}
Output:
1
2*2
3*3*3
3*3*3
2*2
1
I think this is a better and simple solution than the chosen one.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter limit");
int limit = s.nextInt();
int start[] = new int[limit];
int v = 1;
for (int i=1; i<=limit; i++) {
start[i-1] = v;
for (int j=1; j<=i; j++) {
System.out.print(v++);
if(j==i)
continue;
System.out.print("*");
}
System.out.print("\n");
}
for (int i=limit-1; i>=0; i--) {
v=start[i];
for (int j=i; j>=0; j--) {
System.out.print(v++);
if(j==0)
continue;
System.out.print("*");
}
System.out.print("\n");
}
}

Categories