Longest Snake Sequence - java

Question : A set of numbers separated by space is passed as input. The program must print the largest snake sequence present in the numbers. A snake sequence is made up of adjacent numbers such that for each number, the number on the right or left is +1 or -1 of it's value. If multiple snake sequences of maximum length is possible print the snake sequence appearing in the natural input order.
Example Input/Output 1:
Input:
5 6 7 9 8 8
Output:
5 6 7 8 9 8
8 9 8 7 6 5
Example Input/Output 2:
Input:
9 8 7 5 3 0 1 -2 -3 1 2
Output:
3 2 1 0 1
void doPermute(int[] in, StringBuffer out, boolean[] used, int length, int level, StringBuffer max) {
if (level == length) {
int count = 0;
for (int i = 1; i < out.length(); i++) {
if (Math.abs(Character.getNumericValue(out.charAt(i)) - Character.getNumericValue(out.charAt(i - 1))) != 1) {
//System.out.println(Character.getNumericValue(i) - Character.getNumericValue(i - 1) + " " + i + " yes");
count++;
break;
}
}
if (count == 0) {
max.append(out + " ");
}
return;
}
for (int i = 0; i < length; ++i) {
if (used[i]) {
continue;
}
out.append(in[i]);
used[i] = true;
doPermute(in, out, used, length, level + 1, max);
used[i] = false;
out.setLength(out.length() - 1);
}
}
As i am using StringBuffer my code passed the test cases that contains positive value (first test case) but failed in test cases containing negative values(second test case).
Update:-
I replaced stringbuffer with Integer[] and made few changes.it works fine for smaller inputs of length 8 or 9. How to make it fast for larger inputs of length 13 to 15?

Have you tried doing the process using an array of integers?
Scanner sc = new Scanner(System.in);
String s = sc.nextLine(); //The numbers entered in string format separated by spaces
String ss = s.split(" "); //Numbers separated by space will be put as individual numbers in a String array but each number is still in string format
int l = ss.length, i = 0;
int[] n = new int[l]; //The integer array which will store the values
for(i = 0; i < l; i++)
{
n[i] = Integer.parseInt(ss[i]); //Has integers now instead of string numbers
}
There might be creation of a few extra arrays but then calling the Character.getNumericValue() function repeatedly can also reduce efficiency. Also might solve your StringBuffer problem.
But SkillRack is very annoying anyway.

Your comparison isn't finding adjacent numbers for negative values.
For example: Abs(-2) - (-3) = 5 but -2 and -3 should be adjacent.
Ok. I see you're parsing - and digit separately.
Given the requirement of what a snake sequence is, the longest snake sequence for "5 6 7 9 8 8" is "5 6 7". The output listed above does not correspond to the definition: " adjacent numbers such that for each number, the number on the right or left is +1 or -1 of it's value". How does "5 6 7 8 9 8" meet the definition of snake sequence for "5 6 7 9 8 8"? Sorry I couldn't help.
You might want to parse the code into Integers, store the longest sequences in a map).
#Test
public void testSnake(){
String t2 = "9 8 7 5 3 0 1 -2 -3 1 2";
List<String> numsStr = Arrays.asList(t2.split(" "));
List<Integer> nums = new ArrayList();
HashMap<Integer,List<Integer> > numMap = new HashMap();
numsStr.forEach((s) -> {
Integer val = Integer.decode(s);
nums.add(val);
});
nums.forEach((num) -> {
System.out.println("num: " + num);
// track longest sequence, store in numMap
});
// Print numMap
}

Related

I tried all possible combinations to pass test cases but no success. I passed only one test case i.e. sample one

