Shuffling array.Output not correct - java

I have been working on this program and randomly shuffles the contents of an array of integers.
This is what is supposed to look like:
Array contents: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Do you wish to shuffle these numbers? y
Array contents: 5 12 7 10 6 9 15 1 13 3 4 11 14 2 8
Do you wish to shuffle these numbers? y
Array contents: 2 9 15 4 12 11 3 7 10 8 1 6 13 5 14
Do you wish to shuffle these numbers? n
This is what im getting:
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Do you wish to shuffle these numbers? y
Exception in thread "main" java.lang.NumberFormatException: For input string: "y"
and says build failed
This is the main code:
public class Evao1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shuffler myShuffler = new Shuffler(size);
Scanner input = new Scanner(System.in);
for(;;) {
myShuffler.display();
System.out.println();
System.out.print("Do you wish to shuffle these numbers? ");
String value = input.next();
if (value.equals("q")) break;
int value1 = Integer.parseInt(value);
}
}
}
Here is the additional class:
public class Shuffler {
private int[] data;
public Shuffler(int size){
data = new int[size];
for (int i = 0; i < size; i++)
{
data[i] = i + 1;
}
}
public void shuffle(){
for (int i = 0; i < data.length; i++)
{
Random r = new Random(15);
int second = r.nextInt(15) + 1;
int temp = data[i];
data[i] = data[second];
data[second] = temp;
}
}
public void display()
{
String values = "";
for (int i = 0; i < data.length; i++)
{
if (i < 15)
{
values += (i + 1);
if (i < 14)
{
values += ", ";
}
}
}
System.out.printf("Array Contents: %s \n", values);
}
}

The problem is with the last two lines of your for loop in the Evao1 class.
First, I think you meant to write if (value.equals("n")) break;
Second, instead of int value1 = Integer.parseInt(value);
Just do myShuffler.shuffle();
Also, in the for loop of display() you aren't actually displaying anything from the data array.
Change values += (i + 1); to values += data[i];

Related

Segregate_even_odd_numbers

given an array of integers, segregate even and odd numbers in the array. All the even numbers should be present first, and then the odd numbers.
Examples:
Input: arr[] = 1 9 5 3 2 6 7 11
Output: 2 6 5 3 1 9 7 11
Input: arr[] = 1 3 2 4 7 6 9 10
Output: 2 4 6 10 7 1 9 3
public class Segregate_even_odd_numbers {
public static void main(String[] args) {
int a[]= { 1, 3, 2, 4, 7, 6, 9, 10 };
int n=a.length;
int ind=0;
for(int i=0;i<n;i++){
if(a[i]%2==0){
a[ind]=a[i];
ind++;
}
}
for(int i=0;i<n;i++){
if(a[i]%2!=0){
a[ind]=a[i];
ind++;
}
}
for(int i=0;i<n;i++){
System.out.println(a[i] + " ");
}
System.out.println("");
}
}
I am getting output like this
2
4
6
10
7
9
9
10
0th index and 1st index not calculate.
what mistake I made, please guide me.
You're program is almost correct, but needs little modification, below is the implementation and explanation
public class Segregate_even_odd_numbers {
public static void main(String[] args) {
int a[] = { 1, 9, 5, 3, 2, 6, 7, 11 };
int n = a.length;
int evenIndex = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
int temp = a[i];
a[i] = a[evenIndex];
a[evenIndex] = temp;
evenIndex++;
}
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
} }
What are we doing here:
We maintain a evenIndex pointer at 0 index
Whenever we find any Even value we swap it with evenIndex i.e.., arr[evenIndex] = arr[i] and place arr[i] = arr[evenIndex]
This code works does not modify any values if you pass an array with only Even Numbers or Odd Numbers
Time Complexity : O(n)
Space Complexity : O(1)
This can also be accomplished by sorting the array based on the value of each element modulo 2.
int[] a= { 1, 3, 2, 4, 7, 6, 9, 10 };
int[] res = Arrays.stream(a).boxed().sorted(Comparator.comparingInt(x -> x & 1))
.mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(res));

Find all combinations with repetitions but without duplicate rows

