Arrange the numbers by subtracting - java

I have a java problem that I don't know how to solve the program is :
two number must got from user n,k.
I need to find a permuation of numbers from 1 to N such that the difference between two items >=k for example :
we get the numbers (n = 5 and k = 2 )
and the answer must be 1,4,2,5,3 :
and for (n=2 and k = 2) there is not answer because the difference between 1 and two is 1(1,2 or 2,1).
I hope you understand what I want.
and I write some codes that are wrong:
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int n = user_input.nextInt();
int k = user_input.nextInt();
int a ;
if (n%2==0) a = (n-2)/2; else a = (n-1)/2 ;
if (k!=a) {System.out.println("Impossible"); return;}
int h = k+1;
int value = 0;
int t = 1;
boolean b = true;
String res = "1 ";
while (value<n-1) {
value++;
if (b){
t = t + h;
res = res + t + " ";
b = false;
}else {
t = t-k;
res = res + t + " ";
b = true;
}
}
System.out.println(res);
}

Here is the code
public class HelloWorld{
public static void calculationMethod(int n, int k) {
if(n<2 || n/2 < k) {
System.out.println("Impossible");
return;
}
else {
int i = (int)Math.ceil(n/2.0);
int j = n;
int start = i;
boolean flag = true;
while(i>=1 || j>start) {
if(flag) {
System.out.print(i + " " );
i--;
flag = false;
}
else {
System.out.print(j + " " );
j--;
flag = true;
}
}
}
}
public static void main(String []args){
calculationMethod(7,3);
}
}
The idea is to divide your range(n) in half. If k>n/2 then it is not possible to construct any such sequence.
If that is not the case, then have 2 pointers one at the middle of your range and one at the end of the range. and print them alternatively decrementing both pointers until u reach the beginning.
Feel free to improve the code.

public void calculationMethod(int n, int k) {
ArrayList<Integer> intList = new ArrayList<>();
for (int i = 1; i <= n; i++) {
int a = i;
int b = i + 2;
if (!intList.contains(a) && a<=n) {
intList.add(a);
}
if (!intList.contains(b) && b<=n) {
intList.add(b);
}
}
String mValues= TextUtils.join(",",intList);
Log.i("values", mValues);
}

Related

Palindrome in java