Tyson is all prepared for the Beyblade World Championship. The tournament is team-based and each team can have N members. A player can fight against a single player only. Team G-Revolution is all excited and pumped up as they have practised a lot. Kenny, the mind of team G-Revolution, has created a database where he has the data about the power of other teams’ members and his own team members. The tournament is going to start in some time and Kenny moves to the cafeteria to have a snack before the competition.
The team G-Revolution is to fight in some time and they are tensed up as someone has kidnapped Kenny from the cafeteria. They have made a police complaint and the police are searching for Kenny. Luckily, they have found his device with all the data. The problem is, the data is present randomly and not in the order they have to fight the opponent. Team G-Revolution wants to win at any cost and for that, they need the order in which they have to fight optimally to win the maximum number of battles.
A player can win only when his/her beyblade power is strictly greater than the opponents beyblade power.
Example:
Consider the team size is 3, N = 3
The 3 players of both the teams are shown with their beyblade powers.
Team G-Revolution is presented in the order: Tyson, Max, Ray
Team All Starz is presented in the order: Michael, Eddy, Steve
With the given arrangement, Team G-Revolution would be able to win only 1 fight. Team G-Revolution should be shuffled in an optimal manner as below:
The maximum number of fights Team G-Revolution can win is 2 when they are arranged optimally or fight in an optimal order.
Team G-Revolution needs help with the device. Tyson has heard about your skills and called you up to help them shuffle their positions in an order such that they would be able to win the maximum number of fights. Can you help Tyson and Team G-Revolution?
Input Format
The first line of input consists of the number of test cases, T
The first line of each test case consists of the number of members each team can have, N.
The second line of each test case consists of N space-separated integers representing the power of beyblades of Team G-Revolution members.
The third line of each test case consists of N space-separated integers representing the power of beyblades of opponent team members.
Constraints
1<= T <=100000
1<= N <=100000
0<= Power of Beyblade <= LLONG_MAX
Output Format
For each test case, print the maximum number of fights Team G-Revolution can win if they go to fight in an optimal manner.
Sample TestCase 1
Input
1
10
3 6 7 5 3 5 6 2 9 1
2 7 0 9 3 6 0 6 2 6
Output
7
Code:
import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.Arrays;
public class CandidateCode {
private static int testCase = 0;
private static int numOfMembers = 0;
private static int gRevolutionTeamSize = 0;
private static int opponentTeamSize = 0;
private static int numOfGRevolutionWins = 0;
private static final Integer initial_Index = 0;
private static final Integer second_Index = 1;
private static final Integer third_Index = 2;
private static final Integer fourth_Index = 3;
private static final Integer noOfIndex = 4;
private static final Integer testNumber = 100000;
private static String[] powerOpponentTeamArr = null;
private static String[] powerGRevolutionTeamArr = null;
public static void main(String args[] ) throws Exception {
List<Integer> gRevolutionWinsList = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
String[] input = new String[noOfIndex];
try{
for(int i = 0; i < input.length; i++){
input[i] = scan.nextLine();
}
if (!validateInput(input[initial_Index],input[second_Index])) {
System.exit(initial_Index);
}
}
catch(Exception ex){
}
finally{
scan.close();
}
testCase = Integer.parseInt(input[initial_Index]);
numOfMembers = Integer.parseInt(input[second_Index]);
String gRevolutionMembers = input[third_Index];
powerGRevolutionTeamArr = gRevolutionMembers.split(" ");
String opponentMembers = input[fourth_Index];
powerOpponentTeamArr = opponentMembers.split(" ");
gRevolutionTeamSize = powerGRevolutionTeamArr.length;
long[] totalGRevolutionTeamArr = new long[gRevolutionTeamSize];
for (int i = 0; i < gRevolutionTeamSize; i++){
totalGRevolutionTeamArr[i] = Long.parseLong(powerGRevolutionTeamArr[i]);
validateInputPower(totalGRevolutionTeamArr[i]);
}
opponentTeamSize = powerOpponentTeamArr.length;
long[] totalOpponentTeamArr = new long[opponentTeamSize];
for (int i = 0; i < opponentTeamSize; i++){
totalOpponentTeamArr[i] = Long.parseLong(powerOpponentTeamArr[i]);
validateInputPower(totalOpponentTeamArr[i]);
}
Arrays.sort(totalGRevolutionTeamArr);
Arrays.sort(totalOpponentTeamArr);
for(int i = 0; i < numOfMembers; i++){
if((totalGRevolutionTeamArr[i] - totalOpponentTeamArr[i]) > 0){
numOfGRevolutionWins = numOfGRevolutionWins + 1;
}
}
int numCount = numOfGRevolutionWins;
int moveMembers = numOfMembers - numCount - 1;
if(moveMembers >= 0){
for(int i = 0; i < moveMembers; i++){
long teamMember = totalOpponentTeamArr[numCount];
int j;
int numOfGRevolutionWins_1 = 0;
for (j = 0; j < moveMembers; j++){
totalOpponentTeamArr[numCount + j] = totalOpponentTeamArr[numCount + j + 1];
}
totalOpponentTeamArr[numCount + j] = teamMember;
for(int k = numCount; k < numOfMembers; k++){
if((totalGRevolutionTeamArr[k] - totalOpponentTeamArr[k]) > 0){
numOfGRevolutionWins_1 = numOfGRevolutionWins_1 + 1;
}
}
gRevolutionWinsList.add(numOfGRevolutionWins_1);
}
numOfGRevolutionWins = numOfGRevolutionWins + Collections.max(gRevolutionWinsList);
}
System.out.println(numOfGRevolutionWins);
}
private static boolean validateInput(String testCases, String noOfPlayers) {
int test1 = Integer.parseInt(testCases);
int numOfPlayers = Integer.parseInt(noOfPlayers);
if (second_Index <= test1 && test1 <= testNumber && second_Index <= numOfPlayers && numOfPlayers <= testNumber) {
return true;
}
return false;
}
private static void validateInputPower(long memberPower) {
if (!(initial_Index <= memberPower && memberPower <= Long.MAX_VALUE)) {
System.exit(initial_Index);
}
}
}
Result:
Input from line 1 = 1
Input from line 2 = 10
Input from line 3 = 3 6 7 5 3 5 6 2 9 1
Input from line 4 = 2 7 0 9 3 6 0 6 2 6
Scanner input job succeeded if we see some value here = 1
Finally block is called to free Scanner job
Value from first line and parsed string to int = 1
Value from second line and parsed string to int = 10
Value from third line = 3 6 7 5 3 5 6 2 9 1
Value from fourth line = 2 7 0 9 3 6 0 6 2 6
Parsed string number 1 to long : 3
Parsed string number 2 to long : 6
Parsed string number 3 to long : 7
Parsed string number 4 to long : 5
Parsed string number 5 to long : 3
Parsed string number 6 to long : 5
Parsed string number 7 to long : 6
Parsed string number 8 to long : 2
Parsed string number 9 to long : 9
Parsed string number 10 to long : 1
Parsed string number 1 to long : 2
Parsed string number 2 to long : 7
Parsed string number 3 to long : 0
Parsed string number 4 to long : 9
Parsed string number 5 to long : 3
Parsed string number 6 to long : 6
Parsed string number 7 to long : 0
Parsed string number 8 to long : 6
Parsed string number 9 to long : 2
Parsed string number 10 to long : 6
After sorting number 1 is : 1
After sorting number 2 is : 2
After sorting number 3 is : 3
After sorting number 4 is : 3
After sorting number 5 is : 5
After sorting number 6 is : 5
After sorting number 7 is : 6
After sorting number 8 is : 6
After sorting number 9 is : 7
After sorting number 10 is : 9
After sorting number 1 is : 0
After sorting number 2 is : 0
After sorting number 3 is : 2
After sorting number 4 is : 2
After sorting number 5 is : 3
After sorting number 6 is : 6
After sorting number 7 is : 6
After sorting number 8 is : 6
After sorting number 9 is : 7
After sorting number 10 is : 9
Number of G-Revolution wins are : 5
Number will be used is : 4
Number shifted is : 6
Number of wins afterwards : 1
Number shifted is : 6
Number of wins afterwards : 2
Number shifted is : 6
Number of wins afterwards : 2
Number shifted is : 7
Number of wins afterwards : 2
Number of wins afterwards in list : [1, 2, 2, 2]
Answer is = 7
You have fallen into the classic trap of constructing an algorithm based on the example rather than considering the general case. This is not a criticism, but something that we all have to be aware of in order to fight against.
Take a look at your loop here :
for (j = 0; j < moveMembers; j++){
totalOpponentTeamArr[numCount + j] = totalOpponentTeamArr[numCount + j + 1];
}
totalOpponentTeamArr[numCount + j] = teamMember;
So in the given example, a straight sort results in us winning the first numCount = 5 matches, so your algorithm looks to leave those 5 results and rearrange our team from position 6.
Trouble is, that's only for the supplied example.
Consider if the opposing team didn't have strengths 0 or 1, but replaced those with 3 - that is, their team was : 3 3 3 3 3 6 6 6 7 9.
In that case, on the initial straight-sorted matchups, we would lose the first 4 and only win 1 match (the 5-3).
Consider how your algorithm would behave in that scenario, rearranging the team after numCount = 1 ?
So a better algorithm would be :
1) Sort each team as you do at present
2) Starting with their weakest member, find our weakest member that would beat them
3) Continue with their next weakest member, finding our weakest member who would beat that one
etc
At each step, if we have to skip over one of our members, make a note of them (in a list or something). When we come come to the point that we run out of members to match against one of theirs, then just fill in the rest of the matches with this list of our skipped-over members - after all, they were never going to win a match anyway !
t=int(input())
while t>0:
n=int(input())
gr=[int(x) for x in input().split()]
op=[int(x) for x in input().split()]
gr.sort()
op.sort()
l=r=count=0
while l<n and r<n:
if gr[l]>op[r]:
l+=1
r+=1
count+=1
elif gr[l]<=op[r]:
l+=1
print(count)
t-=1
I also appear for the same contest and I got full marks.
Might my code be helpful for you.
to solve this you can sort both the list to reverse order and compare each other. Refer below a working example of in Python:
def main():
testCase=int(input())
while testCase>0:
count=0
numberOfPlayer=int(input())
firstPlayer=list(map(int,input().split()))
secondPlayer=list(map(int,input().split()))
firstPlayer.sort(reverse=True)
secondPlayer.sort(reverse=True)
p=0
for i in range(numberOfPlayer):
for j in range(p,numberOfPlayer):
if firstPlayer[i]>secondPlayer[j]:
p=j+1
count+=1
break
print(count)
testCase-=1
main()
# Made by Ankur Patel
For java based solution
refer
My logic:
// Logic for comparing team battles in optimum manner
while(gRev < numOfMembers){
if((totalGRevolutionTeamArr[gRev] - totalOpponentTeamArr[opp]) > 0){
gRev++;
opp++;
numOfWins++;
}
else{
gRev++;
}
}