There is an array of 1, 2, 3, 4. It is necessary to make all possible combinations of 3 size series, the elements can be repeated. The order of the elements in the row is not important. For instance:
114 = 411 = 141.
I can't find a suitable algorithm. I have found this algorithm, but there can be no repetitions of elements, like 111 or 113, only 123,124 etc.
public void doit(){
String[] arr = {"1", "2", "3","4"};
int count = fuctorial(arr.length);
int max = arr.length - 1;
System.out.println("Вариантов " + count);
int shift = max;
String t;
while (count > 0) {
t = arr[shift];
arr[shift] = arr[shift - 1];
arr[shift - 1] = t;
print(arr);
count--;
if (shift < 2) {
shift = max;
} else {
shift--;
}
}
}
static void print(String[] arr) {
System.out.println(Arrays.toString(arr));
}
static int fuctorial(int n) {
return (n > 0) ? n * fuctorial(n - 1) : 1;
}
Try this.
static void combination(int[] a, int n) {
int size = a.length;
int[] selected = new int[n];
new Object() {
void print() {
for (int i = 0; i < n; ++i)
System.out.print(a[selected[i]] + " ");
System.out.println();
}
void combination(int index, int prev) {
if (index >= n)
print();
else
for (int i = prev; i < size; ++i)
combination(index + 1, selected[index] = i);
}
}.combination(0, 0);
}
and
int[] a = {6, 7, 8, 9};
combination(a, 3);
output:
6 6 6
6 6 7
6 6 8
6 6 9
6 7 7
6 7 8
6 7 9
6 8 8
6 8 9
6 9 9
7 7 7
7 7 8
7 7 9
7 8 8
7 8 9
7 9 9
8 8 8
8 8 9
8 9 9
9 9 9
public void func() {
boolean[] check = new boolean[49];
for(int i=1; i <=4; i++ ) {
for(int j=1; j <=4; j++) {
for(int k=1; k<=4; k++) {
int sum = i*i + j*j + k*k;
if(!check[sum]) {
check[sum] = true;
System.out.println(i + "," + j + "," + k);
}
}
}
}
}
idea is: we take a triplet, calculate the sum of squares, and check if we already had a triplet with that sum. identical triplets will have the same sum of squares.
the sum of squares will always be in the range 3-48. also, the sum is unique to each combination of numbers just like you require.
Complexity is O(N^3) where N is the size of the array. since we need combinations of 3 elements, i don't think you can go below that.
UPDATE: to make is more general, use a HashSet for the sums instead of the boolean array, and iterate 3 nested loops over the input array. calculate the sum of squares and check against the HashSet.
Performance Optimization: calculate the squares of each element in the array in advance so you dont have to calculate them over and over again.

Is String to int Array conversion possible?

I've written that piece of code in which I scanned an integer suppose 121 and for dividing it into 3 part I make it a String and tried to convert it again by splitting.But I am not getting the way? Is there any simple way to make it so?
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt() ;
int sum = 0;
for(int i = 1 ; i<=n; i++){
String s = Integer.toString(i);
int[] c = Integer.parseInt(s.split("")); //Here's the problem
int sm = 0 ;
for(int x :c){
sm +=x ;
}
System.out.print(sm+" ");
}
}
input = 12
expected output: 1 2 3 4 5 6 7 8 9 1 2 3
output : Main.java:14: error: incompatible types: String[] cannot be
converted to String
int[] c = Integer.parseInt(s.split(""));
Your expected output would not even seem to need any integer to string conversion:
int n = scan.nextInt();
for (int i=0; i < n; i++) {
if (i > 0) System.out.print(" ");
System.out.print(1 + i % 9);
}
For an input of n = 12, this prints:
1 2 3 4 5 6 7 8 9 1 2 3
You can't pass the whole array to parseInt(). You need to parse each element individually:
int[] c = Arrays.stream(s.split(""))
.mapToInt(Integer::parseInt)
.toArray();
Or the old-fashioned way:
String[] chars = s.split("");
int[] c = new int[chars.length];
for (int i = 0; i < c.length; i++) {
c[i] = Integer.parseInt(chars[i]);
}
You could map each character from the String[] (from the split) to an int, and then convert that to an int[]. Like,
int[] c = Arrays.stream(s.split("")).mapToInt(Integer::parseInt).toArray();
with no other changes, that produces (as requested)
1 2 3 4 5 6 7 8 9 1 2 3
With input of "12".
You can also do it like this using an IntStream.
int n = 12;
int[] values = IntStream.range(0, n).map(i -> i % 9 + 1).toArray();
System.out.println(Arrays.toString(values));
Produces
[1 2 3 4 5 6 7 8 9 1 2 3]
for n = 12