Here what I tried
sample input is "aabaa"
eg: in if condition val[0] = a[4]
if it is equal i stored it in counter variable if it is half of the length it original string it is palindrome
if it is not it is not a palindrome
I tried with my basic knowledge in java if there is any errors let me know
boolean solution(String inputString) {
int val = inputString.length();
int count = 0;
for (int i = 0; i<inputString.length(); i++) {
if(inputString.charAt(i) == inputString.charAt(val-i)) {
count = count++;
if (count>0) {
return true;
}
}
}
return true;
}
How about
public boolean isPalindrome(String text) {
String clean = text.replaceAll("\\s+", "").toLowerCase();
int length = clean.length();
int forward = 0;
int backward = length - 1;
while (backward > forward) {
char forwardChar = clean.charAt(forward++);
char backwardChar = clean.charAt(backward--);
if (forwardChar != backwardChar)
return false;
}
return true;
}
From here
In your version you compare first element with last, second with second last etc.
last element in this case is inputString.length()-1(so need to use 'inputString.charAt(val-i-1)' . If you iterate till end, then the count should be equal to length of the string.
for(int i = 0; i<inputString.length(); i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val); //true when count=val
Or alternatlively iterate till the mid point of the array, then count value is val/2.
for(int i = 0; i<inputString.length()/2; i++){
if(inputString.charAt(i) == inputString.charAt(val-i-1)){
count ++;
}
}
return (count==val/2); //true when count=val/2
There's no constraints in the question so let me throw in a more cheesy solution.
boolean isPalindrome(String in)
final String inl = in.toLowerCase();
return new StringBuilder(inl).reverse().toString().equals(inl);
}
A palindrome is a word, sentence, verse, or even a number that reads the same forward and backward. In this java solution, we’ll see how to figure out whether the number or the string is palindrome in nature or not.
Method - 1
class Main {
public static void main(String[] args) {
String str = "Nitin", revStr = "";
int strLen = str.length();
for (int i = (strLen - 1); i >=0; --i) {
revStr = revStr + str.charAt(i);
}
if (str.toLowerCase().equals(revStr.toLowerCase())) {
System.out.println(str + " is a Palindrome String.");
}
else {
System.out.println(str + " is not a Palindrome String.");
}
Method - 2
class Main {
public static void main(String[] args) {
int n = 3553, revNum = 0, rem;
// store the number to the original number
int orgNum = n;
/* get the reverse of original number
store it in variable */
while (n != 0) {
remainder = n % 10;
revNum = revNum * 10 + rem;
n /= 10;
}
// check if reversed number and original number are equal
if (orgNum == revNum) {
System.out.println(orgNum + " is Palindrome.");
}
else {
System.out.println(orgNum + " is not Palindrome.");
}

How can I print out all numbers in a single DialogBox (JOPTION)?

package Fibonacci;
class Fibonacci
{
public static void main(String[]args) {
int a = 0;
int b = 1;
String input;
input = javax.swing.JOptionPane.showInputDialog("How many elements you want to print in a Fibonacci series");
int n = Integer.parseInt(input);
javax.swing.JOptionPane.showMessageDialog(null, a + " "+ b + " ");
int c;
for(int i = 2; i < n; i++) {
c = a + b;
javax.swing.JOptionPane.showMessageDialog(null, c + " ");
a = b;
b = c;
}
}
}
// Here is the code ? what can I change to display the output on only one dialogbox? Sorry I'm just new with learning java,
You should first collect the data which you want to print in a DialogBox.
Then you can print the data with the DialogBox (not in the for loop).
Take a look at following code.
import javax.swing.*;
public class main {
public static long fibonacci(int n){
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
b = a + (a = b);
}
return a;
}
public static void main(String... args){
int input = Integer.parseInt(JOptionPane.showInputDialog("Number of print elements"));
String fib = "";
for (int i = 0; i <= input; i++) {
fib = fib + fibonacci(i) + "\n";
}
JOptionPane.showMessageDialog(null, fib);
}
}

Method with one parameter to draw a cross

so I need to use a method with one parameter to draw a cross whose size is dictated by that parameter. So drawCross(5) would be:
*
*
*****
*
*
I can't seem to get it to work. My code will ask for a number, but then nothing. I'm sure it's probably just me being stupid, but I can't for the life of me figure out what it is. Here's what I have:
import java.util.Scanner;
public class Lab9E1CrossTest {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.print("Number: ");
int n = kbd.nextInt();
drawCross(n);
kbd.close();
}
public static void drawCross(int n) {
int lineCounter = 1, charCounter = 1;
if (n % 2 == 1) {
while (lineCounter <= n) {
if (lineCounter == ((n / 2) + 1)) { // determines if middle line
// by dividing n by two then
// adding 1 (ex. middle of 5
// is 3, so 5/2=2, +1=3)
charCounter = 1;
while (charCounter <= n) { // prints out n number of stars
// on one line
System.out.print("*");
charCounter++;
}
} else {
charCounter = 1;
while (lineCounter != ((n / 2) + 1)) {
if (charCounter == ((n / 2) + 1)) { // if middle char of
// line
System.out.print("*");
} else {
System.out.print(" ");
}
charCounter++;
}
}
System.out.println(); // makes sure prints on new line
lineCounter++;
}
} else {
System.out.println("Error: Number is even.");
}
}
}
I would start by validating the user input at the time you receive it (e.g. make sure it's even before you call drawCross).
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.print("Number: ");
if (kbd.hasNextInt()) {
int n = kbd.nextInt();
if (n % 2 != 0) {
drawCross(n);
} else {
System.out.printf("Please enter an odd #, %d is even%n", n);
}
}
}
Next, I suggest you create a utility method to repeat a specific character n times. You can then draw your cross with the repeating String(s)
private static String repeat(char ch, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(ch);
}
return sb.toString();
}
Something like,
public static void drawCross(int n) {
int mid = (n / 2);
String spaces = repeat(' ', mid);
for (int i = 0; i < mid; i++) {
System.out.println(spaces + '*');
}
System.out.println(repeat('*', n));
for (int i = 0; i < mid; i++) {
System.out.println(spaces + '*');
}
}

Getting group of the same numbers numbers

I'm working on a code which will count how many are the groups with the same number.
For example:
11022 = 2 groups with the same number
1100021 = 2 groups with the same number
12123333 = 1 group with the same number
So far I've come up to this code:
package Numbers;
import java.util.*;
public class Numbers{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int strI ;
strI = scan.nextInt();
int[] a = {strI};
System.out.println(sum(a));
System.out.println("length = "+a.length);
}
public static in sum(int[] a){
int sum = 0;
int last = 0;
for (int i = 0; i < a.length - 1; i++){
if(a[i] == a[i + 1] && last != a[i + 1]){
sum++;
}
last = a[i];
}
return sum;
}
}
My problem is that the inputted number will register as 1 index. is it possible to enter a series of number that will go to different indexes?
This is easiest done by converting it to a string so you don't have to deal with place value. After all, you only care about the characters themselves.
public static void main(String[] args){
// Get number n... Assuming n has been set to the int in question
int n = ...; //Fill in with whatever int you want to test
String s = n + "";
char same = ' ';
int consec = 0;
for(int i = 0; i < s.length() - 1; i++){
if(s.charAt(i) == s.charAt(i+1)){
if(same == ' ')
consec++;
same = s.charAt(i);
}
else{
same = ' ';
}
}
System.out.println(consec);
}
First, you can get the count of consecutive digits with something like
public static int sum(int a) {
String strI = String.valueOf(a);
int count = 0;
boolean inRun = false;
for (int i = 1; i < strI.length(); i++) {
if (strI.charAt(i - 1) == strI.charAt(i)) {
if (inRun) {
continue;
}
inRun = true;
count++;
} else {
inRun = false;
}
}
return count;
}
public static void main(String[] args) {
int[] arr = { 11022, 1100021, 12123333 };
for (int val : arr) {
int count = sum(val);
String group = "groups";
if (count == 1) {
group = "group";
}
System.out.printf("%d = %d %s with the same number%n", val, count, group);
}
}
Output is the requested
11022 = 2 groups with the same number
1100021 = 2 groups with the same number
12123333 = 1 group with the same number
As for your second question, you might read Integer into a List - Java arrays are immutable,
List<Integer> al = new ArrayList<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt()) {
al.add(scan.nextInt());
}
Integer[] arr = al.toArray(new Integer[0]);
System.out.println(Arrays.toString(arr));