Regex for 9 unique digits separated by a space?

I'm trying to write a piece of validation code for an input of numbers. The numbers have to contain 0 to 8. The order does not matter, but the digits cannot be repeated.
E.g. 1 4 7 8 0 2 5 3 6 //valid
1 1 3 6 3 8 0 5 4 //invalid as 1 is repeated
I have a regex so far that takes in 9 unique digits:
String pattern = "^(?!.*(.).*\\1)\\d{9}";
E.g. 123456780 //valid
112345678 //invalid as 1 is repeated
1 2 3 4 5 6 7 8 0 //invalid
All I need is to add the bit where it takes in the digits separated by a space!
Thanks.
This is really abuse of regex :D but
^(?!.*(\d).*\1)(?:[0-8] ){8}[0-8]$
should do it. Make sure only digits are taken into consideration in the part where you disallow repetition; then you can have eight digit-space pairs followed by a digit at the end (with correct digits).
I'm not sure you need a regex for this. Consider using a Set:
Scanner sc = new Scanner(System.in);
Set<Integer> set = new HashSet<>();
int count = 0;
while (count < 9) {
System.out.println("Enter a number:");
int num = sc.nextInt();
if (num >= 0 && num <= 8) {
set.add(num);
}
count++;
}
System.out.println(set.size() == 9);
Or if your input comes in one go:
String[] nums = sc.nextLine().split("\\s+");
for (String num : nums) {
set.add(Integer.parseInt(num));
}
You'll have to consider checking for invalid input. Or you could check the nums is 9 first before adding to set and return false then straight away.

