The question is how do I put one two-dimensional array into another if I explain simply the meaning of this project is a self-constructed maze of room which I, as an amateur, cannot describe with due detail because
I don't know what details to add.
import java.util.concurrent.ThreadLocalRandom;
import java.util.Arrays;
import java.util.*;
public class Main
{
static String[][] maze;
public static String Room (int x)
{
// create random number
int randomNum = ThreadLocalRandom.current ().nextInt (5, x + 1);
maze = new String[randomNum][randomNum];
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze.length; j++) {
//create the ROOM
maze[i][j] = "c";
maze[0][j] = "\u2014";
maze[maze.length - 1][j] = "\u2014";
maze[i][0] = "\u007c";
maze[i][maze.length - 1] = "\u007c";
maze[0][maze.length - 1] = "+";
maze[maze.length - 1][0] = "+";
maze[0][0] = "+";
maze[maze.length - 1][maze.length - 1] = "+";
}
}
return (Arrays.deepToString(maze)
.replace("]", "\n")
.replace("[[", " ")
.replace("[", "")
.replace(",", ""));
}
public static String Maze(int x) {
int randomNum = ThreadLocalRandom.current ().nextInt (40, x + 1);
maze = new String[randomNum][randomNum];
for (int i = 0; i < maze.length; i++) {
// create the maze
for (int j = 0; j < maze.length; j++) {
maze[i][j] = "r";
maze[0][j] = "\u2014";
maze[maze.length - 1][j] = "\u2014";
maze[i][0] = "\u007c";
maze[i][maze.length - 1] = "\u007c";
maze[0][maze.length - 1] = "+";
maze[maze.length - 1][0] = "+";
maze[0][0] = "+";
maze[maze.length - 1][maze.length - 1] = "+";
}
}
return (Arrays.deepToString(maze)
.replace("]", "\n")
.replace ("[[", " ")
.replace ("[", "")
.replace (",", ""));
}
public static void main (String[] args) {
// just output
String a = Maze(40);
String x = Room(10);
System.out.println(a);
System.out.println(x);
}
}
Based on your comments, you need to change the room function to use a local string[][] instead of the static string[][] maze declared by the class and change your return statement to process that instead.
Then change your maze function to call the room function each loop instead of doing its own thing
Related
Problem : You have L, a list containing some digits (0 to 9). Write a function solution(L) which finds the largest number that can be made from some or all of these digits and is divisible by 3. If it is not possible to make such a number, return 0 as the solution. L will contain anywhere from 1 to 9 digits. The same digit may appear multiple times in the list, but each element in the list may only be used once.
Test Cases :
Input:
Solution.solution({3, 1, 4, 1})
Output: 4311
Input:
Solution.solution({3, 1, 4, 1, 5, 9})
Output: 94311
My Program :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
public class Solution {
static ArrayList<Integer> al = new ArrayList<Integer>();
static ArrayList<Integer> largest = new ArrayList<Integer>();
static int o = 1;
static int po = 0;
static void combinations(String[] digits, String[] data, int start, int end, int index, int r)
{
if (index == r)
{
String temp = "0";
for (int j = 0; j < r; j++)
{
temp = temp + data[j];
// System.out.print(data[j]);
}
Integer d = Integer.parseInt(temp);
al.add(d);
// System.out.println(al);
}
for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
{
data[index] = digits[i];
combinations(digits, data, i + 1, end, index + 1, r);
}
}
static void printCombinations(String[] sequence, int N)
{
String[] data = new String[N];
for (int r = 0; r < sequence.length; r++)
combinations(sequence, data, 0, N - 1, 0, r);
}
static String[] convert(int[] x)
{
String c[] = new String[x.length];
for(int i=0; i < x.length; i++)
{
Integer k = x[i];
if(k==0)
{
o = o * 10;
continue;
}
c[i] = k.toString();
}
// System.out.println(o);
c = Arrays.stream(c).filter(s -> (s != null && s.length() > 0)).toArray(String[]::new);
po = c.length;
// System.out.println("Come"+ Arrays.asList(c));
return c;
}
public static int solution(int[] l) {
if(l.length==0)
return 0;
if(IntStream.of(l).sum()%3==0)
{
String x = "";
Arrays.sort(l);
for (int i = l.length - 1; i >= 0; i--) {
x = x + l[i];
}
return Integer.parseInt(x);
}
printCombinations(convert(l),po);
al.sort(Comparator.reverseOrder());
al.remove(al.size()-1);
al.removeIf( num -> num%3!=0);
if(al.isEmpty())
return 0;
for(int i=0; i< al.size(); i++)
{
Integer n = al.get(i);
printMaxNum(n);
}
// System.out.println(al);
// System.out.println(largest);
return largest.get(0)*o;
}
static void printMaxNum(int num)
{
// hashed array to store count of digits
int count[] = new int[10];
// Converting given number to string
String str = Integer.toString(num);
// Updating the count array
for(int i=0; i < str.length(); i++)
count[str.charAt(i)-'0']++;
// result is to store the final number
int result = 0, multiplier = 1;
// Traversing the count array
// to calculate the maximum number
for (int i = 0; i <= 9; i++)
{
while (count[i] > 0)
{
result = result + (i * multiplier);
count[i]--;
multiplier = multiplier * 10;
}
}
// return the result
largest.add(result);
}
public static void main(String[] args) {
System.out.println(solution(new int[]{9,8,2,3}));
}
}
My Code passes both given test cases and 3 other hidden test cases except one. I tried all possible input combinations but couldn't get to the exact failure. The return type by default is given as int and therefore they would not pass values which give output that does not fit in int. Any other scenario where my code fails?
I'm trying to solve https://leetcode.com/problems/longest-repeating-substring/
I want to use rolling hash to match strings.
However, my codes don't seem to work when I deal with modulo.
For a string with all same characters, the maximum length of repeating substring should be string.length - 1.
public class Main {
public static void main(String[] args) {
String str = "bbbbbbbbbbbbbbbbbbb";
System.out.println(str.length() - 1);
Solution s = new Solution();
System.out.println(s.longestRepeatingSubstring(str));
}
}
class Solution {
public int longestRepeatingSubstring(String S) {
HashSet<Long> h = new HashSet();
long mod = (long)1e7 + 7;
for(int i = S.length() - 1; i >0; i--){
h = new HashSet();
long c = 0;
int j = 0;
for(; j < i; j ++){
c = (c*26 % mod + S.charAt(j) - 'a')% mod;
}
h.add(c);
for(; j < S.length(); j++){
c -= (S.charAt(j - i ) - 'a') * Math.pow(26,i-1)% mod;
c = (c*26 % mod + S.charAt(j) - 'a')% mod;
if(h.contains(c)){
return i;
}
h.add(c);
}
}
return 0;
}
}
Playground for my codes: https://leetcode.com/playground/F4HkxbFQ
We cannot see your original link, we need a password.
The usage of modulo seems to be really complex.
Why not try something like this
class Scratch {
// "static void main" must be defined in a public class.
public static void main(String[] args) {
String str = "bbaaabbbbccbbbbbbzzzbbbbb";
System.out.println(str.length() - 1);
Solution s = new Solution();
System.out.println(s.longestRepeatingSubstring(str));
}
static class Solution {
public int longestRepeatingSubstring(String s) {
int max = -1;
int currentLength = 1;
char[] array = s.toCharArray();
for (int index = 1; index < array.length; index++) {
if (array[index - 1] == array[index]) {
currentLength++;
max = Math.max(max, currentLength);
} else {
currentLength = 1;
}
}
return max;
}
}
}
I was trying to solve a problem based on value and weight. In the task i had to pick out the elements by their value and weight, and find the highest efficiency solution. I receive an answer, however i am having trouble outputting the elements that were used in order to get an answer.
I've tried creating a string in which i place the values, however it gives out an outofbounds error.
public static void main(String[] args) {
String z[] = new String[]{"a","b","c","d","e","f","g","h","l","m"};
int w[] = new int[]{10,2,4,6,8,1,7,11,4,5};
int c[] = new int[]{20,3,5,7,4,1,8,15,8,6};
int maxW = 50;
int n = c.length;
System.out.println("");
int a = Find(w,c,maxW,n,z);
System.out.println("max value is " + a);
}
static int max(int a, int b)
{
if(a>b)
{
return a;
}
return b;
}
public static int Find(int w[],int c[], int maxW,int n, String[]z)
{
int K[][] = new int[n + 1][maxW + 1];
String s = "";
// Build table K[][] in bottom up manner
for (int i = 0; i<= n; i++)
{
for(int j = 0; j<= maxW; j++)
{
if (i == 0 || j == 0)
{
K[i][j] = 0;
}
else if (w[i - 1]<= j)
{
K[i][j] = max(c[i - 1] + K[i - 1][j - w[i - 1]], K[i - 1][j]);
}
else
{
K[i][j] = K[i - 1][j];
}
}
}
return K[n][maxW];
}
}
i want to output the same index element in string z, as the index element that is used to find the efficiancy.
The ideal result would be something like this in a string:
a a a b c d e m
(Just an example)
Thank you in advance.
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
Say I have a string x and I want to add some character x amount of times so that string x becomes of length y, how would I do this?
String x = "this_is_a_line";
//x.length() = 14;
length y = 20;
//insert character into line so String x becomes balanced to:
x = "this___is___a___line";
//x.length() = 20;
Another example:
String y = "in_it_yeah";
//y.length() = 10
length j = 15;
//inserting characters so String y becomes balanced to:
y = "in____it___yeah";
I want to avoid using StringBuilder to append characters.
My thought process:
Create a Char array of length y.
Copy the string to array.
Attempt to shift the characters one by one
from the furthest character to the right.
I hope I understood you correctly but I think this code does what you're requesting.
Edit: this one will distribute the specified character evenly and can create strings like "a__b_c" if the string isn't long enough yet.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String string = "this_is_a_line";
int length = string.length();
int desiredLength = 16;
int extraLengthRequired = desiredLength - length;
char characterToBeDuplicated = '_';
String[] rawPieces = string.split(Character.toString(characterToBeDuplicated));
ArrayList<String> pieces = new ArrayList<>();
int emptyIndexes = 0;
for (String piece : rawPieces) {
if(piece.equals("")) {
emptyIndexes++;
} else {
pieces.add(piece);
}
}
int numOfCharactersToBeMultiplied = pieces.size() - 1;
int numOfMultiplications = (int) Math.floor((extraLengthRequired + emptyIndexes) / numOfCharactersToBeMultiplied) + 1;
int lengthLeft = (extraLengthRequired + emptyIndexes) % numOfCharactersToBeMultiplied;
String newString = pieces.get(0);
for (int i = 1; i < pieces.size(); i++) {
newString += characterToBeDuplicated;
if(lengthLeft > 0) {
newString += characterToBeDuplicated;
lengthLeft--;
}
for (int j = 1; j < numOfMultiplications; j++) {
newString += characterToBeDuplicated;
}
newString += pieces.get(i);
}
System.out.println(newString + " - " + newString.length());
}
}
Old solution:
public class Main {
public static void main(String[] args) {
String string = "this_is_a_line";
int length = string.length();
int desiredLength = 20;
int extraLengthRequired = desiredLength - length;
char characterToBeDuplicated = '_';
String[] pieces = string.split(Character.toString(characterToBeDuplicated));
int numOfCharactersToBeMultiplied = pieces.length - 1;
int numOfMultiplications = (int) Math.floor(extraLengthRequired / numOfCharactersToBeMultiplied);
String newString = pieces[0];
for (int i = 1; i < pieces.length; i++) {
newString += characterToBeDuplicated;
for (int j = 1; j < numOfMultiplications; j++) {
newString += characterToBeDuplicated;
}
newString += pieces[i];
}
System.out.println(newString);
}
}
I did this one because when I started doing a pseudo code it was a bit challenging for me, though I'm not a fan of answering questions like this on "gimme teh codez".
I recommend you though using StringBuilder on String concatenation inside for loops because it's more efficient than actual String concatenation with +=.
Note that:
This program adds spaces to the end, that's why I print it's length trimmed.
I split it by space with a regex \\s+ instead of _ because that's how you wrote it 1st
The following code works for
a____b_c -> a___b___c (Lenght 9)
a____b_c -> a____b___c (Lenght 10)
this_is_a_line -> this___is___a___line (Lenght 20)
in_it_yeah -> in____it___yeah (Length 15)
Code:
class EnlargeString {
public static void main (String args[]) {
String x = "a b c";
int larger = 10;
int numberOfSpaces = 0;
String s[] = x.split("\\s+"); //We get the number of words
numberOfSpaces = larger - s.length; //The number of spaces to be added after each token
int extraSpaces = numberOfSpaces % s.length; //Extra spaces for the cases of 4 spaces then 3 or something like that
System.out.println(extraSpaces);
String newSpace[] = new String[s.length]; //The String array that will contain all string between words
for (int i = 0; i < s.length; i++) {
newSpace[i] = " "; //Initialize the previous array
}
//Here we add the extra spaces (the cases of 4 and 3)
for (int i = 0; i < s.length; i++) {
if (extraSpaces == 0) {
break;
}
newSpace[i] += " ";
extraSpaces--;
}
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < totalSpaces / s.length; j++) {
newSpace[i] += " "; //Here we add all the equal spaces for all tokens
}
}
String finalWord = "";
for (int i = 0; i < s.length; i++) {
finalWord += (s[i] + newSpace[i]); //Concatenate
}
System.out.println(x);
System.out.println(x.length());
System.out.println(finalWord);
System.out.println(finalWord.trim().length());
}
}
Next time try to do it yourself 1st and show YOUR logic, then your question will be better received (maybe with upvotes instead of downvotes) this is called a Runnable Example. I also recommend you to take a look at String concatenation vs StringBuilder and How to ask a good question, also you might want to Take the tour
Here is my solution:
public class Main
{
public static void main(String args[]){
System.out.print("#Enter width : " );
int width = BIO.getInt();
System.out.print("#Enter line of text : " );
String line = BIO.getString().trim();
int nGaps, spToAdd, gapsLeft, modLeft, rem;
nGaps = spToAdd = gapsLeft = rem = 0;
double route = 0;
String sp = " ";
while ( ! line.equals( "END" )){
nGaps = numGaps(line);
if (nGaps == 0) { line = compLine(line, width).replace(" ", "."); }
else if (nGaps == width) { line = line.replace(" ", "."); }
else{
int posArray[] = new int[nGaps];
posArray = pos(line, nGaps);
gapsLeft = width - line.length();
spToAdd = gapsLeft / nGaps;
modLeft = gapsLeft % nGaps;
route = gapsLeft / nGaps;
sp = spGen(spToAdd);
line = reFormat(posArray, line, width, sp, spToAdd);
if (line.length() < width){
System.out.print("#OK\n");
nGaps = numGaps(line);
int posArray2[] = new int[nGaps];
posArray2 = pos(line, nGaps);
line = compFormat(posArray2, line, modLeft);
}
line = line.replace(" ", ".");
}
System.out.println(line);
System.out.println("#Length is: " + line.length());
System.out.print("#Enter line of text : " );
line = BIO.getString().trim();
}
}
public static int numGaps(String oLine){
int numGaps = 0;
for (char c : oLine.toCharArray()) { if (c == ' ') { numGaps++; } }
return numGaps;
}
public static String spGen(int count) {
return new String(new char[count]).replace("\0", " ");
}
public static String compLine(String oLine, int width){
String newLine = oLine;
int pos = oLine.length();
int numOSpace = width - oLine.length();
String sp = spGen(numOSpace);
newLine = new StringBuilder(newLine).insert(pos, sp).toString();
return newLine;
}
public static int[] pos(String oLine, int nGaps){
int posArray[] = new int[nGaps];
int i = 0;
for (int pos = 0; pos < oLine.length(); pos++) {
if (oLine.charAt(pos) == ' ') { posArray[i] = pos; i++; }
}
//for (int y = 0; y < x; ++y) { System.out.println(posArray[y]); }
return posArray;
}
public static String reFormat(int[] posArray, String oLine, int width, String sp, int spToAdd){
String newLine = oLine;
int mark = 0;
for (int i = 0; i < posArray.length; ++i){ /*insert string at mark, shift next element by the num of elements inserted*/
if (newLine.length() > width) { System.out.println("Maths is wrong: ERROR"); System.exit(1);}
else { newLine = new StringBuilder(newLine).insert(posArray[i]+mark, sp).toString(); mark += spToAdd; }
}
return newLine;
}
public static String compFormat(int[] posArray2, String mLine, int modLeft){
String newLine = mLine;
int mark = 0;
for (int i = 0; i < modLeft; ++i){
//positions
//if position y is != y+1 insert sp modLeft times
if (posArray2[i] != posArray2[i+1] && posArray2[i] != posArray2[posArray2.length - 1]){
newLine = new StringBuilder(newLine).insert(posArray2[i]+mark, " ").toString(); mark++;
}
}
return newLine;
}
}