Shifting an array. Output is not correct.

I have been working on this program and will display the array contents to the user and ask how many positions he would like to shift off the right side of the array, and replace onto the left side.
This is what is supposed to look like:
Array contents: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Shift how many positions? 5
Array contents: 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10
Shift how many positions? 2
Array contents: 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8
Shift how many positions? 0
Array contents: 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8
Shift how many positions? -8
Array contents: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1
Shift how many positions? 15
Array contents: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1
Shift how many positions? 17
Array contents: 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Shift how many positions? q
And im getting this:
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Shift how many positions?5
Array Contents: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Here is the main class:
public class Shift1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shifter test = new Shifter(size);
test.display();
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Shift how many positions?");{
int value1 = input.nextInt();
test.shift(value1);
test.display();
}
}
}
And here is additional class:
public class Shifter
{
public int [] data=new int[15];
public Shifter()
{
int size=0;
}
public Shifter(int size){
for (int i = 0; i < data.length; i++)
{
Random r = new Random(15);
int second = r.nextInt(15) + 1;
int temp = data[i];
data[i] = data[second];
data[second] = temp;
}
}
public void shift(int pos){
for(int x=0; x<pos; x++)
{
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--)
{
data[cnt] = data[cnt]-1;
}
data[0] =temp;
}
}
public void display(){
String values = "";
for (int i = 0; i < data.length; i++)
{
if (i < 15)
{
values += (i + 1);
if (i < 14)
{
values += ", ";
}
}
}
System.out.printf("Array Contents: %s \n", values);
} }
Introduce a loop in main() method.
Firstly read as string in order to recognize q.
Implement Shifter.shift() properly.
Add a space after the prompt.
Initialize the array properly.
Implement Shifter.display() properly.
Corrected codes:
public static void main(String[] args) {
Scanner kp = new Scanner(System.in);
final int size = 15;
char q = 'y';
boolean flag = false;
Shifter test = new Shifter(size);
Scanner input = new Scanner(System.in);
for(;;) {
test.display();
System.out.println();
System.out.print("Shift how many positions? ");
String value = input.next();
if (value.equals("q")) break;
int value1 = Integer.parseInt(value);
test.shift(value1);
}
}
public Shifter(int size){
for (int i = 0; i < data.length; i++)
{
data[i] = i + 1;
}
}
public void shift(int pos){
int max = pos % data.length;
if (max < 0) max += data.length;
for (int x=0; x<max; x++)
{
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--)
{
data[cnt] = data[cnt-1];
}
data[0] =temp;
}
}
public void display(){
String values = "";
for (int i = 0; i < data.length; i++)
{
values += " ";
if (data[i] < 10) values += " ";
values += data[i];
}
System.out.printf("Array Contents: %s \n", values);
}
Though there are more points to be improved, this works as you said.
for(int x=0; x<pos; x++) {
int cnt = data.length-1;
int temp = data[cnt];
for(cnt=data.length-1; cnt>0; cnt--) {
data[cnt] = data[cnt]-1;
}
data[0] =temp;
}
In your shift method you should be utilizing your x for loop variable. cnt and temp are always the same no matter what. So your not really doing anything in this loop.
If your allowed to use something other than an Array, maybe take a look at using a List. It has a unique method such as
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#add(int,%20E)
which will allow you to add a number at the 0 index and it will auto shift the existing values right. So pop a value off the end and move it to the front size amount of times.

Printing a number triangle