Adding Two Elements in an Array (Java)

I need to write a method that adds the two last elements of two arrays together and add the sum on another array. But if the two elements are more than 10, then I would need to carry that number to the next array.
This program should be similar to what an odometer does.
Here is my sample code.
int [] sum(int []number1, int []number2)
{
int [] total;
int carry = 0;
for ( int k = numbers1 - 1; k >= 0; k++)
{
sum = number1[k] + number2[k] + carry;
carry = sum/10;
total[k] = sum
}
return total;
}
An example output would be:
0 1 2 3 4
0 8 9 9 9
4 5 7 0 3
5 4 7 0 2
So the top array is just a visual aid that tells where the position for the number is.
The program is suppose to add the next two arrays together. i.e. 9 + 3 = 12
Since 12 is above 9, it carries over the 10 to the next set of arrays, that is why the third array only has a 2 in its place, and that is why the next array is 9 + 0 = 0; because the 10 was carried over.
I am not sure why my code won't work. I don't get the right numbers. Could anyone give any hints or solution to the problem?
-Thanks
I assume numbers1 is the number of elements in the array.
In this case it should be k-- instead of k++ because you are starting from the last element and moving backword.

For loop to print the number in sequence and reverse it

How to print the following output with only one for-loop in java?
1 2 3 4 5 6 7 8 9 1 0 9 8 7 6 5 4 3 2 1
Code snippet:
class Series{
public static void main(String args[]){
for(int i=1; i<=10; i++){
System.out.println(i);
}
System.out.println(i);
for(int j=9; j>=0; j--){
System.out.println(j);
}
}
My program's in the following manner. Can anyone correct it?
public static void main(String...strings ){
int dir = 1;
for(int i=1; i>0; i+=dir){
if(i == 10)
dir = -1;
System.out.print(i+" ");
}
}
Output:
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The series in the question is wrong.
It should be: 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The code, in one loop, is as follows:
int ctr = 1;
for(int i = 1; i > 0; i += ctr)
{
if(i == 10)
{
ctr = -1;
}
System.out.print(i + " ");
}
Every sequence follows a pattern, Let's try finding one in this.
To work with this code, analyze What loop would print with the variable that you increment and What you want in the output?
In your problem, assuming that the number you are entering is entered by user i.e. n, you want 2*n - 1 numbers in your sequence. Hence we now have the limits of our loop
For n=5, Under no Conditions the loop would simply print a sequence like this
1 2 3 4 5 6 7 8 9 provided you are starting your loop from 1.
The sequence you want is 1 2 3 4 5 4 3 2 1.
Now looking at both the sequences you can see that the sequence is same till the mid point that is till the value of n is reached. Now if you observe the pattern further if you subtract 2 from 6 you get 4 that is the number you want in your sequence. Similarly when you subtract 4 from 7 you get 3 which is the next number in the sequence you required.
Hence the pattern this sequence follows is that after the loop reaches the value provided by the user you need to subtract (2 * k) from the next number where k starts from 1 and increases with every iteration
Now you know how to achieve the pattern which would be easy to achieve using conditional statements.
PS: let's assume an added constraint of using no conditional statements then we have to write an arithmetic expression to solve our problem.
Following the pattern again the expression must display i where i is the variable incremented in the loop
so our code looks like
for (i = 1; i<=2*n - 1;i++)
{
System.out.print(i);
}
Now to get the pattern we need to subtract multiples of 2 after the user provided integer n is reached. But whatever we subtract should also not affect out first n integers.
Since we know we have to subtract multiples of 2 we know the expression we have to subtract would look like 2 * (____). As we want a sequence of multiples we can obtain that using %. As soon as the number goes over n the % operator on i would give us back sequence from 0 to n-1 hence generating multiples of 2.
Now our expression comes to 2 * (i % n). But the problem is that it would also subtract from the first 4 integers which we don't want so we have to make changes such that this expression will work only after loop reaches the value provided by the user.
As we know the division / operator provides us with the quotient. Hence it would yield us 0 till we reach the value of user defined number and 1 for the rest of the sequence as we run our loop till 2*n -1. Hence multiplying this expression to our previous expression yields 2*(i%n)*(i/n)
And there we have it our final code to generate the sequence would be
for (int i = 1;i<2*r;i++)
{
System.out.print(i - 2 * (i%r)*(i/r));
}
Observe the above code for the first n-1 integers i/r would make subtracted expression 0 and for i = n, i % r would make the expression 0. For the rest of the sequence i / r would generate value 1 and hence we will get multiples of 2 from 2 *( i % r) to provide us with the sequence
try this
int j = 10;
for (int i = 1; i <= 10; i++) {
if(i<10)
System.out.print(" " +i);
if(i==10){
i--;
System.out.print(" " +j);
if(j==1){
i++;
}
j--;
}
}
OutPut
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
Something like this?
for(int i=0;i<20;i++) {
if((i/10)%2 == 0)
System.out.print(i%10 + " ");
else
System.out.print((10-(i%10)) + " ");
}
Try this code, You just need a if condition in for loop.
int i = 1;
for(int j=1; j<=20; j++)
{
if(j<11)
System.out.print(j+" ");
else
{
System.out.print((j - i == 10 ?" ": (j-i + " ")));
i = i+2;
}
}
public class forLoopTest {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
System.out.print(i + " ");
}
for (int j = 10; j >= 1; j--) {
System.out.print(j + " ");
}
}
}

