2d array out of bound exception in for-loop - java

I'm working on keyword columnar cipher and I keep getting array out of bound exception, I have tried debugging the code and try and catch to understand the problem but I couldn't!
public Decryption (String cipherText, String keyWord) {
cipherText = cipherText.replaceAll("\\s+","");
cipherText = cipherText.toUpperCase();
cipherText = cipherText.trim();
keyWord = keyWord.toUpperCase();
int column = keyWord.length();
int row = (cipherText.length() / keyWord.length());
if (cipherText.length() % keyWord.length() != 0)
row += 1;
char [][] matrix = new char [row][column];
int re = cipherText.length() % keyWord.length();
for (int i = 0; i < keyWord.length() - re; i++)
matrix[row - 1][keyWord.length() - 1 - i] = '*';
char[] sorted_key = keyWord.toCharArray();
Arrays.sort(sorted_key);
int p = 0, count = 0;
char[] cipher_array = cipherText.toCharArray();
Map<Character,Integer> indices = new HashMap<>();
for(int i = 0; i < column; i++){
int last = indices.computeIfAbsent(sorted_key[i], c->-1);
p = keyWord.indexOf(sorted_key[i], last+1);
indices.put(sorted_key[i], p);
for(int j = 0; j < row; j++){
if (matrix[j][p] != '*')
matrix[j][p] = cipher_array[count];
count++;
}}
}
I'm getting the exception in:
matrix[j][p] = cipher_array[count];
there is a problem with the loop, if I start with j = 1 it doesn't give me the exception but I don't get the correct results (It doesn't print the last row)
The cipher text that I'm trying to decrypt:
YARUEDCAUOADGRYHOBBNDERPUSTKNTTTGLORWUNGEFUOLNDRDEYGOOAOJRUCKESPY
Keyword:
YOURSELF
The result I get when I start the loop with 1:
JUDGE YOURSELF ABOUT YOUR BACKGROUND KNOWLEDGE TO UNDERSTAND CRYP
What I'm supposed to get:
JUDGE YOURSELF ABOUT YOUR BACKGROUND KNOWLEDGE TO UNDERSTAND
CRYPTOGRAPHY

I'm not precisely sure, because your code doesnt allow me to validate this (there is no easy way to check the output of the algorithm without digging in), so... I assume that solution is:
for (int j = 0; j < row; j++) {
if (matrix[j][p] != '*'){
matrix[j][p] = cipher_array[count];
count++;
}
}
instead of:
for (int j = 0; j < row; j++) {
if (matrix[j][p] != '*')
matrix[j][p] = cipher_array[count];
count++;
}

I think that the strategy of appending '*' to the string in this case is not the way to go - like what you did. Better to append some character when you are building the grid.
Following this approach here is a fixed version of your code (check the comments in the code for the changed parts):
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Decryption {
private final String result;
public Decryption(String cipherText, String keyWord) {
cipherText = cipherText.replaceAll("\\s+", "");
cipherText = cipherText.toUpperCase();
cipherText = cipherText.trim();
keyWord = keyWord.toUpperCase();
int column = keyWord.length();
int row = (cipherText.length() / keyWord.length());
if (cipherText.length() % keyWord.length() != 0)
row += 1;
int[][] matrix = new int[row][column];
// Changed to calculate the irregular columns
int re = column - (row * column - cipherText.length());
char[] sorted_key = keyWord.toCharArray();
Arrays.sort(sorted_key);
int p, count = 0;
char[] cipher_array = cipherText.toCharArray();
Map<Character, Integer> indices = new HashMap<>();
for (int i = 0; i < column; i++) {
int last = indices.computeIfAbsent(sorted_key[i], c -> -1);
p = keyWord.indexOf(sorted_key[i], last + 1);
indices.put(sorted_key[i], p);
// Changed: Detects the need of an extra character and fills it in case of need
boolean needsExtraChar = p > re - 1;
for (int j = 0; j < row - (needsExtraChar ? 1 : 0); j++) {
matrix[j][p] = cipher_array[count];
count++;
}
if(needsExtraChar) {
matrix[row - 1][p] = '-';
}
}
result = buildString(matrix);
}
public static void main(String[] args) {
System.out.println(new Decryption("EVLNE ACDTK ESEAQ ROFOJ DEECU WIREE", "ZEBRAS").result);
System.out.println(new Decryption("EVLNA CDTES EAROF ODEEC WIREE", "ZEBRAS").result);
System.out.println(new Decryption("YARUEDCAUOADGRYHOBBNDERPUSTKNTTTGLORWUNGEFUOLNDRDEYGOOAOJRUCKESPY", "YOURSELF").result);
}
private String buildString(int[][] grid) {
return Arrays.stream(grid).collect(StringBuilder::new, (stringBuilder, ints) -> Arrays.stream(ints).forEach(t -> {
stringBuilder.append((char) t);
}), (stringBuilder, ints) -> {
}).toString().replace("-", "");
}
}
If you run this, this will print:
WEAREDISCOVEREDFLEEATONCEQKJEU
WEAREDISCOVEREDFLEEATONCE
JUDGEYOURSELFABOUTYOURBACKGROUNDKNOWLEDGETOUNDERSTANDCRYPTOGRAPHY

Related

Even after using a global static array my values of the array are changing in java. How to overcome it?

In this code I am having some problem as I have marked using a loop which is printing some values. I am storing them in an array as mentioned and am trying to print the values in another function. But even after using the global array the value of the array is changing.
I am not able to figure out the problem. Please help me out.
import java.io.*;
import java.util.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
// Java program to print all permutations of a
// given string.
public class test3
{
static int[] val = new int[100] ; //array declaration as global
public static void main(String[] args)
{
System.out.println("An incremented value");
for(int i=2;i<=2;i++) {
String p="";
for(int j=0;j<=i;j++) {
for(int m=0;m<j;m++) {
p=p+"&";
}
for(int m=0;m<i-j;m++) {
p=p+"|";
}
printAllPermutations(p);
p="";
}
}
System.out.println();
for(int xy=0;xy<32;xy++)
System.out.print("["+xy+"]"+"="+val[xy]+" "); //trying to print the array
}
static void print(char[] temp) {
String a="";
System.out.println();
for (int i = 0; i < temp.length; i++)
{ System.out.print(temp[i]);
a=a+temp[i];}
System.out.print(" "+"opr:"+temp.length+" ");
final int N = temp.length+1;
/*===================CODE PROBLEM PART START=======================*/
for (int i = 0; i < (1 << N); i++) {
// System.out.println(zeroPad(Integer.toBinaryString(i), N));
String b=zeroPad(Integer.toBinaryString(i), N)+"";
// System.out.println("a: "+a+" b:"+b);
char[] arrayA = b.toCharArray();
char[] arrayB = a.toCharArray();
StringBuilder sb = new StringBuilder();
int ii = 0;
while( ii < arrayA.length && ii < arrayB.length){
sb.append(arrayA[ii]).append(arrayB[ii]);
++ii;
}
for(int j = ii; j < arrayA.length; ++j){
sb.append(arrayA[j]);
}
for(int j = ii; j < arrayB.length; ++j){
sb.append(arrayB[j]);
}
//System.out.println(sb.toString());
try {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("JavaScript");
String myExpression = sb.toString();
// System.out.print(se.eval(myExpression));
val[i]=(int)(se.eval(myExpression)); //inserting array value
System.out.print(val[i]); //NEED TO HAVE THESE VALUES IN THE 1-D ARRAY
// System.out.print(val[i]);
} catch (ScriptException e) {
System.out.println("Invalid Expression");
e.printStackTrace();}
}
/*===================CODE PROBLEM PART END========================*/
//
}
//unchangable = rest of the function
static int factorial(int n) {
int f = 1;
for (int i = 1; i <= n; i++)
f = f * i;
return f;
}
static int calculateTotal(char[] temp, int n) {
int f = factorial(n);
// Building HashMap to store frequencies of
// all characters.
HashMap<Character, Integer> hm =
new HashMap<Character, Integer>();
for (int i = 0; i < temp.length; i++) {
if (hm.containsKey(temp[i]))
hm.put(temp[i], hm.get(temp[i]) + 1);
else
hm.put(temp[i], 1);
}
// Traversing hashmap and finding duplicate elements.
for (Map.Entry e : hm.entrySet()) {
Integer x = (Integer)e.getValue();
if (x > 1) {
int temp5 = factorial(x);
f = f / temp5;
}
}
return f;
}
static void nextPermutation(char[] temp) {
// Start traversing from the end and
// find position 'i-1' of the first character
// which is greater than its successor.
int i;
for (i = temp.length - 1; i > 0; i--)
if (temp[i] > temp[i - 1])
break;
// Finding smallest character after 'i-1' and
// greater than temp[i-1]
int min = i;
int j, x = temp[i - 1];
for (j = i + 1; j < temp.length; j++)
if ((temp[j] < temp[min]) && (temp[j] > x))
min = j;
// Swapping the above found characters.
char temp_to_swap;
temp_to_swap = temp[i - 1];
temp[i - 1] = temp[min];
temp[min] = temp_to_swap;
// Sort all digits from position next to 'i-1'
// to end of the string.
Arrays.sort(temp, i, temp.length);
// Print the String
print(temp);
}
static void printAllPermutations(String s) {
// Sorting String
char temp[] = s.toCharArray();
Arrays.sort(temp);
// Print first permutation
print(temp);
// Finding the total permutations
int total = calculateTotal(temp, temp.length);
for (int i = 1; i < total; i++)
nextPermutation(temp);
}
static String zero(int L) {
return (L <= 0 ? "" : String.format("%0" + L + "d", 0));
}
static String zeroPad(String s, int L) {
return zero(L - s.length()) + s;
}
}
The output that I am getting is
An incremented value
|| opr:2 01111111 //WANT TO STORE THESE 32 VALUES IN 1 D ARRAY
&| opr:2 01010111 // AND PRINT THEM OUT
|& opr:2 00011111
&& opr:2 00000001
[0]=0 [1]=0 [2]=0 [3]=0 [4]=0 [5]=0 [6]=0 [7]=1 [8]=0 [9]=0 [10]=0 [11]=0 [12]=0 [13]=0 [14]=0 [15]=0 [16]=0 [17]=0 [18]=0 [19]=0 [20]=0 [21]=0 [22]=0 [23]=0 [24]=0 [25]=0 [26]=0 [27]=0 [28]=0 [29]=0 [30]=0 [31]=0
what I need to do is to store those 32 values in 1 D array for further operation but while doing it all the array values displays 0 only except [7]. I dont know whats going on here.
Reference types are not bound to local scopes, just because your array is static to the class it does not mean that changing the values in one function will not change the values in the actual array. The reference to your array as a parameter will be a copy, but the reference is still "pointing" on an actual object, which is not a copy bound to your local scope.
If you want to save two different states of the array, you will have to save them yourself.

Algorithm - Lexicographically largest possible magical substring

I am working on this magical sub-string problem.
Magical binary strings are non-empty binary strings if the following two conditions are true:
The number of 0's is equal to the number of 1's.
For every prefix of the binary string, the number of 1's should not be less than the number of 0's.
I got stuck on how to proceed further in my Java program.
Here is my program:
static String findLargest(String str) {
String[] splits = str.split("");
Set<String> set = new LinkedHashSet<String>();
for (int i = 0; i < splits.length; i++) {
if (splits[i].equals("0")) {
continue;
}
int zeros = 0;
int ones = 0;
StringBuilder sb = new StringBuilder("");
for (int j = i; j < splits.length; j++) {
if (splits[j].equals("0")) {
zeros++;
} else {
ones++;
}
sb.append(splits[j]);
if (zeros == ones && ones >= zeros) {
set.add(sb.toString());
}
}
}
set.remove(str);
List<String> list = new ArrayList<String>(set);
System.out.println(list);
return null;
}
Using this program I am able to get the magical sub-strings for the given input String 11011000 as [10, 101100, 1100] in my list variable.
Now from here I am struggling how to remove the invalid entry of 101100 from my list and then use the elements 10, 1100 to swap from my input 11011000 to get the final result as 11100100
Also please guide me if there is any other alternate approach.
If your question is about only eliminating the unwanted "101100" from the result, here is the answer
import java.util.ArrayList;
import java.util.HashMap;
import java.lang.*;
import java.util.Set;
import java.util.*;
public class HelloWorld{
public static void main(String []args){
findLargest("11011000");
}
public static String findLargest(String str) {
String[] splits = str.split("");
Set<String> set = new LinkedHashSet<String>();
for (int i = 0; i < splits.length; i++) {
if (splits[i].equals("0")) {
continue;
}
int zeros = 0;
int ones = 0;
StringBuilder sb = new StringBuilder("");
for (int j = i; j < splits.length; j++) {
if (splits[j].equals("0")) {
zeros++;
} else {
ones++;
}
sb.append(splits[j]);
if (zeros == ones && ones >= zeros) {
set.add(sb.toString());
j = i +1; // RESET THE INDEX ELEMENT TO SKIP THE SUBSTRING FROM CONSIDERATION
break; // BREAK FROM THE LOOP
}
}
}
set.remove(str);
List<String> list = new ArrayList<String>(set);
System.out.println(list);
return null;
}
}
I can provide some points.
First, get all the magical substrings and store them as a pair of start and end index(l, r) in a list;
Second, sort the list based on index l;
Those who can be potentially swapped substring can get from the same index l. look at the example given "11011000"
the list will have (0,7),(1,2),(1,6),(3,6),(4,5)
obviously only potential swap is among (1,2)(1,6)
deal these substrings have same index l will help find potential swapping substrings, sort them to find the maximum order.
class Pair{
int start;
int end;
}
public List<Pair> findmagicalPairs(String binString){
List<Pair> magicPairs = new ArrayList<Pair>();
for(int start=0;start<binString.length()-1;start++){
int ones=0;
int zeros=0;
for(int i=start; i<binString.length();i++){
if(binString.charAt(i) == '1'){
ones++;
} else if(binString.charAt(i)=='0'){
zeros++;
}
if(ones == zeros){ //check if magical
Pair temp=new Pair();
temp.start=start;
temp.end =i;
magicPairs.add(temp);
}
}
}
return magicPairs;
}
public String largestMagical(String binString) {
// Write your code here
List<Pair> allPairs = findmagicalPairs(binString);
String largest=binString;
//check by swapping each pairs
for(int i=0;i<allPairs.size()-1;i++){
for(int j=i+1;j<allPairs.size()-1;j++){
if(allPairs.get(i).end+1 == allPairs.get(j).start){
//consecutive Pair so swap and see largest
int index = allPairs.get(j).start;
String swapped = binString.substring(0,allPairs.get(i).start)+binString.substring(allPairs.get(j).start,allPairs.get(j).end+1)+binString.substring(allPairs.get(i).start,allPairs.get(i).end+1)+binString.substring(allPairs.get(j).end+1);
largest = LargestString(largest, swapped);
} else {
//else ignore
}
}
}
return largest;
}
public String LargestString(String first, String second){
if(first.compareTo(second)>0){
return first;
} else {
return second;
}
}
JavaScript Code!
const largestMagical = (binString) => {
//console.log({ binString });
const len = binString.length;
const height = Array(len + 1).fill(0),
num = { 1: 1, 0: -1 },
marked = Array(len + 1).fill(false),
sameHeights = {};
let i,
j,
result = "";
for (i = 1; i <= len; ++i) {
height[i] = height[i - 1] + num[binString[i - 1]];
}
//console.log({ height });
for (i = 0; i <= len; ++i) {
if (marked[i]) continue;
marked[i] = true;
sameHeights[i] = [i];
for (j = i + 1; j <= len; ++j) {
if (height[j] < height[i]) break;
if (height[j] === height[i]) {
sameHeights[i].push(j);
marked[j] = true;
}
}
}
//console.log({ sameHeights });
for (let k in sameHeights) {
const leng = sameHeights[k].length;
let startId, midId, endId;
for (startId = 0; startId < leng - 2; ++startId) {
for (midId = startId + 1; midId < leng - 1; ++midId) {
for (endId = midId + 1; endId < leng; ++endId) {
const start = sameHeights[k][startId],
mid = sameHeights[k][midId],
end = sameHeights[k][endId];
//console.log({start, mid, end});
const swapped =
binString.substring(0, start) +
binString.substring(mid, end) +
binString.substring(start, mid) +
binString.substring(end, len);
//console.log({swapped});
if (swapped > result) result = swapped;
}
}
}
}
return result;
};
console.log(largestMagical("1010111000"));
console.log(largestMagical("11011000"));

Java Transposition cipher for loop

I have been trying to recreate a python function to decrypt messages using a transposition cipher. although it keeps giving me incorrect outputs and making the messages longer. I think the error is to do with the array and the for loop but I'm not 100% sure.
My code
public String TranspositionDecryptText (String EncryptedText, int Key) {
double NumColumnsD = Math.ceil(EncryptedText.length() / Key);
int NumColumns = (int) NumColumnsD;
int NumRows = Key;
int NumShadedBoxes = (NumColumns * NumRows) - EncryptedText.length();
String NormalArray[] = new String[NumColumns];
int col = 0;
int row = 0;
for (int i = 0; i < EncryptedText.length(); i++) {
NormalArray[col] = NormalArray[col] + EncryptedText.charAt(i);
col = col + 1;
if ((col == NumColumns) || ((col == NumColumns - 1) && (row >= NumRows - NumShadedBoxes))) {
col = 0;
row = row + 1;
}
}
String NormalString = "";
for (int i = 0; i < NormalArray.length; i++) {
NormalString = NormalString + NormalArray[i];
}
return NormalString;
}
Python version http://inventwithpython.com/hacking/chapter9.html
def decryptMessage(key, message):
# The transposition decrypt function will simulate the "columns" and
# "rows" of the grid that the plaintext is written on by using a list
# of strings. First, we need to calculate a few values.
# The number of "columns" in our transposition grid:
numOfColumns = math.ceil(len(message) / key)
# The number of "rows" in our grid will need:
numOfRows = key
# The number of "shaded boxes" in the last "column" of the grid:
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
# Each string in plaintext represents a column in the grid.
plaintext = [''] * numOfColumns
# The col and row variables point to where in the grid the next
# character in the encrypted message will go.
col = 0
row = 0
for symbol in message:
plaintext[col] += symbol
col += 1 # point to next column
# If there are no more columns OR we're at a shaded box, go back to
# the first column and the next row.
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
col = 0
row += 1
return ''.join(plaintext)
I found that the text string given needed to be divisible by the key for the decryption to work. After finding this I added a loop to add spaces to the end of the text before being encrypted so the decryption program then has to trim the returned text before. The code now looks like this :
public class TranspositionCipher {
public String TranspositionEncryptText (String Text, int Key) {
while (Text.length() % Key != 0) {
Text = Text + " ";
}
ArrayList EncryptedText = new ArrayList<String>(Key); // Creates an array with as many elements as key
String HoldText = "";
for (int col = 0; col < Key; col++) {
int pointer = col;
while (pointer < Text.length()) {
HoldText = HoldText + Text.charAt(pointer);
pointer = pointer + Key;
}
EncryptedText.add(col, HoldText);
HoldText = "";
}
String EncryptedString = ""; // String version of encrypted text
Iterator iter = EncryptedText.iterator(); // Used to go through the array
while (iter.hasNext()) { // While there are more elements in the array
EncryptedString = EncryptedString + iter.next(); // Add the element to the string
}
return EncryptedString; // Return the encrypted text as a string
}
public String TranspositionDecryptText (String EncryptedText, int Key) {
double NumColumnsD = Math.ceil(EncryptedText.length() / Key);
int NumColumns = (int) NumColumnsD;
int NumRows = Key;
int NumShadedBoxes = (NumColumns * NumRows) - EncryptedText.length();
String NormalArray[] = new String[NumColumns];
int col = 0;
int row = 0;
for (int i = 0; i < NumColumns; i++) {
NormalArray[i] = "";
}
for (int i = 0; i < EncryptedText.length(); i++) {
NormalArray[col] = NormalArray[col] + EncryptedText.charAt(i);
System.out.println(NormalArray[col]);
col = col + 1;
if ((col == NumColumns) || ((col == NumColumns - 1) && (row >= NumRows - NumShadedBoxes))) {
col = 0;
row = row + 1;
}
}
String NormalString = "";
for (int i = 0; i < NormalArray.length; i++) {
NormalString = NormalString + NormalArray[i];
}
NormalString = NormalString.trim();
return NormalString;
}
}

Shuffling strings in Java

While I am creating Java String shuffler, I am getting a problem:
program stucks somewhere.
I have to pass a sentence or a word through BufferedReader
I have to shuffle the word/sentence so that first element is the first letter, then last letter, then 2nd letter, then 2nd from the end till the job is done
2.1. If word/sentence length is odd, the middle character has to be put in the end of the word/sentence.
Have to print it out
Result should be like this:
My code;
public static void main(String[] args) {
String enteredValue = null;
int charArrayLength = 0;
System.out.println("Dāvis Naglis IRDBD11 151RDB286");
System.out.println("input string:");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
enteredValue = br.readLine();
charArrayLength = enteredValue.length(); // length of array entered
char[] characters = new char[charArrayLength];
characters = enteredValue.toCharArray();
} catch (Exception e) {
e.printStackTrace();
}
char[] tempChars = new char[charArrayLength];
for (int i = 0; i <= charArrayLength - 1; i++) {
tempChars[i] = enteredValue.charAt(i);
}
}
/**
* Shuffles the char array if it's length is even
*
* #param array
*/
public static void shuffle(char[] array) {
char[] tempChars = null;
for (int j = 0; j <= array.length; j++) {
if ((array.length % 2 == 0) && (j < array.length)) { // array[j] == (array.length / 2) + 1
tempChars[j] = array[array.length - j];
} else if (array.length % 2 != 0) {
tempChars[array.length] = array[j];
} // end else if
} // end for
String shuffledSentence = new String(tempChars);
System.out.println(shuffledSentence);
}
Don't look at multiple line comments, haven't changed them since start.
Thanks in advance!
Shuffling made easy:
int len = array.length;
char[] tempArray = new char[len];
int i=0, j=0, k=len-1;
while (i<len) {
tempArray[i++] = array[j++];
if (i<len) {
tempArray[i++] = array[k--];
}
}
Wow. Your algorithm is too complex for this problem!
Try this for shuffling:
int n = array.length;
char[] resChars = new char[n];
boolean flag = false;
if (n % 2 != 0) {
flag = true;
char tmp = array[n / 2];
}
for (int j = 0; j < n - 1; j += 2) {
resChars[j] = array[j / 2];
resChars[j + 1] = array[n - 1 - (j / 2)]
}
if (flag)
resChars[n - 1] = tmp;
You can try something like this:
String str;
char[] chars = str.toCharArray();
List<Character> list = new ArrayList<>();
for (char aChar : chars) {
list.add(aChar);
}
Collections.shuffle(list);
String result = list.toString().replaceAll("[\\[\\],]", "");
Your program doesn't stuck, it exits properply.
Process finished with exit code 0
There is no more work to do for the process, since you don't call
your static shuffle method.
In addition, as the others already answered, your static shuffle method needs some design
refactoring.

