I want to print the statement System.out.println(sb.append(ss));
Only the last time I tried to take it out of the for loop but the result is wrong.
public static String constatmentvertBinaryStringToString(String string) {
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss = null;
//for each character
for (int j = 0; j < chars.length; j += 8) {
int idx = 0;
int sum = 0;
//for each bit in reverse
for (int i = 7; i >= 0; i--) {
if (chars[i + j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div = sum / 4;
System.out.println(div);
System.out.println((char) div);
int rem = sum % 4;
System.out.println(rem);
ss = (char) div + "" + rem;
System.out.println(sb.append(ss));
}
return sb.toString();
}
Put System.out.println(sb.append(ss)); out of the loop:
public static String constatment vertBinaryStringToString(String string){
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss=null;
//for each character
for (int j = 0; j < chars.length; j+=8) {
int idx = 0;
int sum =0;
//for each bit in reverse
for (int i = 7; i>= 0; i--) {
if (chars[i+j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div=sum/4;
System.out.println(div);
System.out.println((char)div);
int rem=sum%4;
System.out.println(rem);
ss=(char)div+""+rem;
}
System.out.println(sb.append(ss));
return sb.toString();
}
Because System.out.println(sb.append(ss)); contains a call to sb.append(ss)); taking the statement out of the for loop will have a different result than the one expected.
You should keep sb.append(ss); inside the loop and add System.out.println(sb) outside the loop.
public static String constatmentvertBinaryStringToString(String string) {
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss = null;
//for each character
for (int j = 0; j < chars.length; j += 8) {
int idx = 0;
int sum = 0;
//for each bit in reverse
for (int i = 7; i >= 0; i--) {
if (chars[i + j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div = sum / 4;
System.out.println(div);
System.out.println((char) div);
int rem = sum % 4;
System.out.println(rem);
ss = (char) div + "" + rem;
sb.append(ss);
}
System.out.println(sb);
return sb.toString();
}
Related
public class GFG
{
static final int ASCII_SIZE = 256;
static char getMaxOccuringChar(String str)
{
int count[] = new int[ASCII_SIZE];
int len = str.length();
for (int i=0; i<len; i++)
count[str.charAt(i)]++;
int max = -1;
char result = ' ';
for (int i = 0; i < len; i++) {
if (max < count[str.charAt(i)]) {
max = count[str.charAt(i)];
result = str.charAt(i);
}
}
return result;
}
I stopped here and can't count the most repeated character.
The problem is that you should be iterating over the characters in the count array and not the string contents. You already counted them. Also the result will be the character represented by the value of i so you can just cast i to a char. Lastly unless you want to count spaces you should ignore character 32 (a space) and possibly other white-space characters or they may end up being the most common character. Here's a version that will count the most repeated character:
class GFG {
public static void main(String[] args) {
GFG s = new GFG();
char c = s.getMaxOccuringChar("People say there is nothing like a banana cream pie");
System.out.println("Max char is " + c);
}
static final int ASCII_SIZE = 256;
static char getMaxOccuringChar(String str) {
int count[] = new int[ASCII_SIZE];
int len = str.length();
for (int i = 0; i < len; i++)
count[str.charAt(i)]++;
int max = -1;
char result = ' ';
for (int i = 0; i < count.length; i++) {
if (max < count[i] && i != 32) {
max = count[i];
System.out.println("Max: "+max+" char: "+(char)i);
result = (char)i;
}
}
return result;
}
}
This will print out:
Max: 0 char:
Max: 1 char: P
Max: 6 char: a
Max: 7 char: e
Max char is e
In your second for loop you need
for (int i = 0; i < count.length; i++)
instead of
for (int i = 0; i < len; i++)
and then count[i]instead of count[str.charAt(i)]
and finally result = i instead of result = str.charAt(i)
The following code is supposed to convert letters to numbers and give the sum, but ignore any letters that are uppercase.
Example:
The input abcde should return 15. The input abCde should return 12.
Any help is appreciated.
static int strScore(String str[], String s, int n) {
int score = 0, index=0;
for (int i = 0; i < n; i++) {
if (str[i] == s) {
for (int j = 0; j < s.length(); j++)
score += s.charAt(j) - 'a' + 1;
index = i + 1;
break;
}
}
score = score * index;
return score;
}
public static void main(String[] args) {
String str[] = { "abcde" };
String s = "abcde";
int n = str.length;
int score = strScore(str, s, n);
System.out.println( score);
}
Use Character.isLowerCase(...).
So this is what your strScore method should look like:
static int strScore(String str[], String s, int n) {
int score = 0, index = 0;
for (int i = 0; i < n; i++) {
if (str[i].equals(s)) {
for (int j = 0; j < s.length(); j++) {
char c = s.charAt(j);
if(Character.isLowerCase(c)) // <-- This is the important part
score += c - 'a' + 1;
}
index = i + 1;
break;
}
}
score = score * index;
return score;
}
As pointed out in the comments, there is no need for the str and therfore neither the n parameter. This is a better version:
static int strScore(String s) {
int score = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(Character.isLowerCase(c))
score += c - 'a' + 1;
}
return score;
}
There are two things to address:
You have used == to compare strings. You need to use .equals
You need to put a check like if(s.charAt(j)>= 'a' && s.charAt(j)<'z')
for (int i = 0; i < n; i++) {
if (str[i].equals(s)) {
for (int j = 0; j < s.length(); j++)
if(s.charAt(j)>= 'a' && s.charAt(j)<'z') {
score += s.charAt(j) - 'a' + 1;
You can avoid passing String str[] = { "abcde" }; which has one element which equals s
to The method. You can also avoid passing n which is an simply str.length():
static int strScore(String s) {
int score = 0, index = 0;
for (int i = 0; i < s.length(); i++) {
for (char c : s.toCharArray()) {
if(c >= 'a' && c <'z') { //alternatively if(Character.isLowerCase(c))
score += c - 'a' + 1;
}
}
index = i + 1;
break;
}
score = score * index;
return score;
}
I'm trying to make a program that will format text entered so that each line is set to a specific Length and cant go over e.g. 20 and then have the characters format accordingly on each line and have "." pad the gaps to make up the set length.
This is the output I've got so far:
This.is..an..example
of..text..that..will
have..straight..left
and.right....margins
after formatting ...
For some reason the "." are not appearing between after and formatting as well as after the "g" a dot is missing a space is taking its place instead. It seems to always happen's on the last line.
This is what the output should look like:
This.is..an..example
of..text..that..will
have..straight..left
and.right....margins
after.formatting....
Code:
import java.util.*;
public class FormattedPadding {
public static ArrayList<String> fullJustify(ArrayList<String> a, int b) {
ArrayList<String> result = new ArrayList<String>();
if(a == null || a.size() == 0)
return result;
int i = 0;
int currentLength = 0;
String temp = "";
for(i = 0; i < a.size(); i++){
currentLength += a.get(i).length() + 1;
if(currentLength > b + 1) {
result.add(temp);
temp = "";
currentLength = 0;
i--;
//System.out.println("Intermediate result: " + result);
}
else
temp += a.get(i) + " ";
}
if(!temp.equals(""))
result.add(temp);
for(i = 0; i < result.size() - 1; i++){
temp = result.get(i);
String[] tempArray = temp.split(" ");
int totalLength = 0;
for(int j =0; j < tempArray.length; j++)
totalLength += tempArray[j].length();
int[] spaceCount = getSpaceCount(b-totalLength, tempArray.length);
for(int l =0; l < spaceCount.length; l++)
System.out.print(spaceCount[l] + " " );
System.out.println();
temp = "";
for(int j = 0; j < tempArray.length; j++){
temp += tempArray[j];
for(int k = 0; k < spaceCount[j]; k++)
temp += ".";
}
result.set(i, temp);
}
temp = result.get(result.size() - 1);
if(temp.length() < b){
while(temp.length() < b)
temp += ".";
}
else if(temp.length() > b)
temp = temp.substring(0, b);
result.set(result.size() - 1, temp);
return result;
}
public static int[] getSpaceCount(int freeSpace, int numOfStrings) {
int size = numOfStrings - 1;
int[] ret = new int[size + 1];
if(size == 0){
ret[0] = freeSpace;
}
else {
for(int i =0; i < ret.length; i++) {
if(size != 0){
ret[i] = freeSpace % size == 0 ? freeSpace/size : freeSpace/(size + 1);
}
freeSpace = freeSpace - ret[i];
size--;
}
}
return ret;
}
public static void main(String[] args) {
//ArrayList<String> a = new ArrayList<String>();
System.out.println("#Enter ");
String usrInput = BIO.getString();
String[] items = usrInput.split("\\s+"); // Split where whitespace is encounterd using the RegEx
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(items));
// ^Split input into ArrayList
int b = 20; // Line length
ArrayList<String> result = fullJustify(newList, b);
for(int i =0; i < result.size(); i++) {
System.out.println(result.get(i));
}
System.out.println(result);
}
}
First of all, I think your code will go to infinite loop if any of the words has length more than "b"
About the issue, you create different logic for the last line
temp = result.get(result.size() - 1);
if(temp.length() < b){
while(temp.length() < b)
temp += ".";
}
else if(temp.length() > b)
temp = temp.substring(0, b);
result.set(result.size() - 1, temp);
You can remote those part, and change the loop from result.size()-1 to result.size(), so it will cover all lines:
for(i = 0; i < result.size(); i++){
I am using this code for sentence similarties the code is available on java i want to use this in c#.
public static int getWordChanges(String s1, String s2) {
int similarityThreshold = 50;
int wordChanges = 0;
s1 = s1.toLowerCase().replace(".", "").replace(",", "").replace(";", "");
s2 = s2.toLowerCase().replace(".", "").replace(",", "").replace(";", "");
//Loop through each word in s1
for (int i = 0; i < s1.split(" ").length; i++) {
boolean exists = false;
//Search for i'th word in s1 in s2
for (int j = 0; j < s2.split(" ").length; j++) {
//Is the word misspelled?
if ((getLevenshteinDistance(s1.split(" ")[i], s2.split(" ")[j]) * 100 / s1.split(" ")[i].length()) < similarityThreshold) {
exists = true;
break;
}
}
//If the word does not exist, increment wordChanges
if (!exists) {
wordChanges++;
}
}
return wordChanges;
}
This is Java code i want to execute this code in c#
After convert the code in c#
public int getWordChanges(String s1, String s2)
{
int similarityThreshold = 50;
int wordChanges = 0;
s1 = s1.ToLower().Replace(".", "").Replace(",", "").Replace(";", "");
s2 = s2.ToLower().Replace(".", "").Replace(",", "").Replace(";", "");
//Loop through each word in s1
for (int i = 0; i < s1.Split(' ').Length; i++)
{
bool exists = false;
//Search for i'th word in s1 in s2
for (int j = 0; j < s2.Split(' ').Length; j++)
{
//Is the word misspelled?
if ((getLevenshteinDistance(s1.Split(' ')[i], s2.Split(' ')[j]) * 100 / s1.Split(' ')[i].Length()) < similarityThreshold)
{
exists = true;
break;
}
}
//If the word does not exist, increment wordChanges
if (!exists)
{
wordChanges++;
}
}
return wordChanges;
}
}
}
There are error at this line
if ((getLevenshteinDistance(s1.Split(' ')[i], s2.Split(' ')[j]) * 100 / s1.Split(' ')[i].Length()) < similarityThreshold)
on length error will show how i resolve this one
Add this function to your project
public static int getLevenshteinDistance(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
Source
And change .Length() to .Length Because String.Length is a property and not a method
I am writing a program for a class to first encrypt a string with a predetermined key. That part is done. Next part is where i have a problem or not a problem per se. its a question of redundancy. After this I am supposed to do a KPA on the string and the encrypted string to find the key.
Which is working but i am using like 15 nested for loops for the brute force. Is there another way to do this? without doing it recursively!
static String Key = null;
public static void main(String[] args) {
long startTime = System.nanoTime();
long startTime1 = System.currentTimeMillis();
int cntr = 0;
String key = "AAAAAAAAAAADDDAM";
String plaintext = "Secretfoemotherd";
StringBuilder cipher = new StringBuilder();
StringBuilder brutus = new StringBuilder();
byte[] ciphertext = encrypt(byteT(key), byteT(plaintext));
for (int i = 0; i < ciphertext.length; i++) {
cipher.append(ciphertext[i]);
}
while (true) {
char[] nkey = new char[16];
for (int i1 = 65; i1 < 122; i1++) {
nkey[0] = (char) i1;
for (int i2 = 65; i2 < 122; i2++) {
nkey[1] = (char) i2;
for (int i3 = 65; i3 < 122; i3++) {
nkey[2] = (char) i3;
for (int i4 = 65; i4 < 122; i4++) {
nkey[3] = (char) i4;
for (int i5 = 65; i5 < 122; i5++) {
nkey[4] = (char) i5;
for (int i6 = 65; i6 < 122; i6++) {
nkey[5] = (char) i6;
for (int i7 = 65; i7 < 122; i7++) {
nkey[6] = (char) i7;
for (int i8 = 65; i8 < 122; i8++) {
nkey[7] = (char) i8;
for (int i9 = 65; i9 < 122; i9++) {
nkey[8] = (char) i9;
for (int i10 = 65; i10 < 122; i10++) {
nkey[9] = (char) i10;
for (int i11 = 65; i11 < 122; i11++) {
nkey[10] = (char) i11;
for (int i12 = 65; i12 < 122; i12++) {
nkey[11] = (char) i12;
for (int i13 = 65; i13 < 122; i13++) {
nkey[12] = (char) i13;
for (int i14 = 65; i14 < 122; i14++) {
nkey[13] = (char) i14;
for (int i15 = 65; i15 < 122; i15++) {
nkey[14] = (char) i15;
for (int i16 = 65; i16 < 122; i16++) {
nkey[15] = (char) i16;
cntr++;
byte[] brutusCipher = Crack(
byteC(nkey),
byteT(plaintext));
for (int k = 0; k < brutusCipher.length; k++) {
brutus.append(brutusCipher[k]);
}
if (brutus
.toString()
.equals(cipher
.toString())) {
System.out
.println("found it");
System.out
.println("Key: "
+ Key);
System.out
.println("Brutus: "
+ brutus);
System.out
.println("i ran: "
+ cntr
+ "times");
long endTime = System
.nanoTime();
System.out
.println("time:"
+ (endTime - startTime)
+ " ns");
long endTime1 = System
.currentTimeMillis();
System.out
.println("Took "
+ (endTime1 - startTime1)
+ " ms");
return;
}
brutus.setLength(0);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
public static byte[] byteT(String s) {
return s.getBytes();
}
public static byte[] byteC(char[] s) {
StringBuilder temp = new StringBuilder();
for (int i = 0; i < s.length; i++) {
temp.append(s[i]);
}
Key = temp.toString();
return temp.toString().getBytes();
}
public static byte[] encrypt(byte[] key, byte[] plaintext) {
byte[] d = new byte[key.length];
System.out.println(key.length);
for (int i = 0; i < key.length; i++) {
d[i] = (byte) (key[i] ^ plaintext[i]);
}
return d;
}
public static byte[] Crack(byte[] key, byte[] plaintext) {
byte[] n = new byte[key.length];
for (int i = 0; i < key.length; i++) {
n[i] = (byte) (key[i] ^ plaintext[i]);
}
return n;
}
}
Here is my suggestion on how you can improve your code:
char[] nkey = new char[16];
for (int i =0 ;i<16;++i) {
nkey[i] = 65;
}
while (true) {
//... do the stuff you do in the inner of the cycle
int index = 15;
nkey[index]++;
while (index >= 0 && nkey[index] >= 122) {
nkey[index] = 65;
index--;
if (index < 0) {
break;
}
nkey[index]++;
}
}
You can imagine what I do as representing what you iterate upon as a number in base 122-65 and adding one to it.
You could create a class like this (not tested):
class IncrementableCharArray {
private final char[] array;
IncrementableCharArray(int size) {
array = new char[size];
Arrays.fill(array, 'A');
}
boolean increment() {
//here logic to increment the array
int index = 0;
while(index < array.length && array[index] == 'z') index++;
if (index == array.length) return false;
array[index]++;
return true;
}
char[] get() { return array; }
}
The performance won't be better but it will be a little bit more readable. And you can use it like this:
IncrementableCharArray array = new IncrementableCharArray(16);
while(array.increment()) {
char[] nkey = array.get();
//your test here
}