How to Find the Longest Palindrome (java)

Hi I've been doing this java program, i should input a string and output the longest palindrome that can be found ..
but my program only output the first letter of the longest palindrome .. i badly need your help .. thanks!
SHOULD BE:
INPUT : abcdcbbcdeedcba
OUTPUT : bcdeedcb
There are two palindrome strings : bcdcb and bcdeedcb
BUT WHEN I INPUT : abcdcbbcdeedcba
output : b
import javax.swing.JOptionPane;
public class Palindrome5
{ public static void main(String args[])
{ String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
for(int x=0; x<size; x++)
{ for(int y=x+1; y<size-x; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
Out = GetLongest(subword);
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + Out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
public static String GetLongest(String sWord)
{
int sLength = sWord.length();
String Lpalindrome = "";
int storage = 0;
if(storage<sLength)
{
storage = sLength;
Lpalindrome = sWord;
}
return(Lpalindrome);
}
}
modified program..this program will give the correct output
package pract1;
import javax.swing.JOptionPane;
public class Palindrome5
{
public static void main(String args[])
{
String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
String Lpalindrome = "";
int storage=0;
String out="";
for(int x=0; x<size; x++)
{ for(int y=x+1; y<=size; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
int sLength = subword.length();
if(storage<sLength)
{
storage = sLength;
Lpalindrome = subword;
out=Lpalindrome;
}
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
}
You have two bugs:
1.
for(int y=x+1; y<size-x; y++)
should be
for(int y=x+1; y<size; y++)
since you still want to go all the way to the end of the string. With the previous loop, since x increases throughout the loop, your substring sizes decrease throughout the loop (by removing x characters from their end).
2.
You aren't storing the longest string you've found so far or its length. The code
int storage = 0;
if(storage<sLength) {
storage = sLength;
...
is saying 'if the new string is longer than zero characters, then I will assume it is the longest string found so far and return it as LPalindrome'. That's no help, since we may have previously found a longer palindrome.
If it were me, I would make a static variable (e.g. longestSoFar) to hold the longest palindrome found so far (initially empty). With each new palindrome, check if the new one is longer than longestSoFar. If it is longer, assign it to longestSoFar. Then at the end, display longestSoFar.
In general, if you're having trouble 'remembering' something in the program (e.g. previously seen values) you have to consider storing something statically, since local variables are forgotten once their methods finish.
public class LongestPalindrome {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String S= "abcdcba";
printLongestPalindrome(S);
}
public static void printLongestPalindrome(String S)
{
int maxBack=-1;
int maxFront = -1;
int maxLength=0;
for (int potentialCenter = 0 ; potentialCenter < S.length();potentialCenter ++ )
{
int back = potentialCenter-1;
int front = potentialCenter + 1;
int longestPalindrome = 0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome+1;
maxBack = back + 1;
maxFront = front;
}
back = potentialCenter;
front = potentialCenter + 1;
longestPalindrome=0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome;
maxBack = back + 1;
maxFront = front;
}
}
if (maxLength == 0) System.out.println("There is no Palindrome in the given String");
else{
System.out.println("The Longest Palindrome is " + S.substring(maxBack,maxFront) + "of " + maxLength);
}
}
}
I have my own way to get longest palindrome in a random word. check this out
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.
public class LongestPalindrome {
public static void main(String[] args) {
HashMap<String, Integer> result = findLongestPalindrome("ayrgabcdeedcbaghihg123444456776");
result.forEach((k, v) -> System.out.println("String:" + k + " Value:" + v));
}
private static HashMap<String, Integer> findLongestPalindrome(String str) {
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (i < str.length()) {
String alpha = String.valueOf(str.charAt(i));
if (str.indexOf(str.charAt(i)) != str.lastIndexOf(str.charAt(i))) {
String pali = str.substring(i, str.lastIndexOf(str.charAt(i)) + 1);
if (isPalindrome(pali)) {
map.put(pali, pali.length());
i = str.lastIndexOf(str.charAt(i));
}
}
i++;
}
return map;
}
public static boolean isPalindrome(String input) {
for (int i = 0; i <= input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return false;
}
}
return true;
}
}
This approach is simple.
Output:
String:abcdeedcba Value:10
String:4444 Value:4
String:6776 Value:4
String:ghihg Value:5
This is my own way to get longest palindrome. this will return the length and the palindrome word
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.

Categories

Resources