If a user inputs some numbers like this (number of lines are arbitrary):
1
2
3
4
5
I need to create a method that makes a series of outputs like this:
First output:
1
2
3
4
5
Second output:
2
1
3
4
5
Third output:
4
3
2
1
5
Fourth output:
5
4
3
2
1
I'm just confused with the pattern that is being utilized here.
I think you must flip from the middle on each iteration i the sub sequence from 0 to i*2 -1.
Pseudo code assuming that seq is the input sequence:
void pattern(seq){
print(seq)//First output
for(int i=1;i*2<=seq.length-1;i++){
seq = concatenate(seq.subSquence(i,i*2-1), seq.subSquence(0,i-1), seq.subSquence(i*2,seq.length-1) );
print(seq)
}
seq = concatenate(seq.subSquence(i,seq.length-1), seq.subSquence(0,i-1))
print(seq)//Last output
}
What you have to do is to take always next_element from original structure (array, list) and place it top.(others elements goes down by 1 till next element initial position)
next_element is start from second_position and it's increment by 1 till the end of structure (length or size)
import java.util.Arrays;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args)
{
int a1[] = {1,2,3,4,5};
new Test().compute(a1);
int a2[] = {5,4,3,2,1};
new Test().compute(a2);
}
public void compute(int[] a)
{
for(int i=1;i<a.length;i++)
{
//i : next_element which will be place always on first_position
int temp= a[i];
//j : current_element (iterate by till next_element)
for(int j=i; j>0; j--)
{
a[j] = a[j-1];
}
a[0] = temp;
String str = Arrays.stream(a).boxed().map(t->String.valueOf(t)).collect(Collectors.joining(","));
System.out.println("step="+i+": array="+str);
}
}
}
Output
step=1: array=2,1,3,4,5
step=2: array=3,2,1,4,5
step=3: array=4,3,2,1,5
step=4: array=5,4,3,2,1
and (reverse)
step=1: array=4,5,3,2,1
step=2: array=3,4,5,2,1
step=3: array=2,3,4,5,1
step=4: array=1,2,3,4,5
Related
The following is no homework. I'm just trying to write my own permutation code. I have an idea but I have problems in writing this idea as code.
As example the input is myArray={1,2,3};
Then the output is supposed to be:
1 2 3
2 1 3
2 3 1
3 2 1
3 1 2
1 3 2
I figured out it's possible by switching the first element with second, then switch second with third (however not entirely possible, but I know I need this).
That's why my question is how can I do this in Java?
I have 1 2 3 and I want switch first element with second, so I get 2 1 3. Print this. Now I want switch second element with third, I get 2 3 1, print it. Repeat n! times where n is myArray length.
I tried to do this with the following code but it seems like I'm far away from it :(
public class Test{
public static void main(String[] args){
int[] myArray = {1,2,3};
for(int x=0; x<6; x++){
for(int i=0; i<myArray.length-1; i++){
int temp=myArray[i];
myArray[i]=myArray[i+1];
myArray[i+1]=temp;
}
for(int i=0; i<myArray.length; i++){
System.out.print(myArray[i]+" ");
}
System.out.println("");
}
}
}
Output:
2 3 1
3 1 2
1 2 3
2 3 1
3 1 2
1 2 3
I'm not sure if I understood correctly though.
public static void main(String[] args) {
int[] myArray = {1, 2, 3};
for (int i = 0; i < 6; i++) {
print(myArray);
int temp = myArray[i % myArray.length];
myArray[i % myArray.length] = myArray[(i + 1) % myArray.length];
myArray[(i + 1) % myArray.length] = temp;
}
}
private static void print(int[] array) {
for (int anArray : array) {
System.out.print(anArray + " ");
}
System.out.println("");
}
EDIT:
I noticed, there is a wrong order, so it should be better:
public static void main(String[] args) {
int[] myArray = {1, 2, 3};
for (int i = 0; i < 6; i++) {
int idx = i % (myArray.length - 1);
print(myArray);
int temp = myArray[idx];
myArray[idx] = myArray[idx + 1];
myArray[idx + 1] = temp;
}
}
I am a beginner in Java. I was wondering how I would print the last couple of values for this reverse arrayList since they are not part of a successive sequence of 4. I was thinking of using if (numbers.size()%4==0) but I dont know where to properly implement it.
import java.util.*;
public class printArray {
public static void main(String[] args) {
ArrayList <Integer> numbers= new ArrayList<>();
numbers.add(10);
numbers.add(13);
numbers.add(2);
numbers.add(8);
numbers.add(7);
numbers.add(90);
numbers.add(-1);
numbers.add(2);
numbers.add(4);
numbers.add(5);
System.out.println(numbers);
System.out.println(reverse4(numbers));
}
public static ArrayList<Integer> reverse4 (ArrayList<Integer> numbers){
ArrayList< Integer> reverseSet= new ArrayList<>();
for (int i = 0; i < numbers.size(); i += 4) {//goes from 0 to 4, 4 to 8 and keeps incrementing by 4
for (int k = i + 3; k >= i ; k--)// reverse order, executes 4 times before going to the outer loop
reverseSet.add(numbers.get(k));
}
return reverseSet;
}
}
You could check if k is within range
if (k < numbers.size())
before you do the reverseSet.add().
Edit: sorry, misunderstood what you're doing. You want to reverse any full sets of four, but not any partial sets at the end, it sounds like.
So, count:
position | 1 2 3 4 | 5 6 7
---------+----------------------------+--------------------
count | size-7 size-6 size-5 size-4|size-3 size-2 size-1
last
one
position | 1 2 3 4 | 5 6
---------+----------------------------+--------------------
count | size-6 size-5 size-4 size-3|size-2 size-1
last
one
position | 1 2 3 4 | 5
---------+----------------------------+--------------------
count | size-5 size-4 size-3 size-2|size-1
last
one
position | 1 2 3 4 |
---------+----------------------------+--------------------
count | size-4 size-3 size-2 size-1|
last
one
It looks like the last valid value of i should always be less than the size of the array minus three (unless the ArrayList is too short, but you'd need different code for that—my previous answer should work there). So instead of what I said above, replace i < numbers.size() with i < numbers.size() - 3.
Here is the changed reverse4 method :
public static ArrayList<Integer> reverse4(ArrayList<Integer> numbers) {
ArrayList<Integer> reverseSet = new ArrayList<>();
for (int i = 0; i < numbers.size(); i += 4) {
if (i + 3 < numbers.size()) { // check if remaining number of elements less than 4
for (int k = i + 3; k >= i; k--)
reverseSet.add(numbers.get(k));
} else {
for (int k = i; k < numbers.size(); k++) {
reverseSet.add(numbers.get(k)); // add the remaining elements without reversing
}
}
}
return reverseSet;
}
Note the new conditions to check if the list has 4 remaining elements.
I know there is another thread with the same name, but the answer isn't really the one I'm looking for.
I can only use for loops. The other answer uses complex syntax like:
reverse = !reverse ? i == max : reverse;
i = reverse ? i-1 : i+1;
Can it be simpler than that?
Thanks a lot.
So, this is the output.
I can only get until 4 I don't know how to keep from there...
1
1 2
1 2 3
1 2 3 4
1 2 3
1 2
1
This is what I have so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=1;i<=4;i++) {
for(int j = 1; j <= i; j++) System.out.print(j+" ");
System.out.println("");
}
for(int i=4;i>=1;i--){
for(int j = 1; j <= i; j++) System.out.print(j+" ");
System.out.println("");
}
}
}
but my output is the following:
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1
Hii have done using the below code
public class Test
{
public static void main(String args[]) {
int j,i;
int max=4;
int n=0;
for(i=0;i<((max*2)-1);i++)
{
if(i<max)
n++;
else
n--;
for(j=1;j<=n;j++)
{
System.out.print(j+" ");
}
System.out.println("");
}
}
}
The below is the outputYou can generalize it for any number i hope this is fine
Your two outer loops are:
for(int i=1;i<=4;i++) {
for(int i=4;i>=1;i--) {
This will generate the sequence 1, 2, 3, 4, 4, 3, 2, 1. If you want to only have one 4-length row in the output, change the second loop to:
for(int i=3;i>=1;i--) {
so that it starts from 3, instead of 4. The problem is that currently, both your outer loops generate the value 4 right after one another.
I have this code for insertion sort which is failing to give an output for a test case..
import java.io.*;
import java.util.*;
public class Solution {
public static void insertionSortPart2(int[] ar)
{
// Fill up the code for the required logic here
// Manipulate the array as required
// The code for Input/Output is already provided
int n =ar.length;
for(int i=1;i<n;i++)
{int k= ar[i];
int j=i-1;
while(ar[j]>k && j>-1)
{
ar[j+1]=ar[j];
j--;
}
ar[j+1]=k;
printArray(ar);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] ar = new int[s];
for(int i=0;i<s;i++){
ar[i]=in.nextInt();
}
insertionSortPart2(ar);
}
private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
}
The test case for which this does not return an output is
9 8 6 7 3 5 4 1 2
error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
I cannot figure out why..
It works correctly for 1 4 3 5 6 2
Issue is with your while loop and this is the line where you might be getting exception while(ar[j]>k && j>-1). You are trying to access array using negative index i.e. -1. You get this exception when you try to access elements outside of either lower or outer bound of an array.
When i is 1, j is 0 by j=i-1
You enter the while loop since a[1] > a[0] i.e. 9 > 8
You do j-- where value of j becomes -1
You come back to while (while(ar[j]>k && j>-1)) try to access a[j] ie.. a[-1] and hence you get ArrayOutOfBoudException.
You may need to check j > -1 before accessing array i.e. reverse your condition in while loop from
while(ar[j]>k && j>-1)
To
while(j>-1 && ar[j]>k)
I have a problem that asks:
Write a program that converts its input arguments into an array of
integers, and then finds the length and location of the longest
contiguous sequence of equal values where the values of the elements
just before and just after this sequence are smaller.
For example, if
the command line arguments are “1 2 2 2 2 5 5 5 3” your program should
output the numbers 5 3 (the first number is a zero-based offset, and
the second number is the length of the subsequence). If a contiguous
subsequence appears at the beginning or end of the array, treat this
as a special case;e.g.,for input “5 5 5 5 3 8 8 8 1”your output should
be 0 4 (and not 5 3). If there are multiple subsequences that satisfy
the above condition, then output the first one.
Updated code:
public class LongestPlateau {
public static void main(String[] args) {
// TODO - Your solution
int N= args.length;
int [] array = new int [N];
int new_length=0;
int location=0;
int max=0;
int current_length=0;
//assign digits into array
for (int i=0; i < N; i++){
int number = Integer.parseInt(args[i]);
array [i] = number;
}
int compare=array[0];
for (int l=0; l<N; l++){
if (array[l] < compare){
current_length=0;
compare = array[l];
}
else if (array[l] == compare){
current_length+=1;
compare = array[l];
}
else if (array[l] > compare){
compare=array[l];
l++;
}
compare= array[l];
for (int b=0; b<N; b++){
if (current_length > max){
max = current_length;
location = array[l];
new_length=max-1;
}
else if (current_length==1){
new_length=max;
}
}
}
System.out.println(location);
System.out.println(new_length);
}
}
Issue is that for the input of "1 2 3 4" I continously get an Array Index out of bounds error.
Before you start writing code, try and think how a human would have solved it.
e.g.
For every item in the input, compare it to the previous, if it's larger, start a new sequence length check (write 0 in your notebook under - "current sequence length)), if it's the same, increase it by 1, if it's less, mark that sequence length as complete. if it's larger than your largest sequence length so far (started with 0) then this is now your largest sequence, if not, ignore that sequence length and move on to the next character. (or something like this)
write these instructions to yourself as a human, and try to follow them, and fix them as you find edge cases. Once you have a working human language algorithm, writing the code will be almost self driven.
You really need to post the specific issue you are seeing, how your actual results differ from your expected results, and what solutions you have attempted.
In any case, as for the general "how to proceed" question, I find that it often helps to work out these types of problems on paper first. Write down your sequence and step through it, observe what information you need to keep track of and what logic you need to apply to produce the desired results. Once you are able to do this, it will be far more straightforward to translate your clearly thought out algorithm into concrete code.
It appears you are at least somewhat on the right track parsing and storing your integer array, but you are a bit misguided with your [t+?] lookaheads. If you write this out and step through it by hand, you may be surprised at what you come up with.
Here is a full program description with test cases:
Given an array of integers int A[], find the length and location of the longest contiguous sequence of equal values for which the values of the elements just before and just after this sequence are smaller.
You should just print these two numbers (first is the length and second is the starting index of the plateau).
To complete the definition, we can consider there are imaginary index positions at A[-1] and A[A.length] where A[-1] < A[0] and A[A.length] < A[A.length-1]. Therefore, the plateau can start/end at both ends of array A. This condition guarantees the existence of a plateau. A plateau can be of length 1.
Example 1:
java LongestPlateau 1 2 2 2 2 1
With this command line arguments, program should print:
4
1
Example 2:
java LongestPlateau 1 2 2 2 2 3
With this command line arguments, program should print:
1
5
Example 2:
java LongestPlateau 3 2 2 2 1 2 1 1 1 2 2 0 1 1 1 1 0
With this command line arguments, program should print:
4
12
Example 2:
java LongestPlateau 3 2 2 2 2 2 2 1 2 1 1 1 2 2 0 1 1 1 1
With these command-line arguments, the program should print:
4
15
Here is my solution:
public class LongestPlateau {
private static int[] parseInputArray(String[] args) {
int[] value = new int[args.length+1];
for(int i = 0 ; i < args.length; i++){
if (i == args.length-1) value[i] = 0; // this imaginary last value of the array ensures that if the plateau is the last value of the array, then it outputs the correct answer
value[i] = Integer.parseInt(args[i]);
}
return value;
}
public static void printLargestPlateau(int[] values) {
int biggestStartIndex = -1;
int biggestLength = 0;
int currentIndex = 1;
int currentPlateauStartIndex = 1;
int currentLength = 1;
boolean plateauStarted = false;
while (currentIndex < values.length) {
if(isStartOfPlateau(currentIndex, values)){
currentLength = 1;
plateauStarted = true;
currentPlateauStartIndex = currentIndex;
} else if (isEndOfPlateau(currentIndex, values)) {
if(plateauStarted && currentLength > biggestLength){
biggestLength = currentLength;
biggestStartIndex = currentPlateauStartIndex;
}
plateauStarted = false;
currentLength = 1;
} else {
currentLength++;
}
currentIndex++;
}
System.out.println(biggestLength +"\n"+biggestStartIndex);
}
private static boolean isStartOfPlateau(int index, int[] values){
if(index <= 0){
return false;
}
return values[index-1] < values[index];
}
private static boolean isEndOfPlateau(int index, int[] values){
if(index <= 0){
return false;
}
return values[index - 1] > values[index];
}
public static void main(String[] args) {
int[] values = parseInputArray(args);
printLargestPlateau(values);
}
}