CS student here. I've just received an introduction to loops and I'm not sure I understand them very well. I'm trying to print a triangle of numbers n, such that if n = 4 you'd get something like this:
4
3 7
2 6 9
1 5 8 10
Instead I'm winding up with something like:
4
3 5
Suffice it to say I'm lost. Here's my code:
void drawT3 (int n)
{
int k = 1;
int t = 1;
for (int i=1;i<=n;i++)
{
k = n;
int j;
for (j=1;j<=n-i;j++)
System.out.print(" ");
for (j=1;j<=t;j++)
{
System.out.printf("%3d",k);
k += (n - j);
}
n--;
t++;
System.out.println();
}
}
void printTriangle(int n)
{
// build an auxiliary 2D array
final int t[][] = new int[n][n];
int i = 1;
for (int s = n - 1; s <= 2 * (n - 1); s++)
{
for (int x = s - n + 1; x < n; x++)
{
t[x][s - x] = i++;
}
}
// print the array
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
if (t[x][y] > 0)
{
System.out.printf("%3d", t[x][y]);
}
else
{
System.out.printf(" ");
}
}
System.out.println(); // start new line
}
}
Build an auxiliary 2D array of size n.
Put numbers into array as human will do, from 1 to n, following the diagonals. s in the code represents x + y sum. That sum is constant for every diagonal. In the first diagonal (the longest one) sum is equal to n - 1. In the second diagonal sum is 1 more, n. In the last "diagonal" (bottom right corner) the sum is 2 * (n - 1). That's exactly our loop: for (int s = n - 1; s <= 2 * (n - 1); s++). Having the sum and x we can obtain y with simple subtraction, y = s - x.
Print the array. Each cell of array is initialized with 0 (int's default value). So, if a cell has zero, we just print 3 spaces, to preserve the shape of triangle.
PS. My code was written for "educational purposes" :) To show how it can be done, in easy way. It's not optimized for speed nor memory.
public static void main(String[] args) {
// TODO code application logic here
triangle(4);
}
static public void triangle(int n){
int x = 0;
for (int i = n;i>0;i--){
System.out.print(i + " ");
x = i+n;
for (int j=0;j<n-i;j++){
System.out.print(x - j + " ");
x = x + n -j;
}
System.out.println("");
}
}
Output for 4:
4
3 7
2 6 9
1 5 8 10
Output for 6:
6
5 11
4 10 15
3 9 14 18
2 8 13 17 20
1 7 12 16 19 21
Observe that there are many ways to print out a triangle of numbers as described above, For example, here are two,
// for n=5,
// 1 2 3 4 5
// 6 7 8 9
// 10 11 12
// 13 14
// 15
And
// 5
// 4 9
// 3 8 12
// 2 7 11 14
// 1 6 10 13 15
And since recursion is Fun!
class triangle
{
//Use recursion,
static int rowUR( int count, int start, int depth )
{
int ndx;
if(count<=0) return start;
//-depth?
for (ndx=0;ndx<depth;ndx++)
{
System.out.print(" ");
}
//how many? 5-depth, 5,4,3,2,1
for( ndx=0; ndx<count; ++ndx )
{
System.out.printf("%3d",start+ndx);
}
System.out.printf("\n");
if( count>0 )
{
rowUR( count-1, ndx+start, depth+1 );
}
return ndx;
}
//Use recursion,
static int rowLR( int count, int start, int depth )
{
int ndx, accum;
if( start < count )
rowLR( count, start+1, depth+1 );
for( ndx=0; ndx<depth; ++ndx )
{
System.out.print(" ");
}
accum=start;
//how many? 5-depth, 1,2,3,4,5
for( ndx=0; ndx<(count-depth); ++ndx )
{
System.out.printf("%3d",accum);
accum+=count-ndx;
}
System.out.printf("\n");
return ndx;
}
public static void main(String[] args)
{
int count=4, depth=0, start=1;
System.out.printf("rowUR\n");
rowUR( count=5, start=1, depth=0 );
System.out.printf("rowLL\n");
rowLL( count=5, start=1, depth=0 );
}
};
int n=4,i,j,k,t;
for (i=n;i>=1;i--)
{
t=i;
k=n;
for(j=1;j<i;j++)
System.out.printf(" "); // for leading spaces
System.out.printf("%3d",i); // for first digit(or number) in each row (in your example these are 4,3,2,1)
for(j=i;j<n;j++)
{
t+=k;
System.out.printf("%3d",t);
k--;
}
System.out.print("\n");
}
OUTPUT:
for n=8
8
7 15
6 14 21
5 13 20 26
4 12 19 25 30
3 11 18 24 29 33
2 10 17 23 28 32 35
1 9 16 22 27 31 34 36
http://ideone.com/C1O1GS
make space around numbers according to your need.
PS: I would never suggest to write any pattern code using array unless it is very complicated. array will use extra memory space.

Categories

Resources