Creating a looping square with java

Full Disclosure: Homework.
Explanation: I cant understand my teacher.
Problem:
Write a method called printSquare that takes in two integer
parameters, a min and a max, and prints the numbers in the range from
min to max inclusive in a square pattern. The square pattern is
easier to understand by example than by explanation, so take a look at
the sample method calls and their resulting console output in the
table below. Each line of the square consists of a circular sequence
of increasing integers between min and max. Each line prints a
different permutation of this sequence. The first line begins with
min, the second line begins with min + 1, and so on. When the
sequence in any line reaches max, it wraps around back to min. You
may assume the caller of the method will pass a min and a max
parameter such that min is less than or equal to max
I cannot for the life of me figure out how to make the numbers stop at the 'max' value and start over in the middle of the line.
This is what I have so far, apologies but I have trouble with for loops.
for(int i = 0; i < row; i++)
{
for(int d = 0; d < row; d++)
{
System.out.print(d+1);
}
System.out.println(i);
}
I know I used row twice, but its the only way i can get the compiler to form a square shape with the loop. Does anyone even remotely understand what i'm trying to do? :/
This is actually a nice mathematical problem. Assume:
int side = to - from + 1; /// the size/width of the square.
the value at any point in the square (row, col) is:
from + ((row + col) % side)
you should be able to put that in your loops and "smoke it".
Edit based on comment asking for explanation.
The trick is to loop through all the positions in the 'matrix'. Given that the matrix is square, the loops are relatively simple, just two loops (nested) that traverse the system:
final int side = to - from + 1;
for (int row = 0; row < side; row++) {
for(int col = 0; col < side; col++) {
... magic goes here....
}
}
Now, in this loop, we have the variables row and col which represent the cell in the matrix we are interested in. The value in that cell needs to be proportional to the distance it is from the origin..... let me explain.... If the origin is the top left (which it is), then the distances from the origin are:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
The distance is the sum of the row and the column...... (rows and columns start counting from 0).
The values we put in each matrix are limited to a fixed range. For the above example, with a square of size 5, it could have been specified as printSquare(1,5).
The value in each cell is the from value (1 in this example) plus the distance from the origin... naively, this would look like:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
here the values in the cell have exceeded the limit of 5, and we need to wrap them around... so, the trick is to 'wrap' the distances from the origin..... and the 'modulo' operator is great for that. First, consider the original 'origin distance' matrix:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
if we instead populate this matrix with 'the remainder of the distance when dividing by 5' (the modulo 5, or %5) we get the matrix:
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
Now, if we add this 'modulo' result to the from value (1), we get our final matrix:
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
in a sense, all you need to know is that the value at each cell is:
the from value plus the remainder when you divide the 'distance' by the width.
Here's the code I tested with:
public static final String buildSquare(final int from, final int to) {
final StringBuilder sb = new StringBuilder(side * side);
final int side = to - from + 1;
for (int row = 0; row < side; row++) {
for(int col = 0; col < side; col++) {
sb.append( from + ((row + col) % side) );
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(buildSquare(1, 5));
System.out.println(buildSquare(3, 9));
System.out.println(buildSquare(5, 5));
System.out.println(buildSquare(0, 9));
System.out.println(buildSquare(0, 3));
}
Since this is homework, I'll just give a hint.
I cannot for the life of me figure out how to make the numbers stop at the 'max' value and start over in the middle of the line.
Here's one way to do it.
Create the first number twice in an array. Taking the printSquare(1, 5) example, create an int array of 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.
Use a loop to loop through the array, starting with element zero and ending with element 4, and another loop to display 5 digits (max - min + 1).
try this
int i,j,k;
for(i=min;i<=max;i++) {
for(j=i;j<=max;j++) {
System.out.print(j);
}
for(k=min;k<i;k++){
System.out.print(k);
}
System.out.println();
}
you can try
loop from min value to max value and put all the numbers in an array
now loop again from min value to max value
each time print the array and do a circular shift (for circular shift you can find lot of example in SO)
I think #rolfl's solution is the cleanest. I'd recommend going with that.
You can find another simple solution by observing that each output in your "square" simply shifts the first element to the end the list of numbers. To imitate this, you can put all the numbers from min to max in a data structure like LinkedList or ArrayDeque where you can easily add/remove items from both ends, then you'd print the contents in order, and shift the first entry to the end. E.g., coll.addLast(coll.removeFirst()). If you repeat that process max - min + 1 times, you should get the desired output.
no array no problem you can easily solve.
it work with any range of number.
static void printSquare(int min, int max){
int len = max - min + 1;
int copy_min = min, permanent_min = min;
for(int i = 0; i < len; i++){
for(int j = 0; j< len; j++){
if(min > max)
if(min % len < permanent_min)
System.out.print((min % len )+ len);
else
System.out.print(min % len);
else
System.out.print(min);
min++;
}
min = ++copy_min;
System.out.println();
}
}
public static void printSquare(int min, int max)  {
    
    for (int i = min; i <= (max -min)+min; i++)  {
        
        for( int j =i; j <= max ; j++) {                
            System.out.print(j);   
            } 
        for (int j1= min; j1<= i * 1 - 1; j1++) {
            System.out.print(j1);
            }
        System.out.println();
    }
    
}

Categories