How can I get the longest increasing subsequence in a string?

I'm pretty rusty on my Java skills but I was trying to write a program that prompts the user to enter a string and displays a maximum length increasing ordered subsequence of characters. For example, if the user entered Welcome the program would output Welo. If the user entered WWWWelllcommmeee, the program would still output Welo. I've gotten this much done but it's not doing what it should be and I'm honestly at a loss as to why.
import java.util.ArrayList;
import java.util.Scanner;
public class Stuff {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string. ");
String userString = input.next();
ArrayList charList = new ArrayList();
ArrayList finalList = new ArrayList();
int currentLength = 0;
int max = 0;
for(int i = 0; i < userString.length(); i++){
charList.add(userString.charAt(i));
for(int j = i; j < userString.length(); j++){
int k=j+1;
if(k < userString.length() && userString.charAt(k) > userString.charAt(j)){
charList.add(userString.charAt(j));
currentLength++;
}
}
}
if(max < currentLength){
max = currentLength;
finalList.addAll(charList);
}
for (int i = 0; i < finalList.size(); i++){
char item = (char) finalList.get(i);
System.out.print(item);
}
int size1 = charList.size();
int size2 = finalList.size();
System.out.println("");
System.out.println("Size 1 is: " + size1 + " Size 2 is : " + size2);
}
}
My code, if I input Welcome, outputs WWeceeclcccome.
Does anyone have some tips on what I'm doing wrong?
In these cases it tends to help to step away from the keyboard and think about the algorithm you're trying to implement. Try to explain it first in words.
You are constructing a list of individual characters by appending each of the characters in the input string followed by characters to its right that are in correct alphabetical with their successor. For the input "Welcome" this means the accumulated output will be, showing the outer loop in vertical and inner loop in horizontal:
W W e c
e e c
l c
c c
o
m
e
In total: WWeceeclccome
I can't see the logic of this implementation. Here is a faster solution which runs in O(nlogn) time.
import java.util.Scanner;
public class Stuff
{
//return the index of the first element that's not less than the target element
public static int bsearch(char[] arr, int size, int key)
{
int left = 0;
int right = size - 1;
int mid;
while (left <= right)
{
mid = (left + right) / 2;
if(arr[mid] < key)
left = mid + 1;
else
right = mid - 1;
}
return left;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string: ");
String userString = input.next();
char[] maxArr = new char[userString.length()];
char[] precedent = new char[userString.length()];
maxArr[0] = userString.charAt(0);
precedent[0] = userString.charAt(0);
int len = 1;
for(int i = 1; i < userString.length(); i++)
{
if(userString.charAt(i) > maxArr[len - 1])
{
maxArr[len] = userString.charAt(i);
precedent[len] = userString.charAt(i);
len++;
}
else
maxArr[bsearch(maxArr, len, userString.charAt(i))] = userString.charAt(i);
}
//System.out.println(len);
for(int i = 0; i < len; i++)
System.out.print(precedent[i]);
}
}
Using Dynamic Programming O(N^2) in lexicography order mean if i/p is abcbcbcd then o/p can be abcccd, abbbcd, abbccd but as per lexicography order o/p will be abbbcd.
public static String longestIncreasingSubsequence(String input1) {
int dp[] = new int[input1.length()];
int i,j,max = 0;
StringBuilder str = new StringBuilder();
/* Initialize LIS values for all indexes */
for ( i = 0; i < input1.length(); i++ )
dp[i] = 1;
/* Compute optimized LIS values in bottom up manner */
for ( i = 1; i < input1.length(); i++ )
for ( j = 0; j < i; j++ )
if (input1.charAt(i) >= input1.charAt(j) && dp[i] < dp[j]+1)
dp[i] = dp[j] + 1;
/* Pick maximum of all LIS values */
for ( i = 0; i < input1.length(); i++ ) {
if ( max < dp[i] ) {
max = dp[i];
if (i + 1 < input1.length() && max == dp[i+1] && input1.charAt(i+1) < input1.charAt(i)) {
str.append(input1.charAt(i+1));
i++;
} else {
str.append(input1.charAt(i));
}
}
}
return str.toString();
}

Categories