Affine Cipher Code in java that also encrypts integer - validation

private static int firstKey = 5;
private static int secondKey = 19;
private static int module = 26;
public static void main(String[] args) {
String input = "abcdefghijklmnopqrstuvwxyz";
String cipher = encrypt(input);
String deciphered = decrypt(cipher);
System.out.println("Source: " + input);
System.out.println("Encrypted: " + cipher);
System.out.println("Decrypted: " + deciphered);
}
static String encrypt(String input) {
StringBuilder builder = new StringBuilder();
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
character = (char) ((firstKey * (character - 'a') + secondKey) % module + 'a');
//}
builder.append(character);
}
return builder.toString();
}
static String decrypt(String input) {
StringBuilder builder = new StringBuilder();
// compute firstKey^-1 aka "modular inverse"
BigInteger inverse = BigInteger.valueOf(firstKey).modInverse(BigInteger.valueOf(module));
// perform actual decryption
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
int decoded = inverse.intValue() * (character - 'a' - secondKey + module);
character = (char) (decoded % module + 'a');
//}
builder.append(character);
}
return builder.toString();
}
i got this code from this site itself
but the above code does not decrpyt the integers ..
please help
above is a code that i got from this site.
but this doesnot decrypts the integer.
please help.

I have added two more functiond that incrypt and decrypt integers that work.You can use them when you want to incrypt, decrypt integers, and the previous functions when you want to enc/dec lower case alphabets
//Code
import java.math.BigInteger;
public class main{
private static int firstKey = 5;
private static int secondKey = 19;
private static int module = 26;
public static void main(String[] args) {
String input = "abcdefghijklmnopqrstuvwxyz";
String cipher = encrypt(input);
String deciphered = decrypt(cipher);
System.out.println("Source: " + input);
System.out.println("Encrypted: " + cipher);
System.out.println("Decrypted: " + deciphered);
System.out.println("\n");
//for Integer
String input1 = "826429837598327598327549832";
String cipher1 = encryptInt(input1);
String deciphered1 = decryptInt(cipher1);
System.out.println("Source: " + input1);
System.out.println("Encrypted: " + cipher1);
System.out.println("Decrypted: " + deciphered1);
}
static String encrypt(String input) {
StringBuilder builder = new StringBuilder();
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
character = (char) ((firstKey * (character - 'a') + secondKey) % module + 'a');
//}
builder.append(character);
}
return builder.toString();
}
static String decrypt(String input) {
StringBuilder builder = new StringBuilder();
// compute firstKey^-1 aka "modular inverse"
BigInteger inverse = BigInteger.valueOf(firstKey).modInverse(BigInteger.valueOf(module));
// perform actual decryption
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
int decoded = inverse.intValue() * (character - 'a' - secondKey + module);
character = (char) (decoded % module + 'a');
//}
builder.append(character);
}
return builder.toString();
}
//ENCRIPTION DECRIPTION FOR INTEGERS
static String encryptInt(String input) {
StringBuilder builder = new StringBuilder();
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
character = (char) ((firstKey * (character - '0') + secondKey) % module + '0');
//}
builder.append(character);
}
return builder.toString();
}
static String decryptInt(String input) {
StringBuilder builder = new StringBuilder();
// compute firstKey^-1 aka "modular inverse"
BigInteger inverse = BigInteger.valueOf(firstKey).modInverse(BigInteger.valueOf(module));
// perform actual decryption
for (int in = 0; in < input.length(); in++) {
char character = input.charAt(in);
// if (Character.isLetter(character)) {
int decoded = inverse.intValue() * (character - '0' - secondKey + module);
character = (char) (decoded % module + '0');
//}
builder.append(character);
}
return builder.toString();
}
}

Related

combine two byte[] in SHA512Digest 's doFinal

in this methode there is only one instruction that not working:
private static byte[] encodePassword(String password,String salt) throws UnsupportedEncodingException
{
String mergedPasswordAndSalt =mergePasswordAndSalt(password, salt);
SHA512Digest digester =new SHA512Digest();
byte[] hash = new byte[digester.getDigestSize()];
digester.update(hash, 0, mergedPasswordAndSalt.length());
digester.doFinal(hash, 0);
System.out.println("init hash= "+Base64.encode(hash));
for (int i = 1; i < ITERATIONS; ++i) {
digester.update(hash, 0, mergedPasswordAndSalt.length());
digester.doFinal(Bytes.concat(hash, mergedPasswordAndSalt.getBytes("UTF-8")),0);
}
System.out.println("FINAL hash= "+Base64.encode(hash));
return hash;
}
that instructions: is the equivalent of this one in the java api that is way:
for (int i = 1; i < ITERATIONS; ++i) {
hash = digester.digest(Bytes.concat(hash, mergedPasswordAndSalt.getBytes("UTF-8")));
}
I have the solution:
To concat bytes i used this method:
public static byte[] concat(byte[]... arrays) {
int length = 0;
byte[][] arr$ = arrays;
int pos = arrays.length;
for(int i$ = 0; i$ < pos; ++i$) {
byte[] array = arr$[i$];
length += array.length;
}
byte[] result = new byte[length];
pos = 0;
byte[][] arr$$=arrays;
arr$=arr$$;
int len$ = arrays.length;
for(int i$ = 0; i$ < len$; ++i$) {
byte[] array = arr$[i$];
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
To do 4999 iteration on the digest we need a method that takes the hash after every iteration and works in the current digest concatenated with the first diegest(generate out of loop):
private static byte[] encodePassword(String password,String salt) throws UnsupportedEncodingException
{
String mergedPasswordAndSalt =mergePasswordAndSalt(password, salt);
byte[] hash = new byte[88];
hash=digestt(mergedPasswordAndSalt.getBytes("UTF-8"));
for (int i = 1; i < ITERATIONS; ++i) {
hash=digestt(concat(hash,mergedPasswordAndSalt.getBytes("UTF-8")));
}
return hash;
}
public static byte[] digestt(byte[] bytes) {
Digest digest = new SHA512Digest();
byte[] resBuf = new byte[digest.getDigestSize()];
digest.update(bytes, 0, bytes.length);
digest.doFinal(resBuf, 0);
return resBuf;
}
thank you very much i asked many questions and you are always there for help.

Send Concatinated SMS message using EasySMPP API (How to Add UDH Info)

i am using c# API called EasySMPP, it is pretty great in sending single SMS, it is also good in send large SMS, but the recipient get the messages separately, which is not meaningful, what i am looking is how to modify the PDU so that i can append the UDH info.
How can i achieve adding a UHD info, here is the SubmitSM method from the API,
public int SubmitSM
(
byte sourceAddressTon,
byte sourceAddressNpi,
string sourceAddress,
byte destinationAddressTon,
byte destinationAddressNpi,
destinationAddress,
byte esmClass,
byte protocolId,
byte priorityFlag,
DateTime sheduleDeliveryTime,
DateTime validityPeriod,
byte registeredDelivery,
byte replaceIfPresentFlag,
byte dataCoding,
byte smDefaultMsgId,
byte[] message)
{
try
{
byte[] _destination_addr;
byte[] _source_addr;
byte[] _SUBMIT_SM_PDU;
byte[] _shedule_delivery_time;
byte[] _validity_period;
int _sequence_number;
int pos;
byte _sm_length;
_SUBMIT_SM_PDU = new byte[KernelParameters.MaxPduSize];
////////////////////////////////////////////////////////////////////////////////////////////////
/// Start filling PDU
Tools.CopyIntToArray(0x00000004, _SUBMIT_SM_PDU, 4);
_sequence_number = smscArray.currentSMSC.SequenceNumber;
Tools.CopyIntToArray(_sequence_number, _SUBMIT_SM_PDU, 12);
pos = 16;
_SUBMIT_SM_PDU[pos] = 0x00; //service_type
pos += 1;
_SUBMIT_SM_PDU[pos] = sourceAddressTon;
pos += 1;
_SUBMIT_SM_PDU[pos] = sourceAddressNpi;
pos += 1;
_source_addr = Tools.ConvertStringToByteArray(Tools.GetString(sourceAddress, 20, ""));
Array.Copy(_source_addr, 0, _SUBMIT_SM_PDU, pos, _source_addr.Length);
pos += _source_addr.Length;
_SUBMIT_SM_PDU[pos] = 0x00;
pos += 1;
_SUBMIT_SM_PDU[pos] = destinationAddressTon;
pos += 1;
_SUBMIT_SM_PDU[pos] = destinationAddressNpi;
pos += 1;
_destination_addr = Tools.ConvertStringToByteArray(Tools.GetString(destinationAddress, 20, ""));
Array.Copy(_destination_addr, 0, _SUBMIT_SM_PDU, pos, _destination_addr.Length);
pos += _destination_addr.Length;
_SUBMIT_SM_PDU[pos] = 0x00;
pos += 1;
_SUBMIT_SM_PDU[pos] = esmClass;
pos += 1;
_SUBMIT_SM_PDU[pos] = protocolId;
pos += 1;
_SUBMIT_SM_PDU[pos] = priorityFlag;
pos += 1;
_shedule_delivery_time = Tools.ConvertStringToByteArray(Tools.GetDateString(sheduleDeliveryTime));
Array.Copy(_shedule_delivery_time, 0, _SUBMIT_SM_PDU, pos, _shedule_delivery_time.Length);
pos += _shedule_delivery_time.Length;
_SUBMIT_SM_PDU[pos] = 0x00;
pos += 1;
_validity_period = Tools.ConvertStringToByteArray(Tools.GetDateString(validityPeriod));
Array.Copy(_validity_period, 0, _SUBMIT_SM_PDU, pos, _validity_period.Length);
pos += _validity_period.Length;
_SUBMIT_SM_PDU[pos] = 0x00;
pos += 1;
_SUBMIT_SM_PDU[pos] = registeredDelivery;
pos += 1;
_SUBMIT_SM_PDU[pos] = replaceIfPresentFlag;
pos += 1;
_SUBMIT_SM_PDU[pos] = dataCoding;
pos += 1;
_SUBMIT_SM_PDU[pos] = smDefaultMsgId;
pos += 1;
_sm_length = message.Length > 254 ? (byte)254 : (byte)message.Length;
_SUBMIT_SM_PDU[pos] = _sm_length;
pos += 1;
Array.Copy(message, 0, _SUBMIT_SM_PDU, pos, _sm_length);
pos += _sm_length;
Tools.CopyIntToArray(pos, _SUBMIT_SM_PDU, 0);
Send(_SUBMIT_SM_PDU, pos);
undeliveredMessages++;
return _sequence_number;
}
catch (Exception ex)
{
logMessage(LogLevels.LogExceptions, "SubmitSM | " + ex.ToString());
}
return -1;
}
Thanks a lot!!!!
As I can see, EasySMPP has option to split long text.
public int SendSms(String from, String to, bool splitLongText, String text, byte askDeliveryReceipt, byte esmClass, byte dataCoding)
Otherwise, smpp protocol has ability to do manually also.
Either in SAR parameters:
SAR_MSG_REF_NUM - reference, unique to all sms parts
SAR_SEGMENT_SEQNUM - sequence number (1,2,3...)
SAR_TOTAL_SEGMENTS - number of all sequences
or you can encapsulate in the beggining of the message
with UDHI set to 64
or you can set message in MESSAGE_PAYLOAD TLV and SMSC will do it for you.
Hope it helps
Here is the method where UDH is added.
public int SendSms(String from, String to,
bool splitLongText, String text,
byte askDeliveryReceipt,
byte esmClass, byte dataCoding)
{
int messageId = -1;
byte sourceAddressTon;
byte sourceAddressNpi;
string sourceAddress;
byte destinationAddressTon;
byte destinationAddressNpi;
string destinationAddress;
byte registeredDelivery;
byte maxLength;
sourceAddress = Tools.GetString(from, 20, "");
sourceAddressTon = getAddrTon(sourceAddress);
sourceAddressNpi = getAddrNpi(sourceAddress);
destinationAddress = Tools.GetString(to, 20, "");
destinationAddressTon = getAddrTon(destinationAddress);
destinationAddressNpi = getAddrNpi(destinationAddress);
registeredDelivery = askDeliveryReceipt;
if (dataCoding == 8)
{
// text = Tools.Endian2UTF(text);
maxLength = 70;
}
else
maxLength = 160;
if ((text.Length <= maxLength) || (splitLongText))
{
byte protocolId;
byte priorityFlag;
DateTime sheduleDeliveryTime;
DateTime validityPeriod;
byte replaceIfPresentFlag;
byte smDefaultMsgId;
// byte[] message = new byte[146];
byte[] udh = new byte[6];
string smsText = text;
byte[] message;
protocolId = 0;
priorityFlag = PriorityFlags.VeryUrgent;
sheduleDeliveryTime = DateTime.MinValue;
validityPeriod = DateTime.MinValue;
replaceIfPresentFlag =
ReplaceIfPresentFlags.DoNotReplace;
smDefaultMsgId = 0;
if (dataCoding == 8)
{
message = new byte[70];
}
else
{
message = new byte[146];
}
string[] lists = dataCoding == 8 ?
split_message_unicode(text) :
split_message_asci(text);
int count = 1;
foreach (string s in lists)
{
Array.Clear(message, 0, message.Length);
// while (smsText.Length > 0)
// {
int pos = 0;
// byte desc = Convert.ToByte('c');
byte headerLen = Convert.ToByte(05);
byte concat = Convert.ToByte(00);
byte refNo = Convert.ToByte(03);
byte sequenceNo = Convert.ToByte(03);
byte NoOfMessages = Convert.ToByte(lists.Length);
byte partNo = Convert.ToByte(count);
count++;
udh[pos] = headerLen;
pos++;
udh[pos] = concat;
pos++;
udh[pos] = refNo;
pos++;
udh[pos] = sequenceNo;
pos++;
udh[pos] = NoOfMessages;
pos++;
udh[pos] = partNo;
pos++;
Array.Copy(udh, 0, message, 0, pos);
if (dataCoding == 8)
{
int len = Tools.GetEthiopic(s).Length;
Array.Copy(Tools.GetEthiopic(s), 0, message,
pos, len);
//message =
Tools.GetEthiopic(smsText.Substring(0, smsText.Length >
maxLength ? maxLength : smsText.Length));
//message =
Encoding.UTF8.GetBytes(smsText.Substring(0, smsText.Length >
maxLength ? maxLength : smsText.Length));
}
else{
// message = Encoding.ASCII.GetBytes(s);
Array.Copy(Encoding.ASCII.GetBytes(s), 0,
message, pos, Encoding.ASCII.GetBytes(s).Length);
}
smsText = smsText.Remove(0, smsText.Length >
maxLength ? maxLength : smsText.Length);
messageId = SubmitSM(sourceAddressTon,
sourceAddressNpi, sourceAddress,
destinationAddressTon,
destinationAddressNpi, destinationAddress,
esmClass, protocolId,
priorityFlag,
sheduleDeliveryTime,
validityPeriod, registeredDelivery, replaceIfPresentFlag,
dataCoding, smDefaultMsgId,
message);
// }
}
}
else
{
byte[] data;
if (dataCoding == 8)
data = Tools.GetEthiopic(text);
//data = Encoding.UTF8.GetBytes(text);
else
data = Encoding.ASCII.GetBytes(text);
messageId = DataSM(sourceAddressTon, sourceAddressNpi,
sourceAddress,
destinationAddressTon,
destinationAddressNpi, destinationAddress,
esmClass, registeredDelivery,
dataCoding, data);
}
return messageId;
}
pass ems_class as 0x40, what you need to to is just to split your message in to parts, here is splitting method,
private string[] split_message_asci(string message)
{
int message_len = message.Length;
decimal val=(message.Length / 140m);
decimal parts = Math.Ceiling(val);
string[] strs = new string[(int)parts];
string str = string.Empty;
int interval=140;
int i =0;
int Count= 0;
while (i < message_len)
{
if (Count < (int)parts-1)
{
str = message.Substring(i, interval);
strs[Count] = str;
i += interval ;
}
else
{
str = message.Substring(i, message_len-i);
strs[Count] = str;
i += interval + 1;
}
Count++;
}
return strs;
}

Optimizing apriori algorithm code

I am writing code for apriori algorithm in data mining my code takes as long as 60 seconds for a pretty small dataset which is solved by other code i got from internet in just 2 seconds but i am not getting where am i doing wrong, can someone tell me why the other code is fast over mine.
My code:
import java.util.*;
import java.io.*;
public class Apriori_p {
double support;
ArrayList<String> trans;
Map<String, Integer> map;
long start;
void print(ArrayList<String> temp) {
for (int i = 0; i < temp.size(); i++) {
System.out.println(temp.get(i));
}
System.out.println("Count :" + temp.size());
}
void run() throws FileNotFoundException {
start = System.currentTimeMillis();
trans = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
map = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter support %");
support = sc.nextDouble();
System.out.println("Enter file name");
String file = sc.next();
sc = new Scanner(new File(file));
int lines = 0;
while (sc.hasNextLine()) {
String s = sc.nextLine();
if (s.matches("\\s*")) {
continue;
}
lines++;
String[] spl = s.split("\\s+");
ArrayList<Integer> elem = new ArrayList<>();
for (int i = 0; i < spl.length; i++) {
String cand;
int n = Integer.parseInt(spl[i]);
cand = spl[i].trim();
if (!elem.contains(n)) {
elem.add(n);
}
if (map.containsKey(cand)) {
int count = map.get(cand);
map.put(cand, count + 1);
} else {
map.put(cand, 1);
}
}
Collections.sort(elem);
String con = " ";
for (int i = 0; i < elem.size(); i++) {
con = con + elem.get(i) + " ";
String s1 = String.valueOf(elem.get(i)).trim();
if(!temp.contains(s1))
temp.add(s1);
}
trans.add(con);
}
support = (support * lines) / 100;
System.out.println(System.currentTimeMillis() - start);
apriori(temp, 1);
}
public static void main(String[] args) throws FileNotFoundException {
new Apriori_p().run();
}
public void apriori(ArrayList<String> temp, int m) {
Set<String> diff = null;
if (m == 1) {
diff = new HashSet<>();
}
for (int i = 0; i < temp.size(); i++) {
if (map.get(temp.get(i)) < support) {
if (m == 1) {
diff.add(temp.get(i));
}
temp.remove(i);
i--;
}
}
for (int i = 0; i < trans.size() && m == 1; i++) {
for (String j : diff) {
String rep = " " + j + " ";
trans.get(i).replace(rep, " ");
}
}
if (temp.size() == 0) {
return;
}
System.out.println("Size " + m + " :");
print(temp);
ArrayList<String> ntemp = new ArrayList<>();
int n = temp.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
StringTokenizer st1 = new StringTokenizer(temp.get(i), " ");
StringTokenizer st2 = new StringTokenizer(temp.get(j), " ");
String str1 = "", str2 = "";
for (int s = 0; s < m - 2; s++) {
str1 = str1 + " " + st1.nextToken();
str2 = str2 + " " + st2.nextToken();
}
if (str2.compareToIgnoreCase(str1) == 0) {
int s1 = Integer.parseInt(st1.nextToken()), s2 = Integer.parseInt(st2.nextToken());
String s3;
if (s1 <= s2) {
s3 = (str1 + " " + s1 + " " + s2).trim();
} else {
s3 = (str1 + " " + s2 + " " + s1).trim();
}
if(!ntemp.contains(s3)){
ntemp.add(s3);
}
}
}
}
temp.clear();
for (int j = 0; j < ntemp.size(); j++) {
int c = 0;
for (int i = 0; i < trans.size(); i++) {
int check = 0;
String tr = trans.get(i);
StringTokenizer st1 = new StringTokenizer(ntemp.get(j)," ");
while(st1.hasMoreElements()){
String str = st1.nextToken();
if(!tr.contains(" " + str + " ")){
check = 1;
break;
}
}
if(check == 0){
c= 1;
if (map.containsKey(ntemp.get(j))) {
int count = map.get(ntemp.get(j));
map.put(ntemp.get(j), count + 1);
} else {
map.put(ntemp.get(j), 1);
}
}
}
if (c == 0) {
ntemp.remove(j);
j--;
}
}
apriori(ntemp, m + 1);
}
}
Fast code:
import java.io.*;
import java.util.*;
public class Apriori3{
public static void main(String[] args) throws Exception {
Apriori3 ap = new Apriori3(args);
}
private List<int[]> itemsets;
private String transaFile;
private int numItems;
private int numTransactions;
private double minSup;
private boolean usedAsLibrary = false;
public Apriori3(String[] args) throws Exception {
configure(args);
go();
}
private void go() throws Exception {
long start = System.currentTimeMillis();
createItemsetsOfSize1();
int itemsetNumber = 1;
int nbFrequentSets = 0;
while (itemsets.size() > 0) {
calculateFrequentItemsets();
if (itemsets.size() != 0) {
nbFrequentSets += itemsets.size();
log("Found " + itemsets.size() + " frequent itemsets of size " + itemsetNumber + " (with support " + (minSup * 100) + "%)");;
createNewItemsetsFromPreviousOnes();
}
itemsetNumber++;
}
long end = System.currentTimeMillis();
log("Execution time is: " + ((double) (end - start) / 1000) + " seconds.");
log("Found " + nbFrequentSets + " frequents sets for support " + (minSup * 100) + "% (absolute " + Math.round(numTransactions * minSup) + ")");
log("Done");
}
private void foundFrequentItemSet(int[] itemset, int support) {
if (usedAsLibrary) {
} else {
System.out.println(Arrays.toString(itemset) + " (" + ((support / (double) numTransactions)) + " " + support + ")");
}
}
private void log(String message) {
if (!usedAsLibrary) {
System.err.println(message);
}
}
private void configure(String[] args) throws Exception {
if (args.length != 0) {
transaFile = args[0];
} else {
transaFile = "chess.dat"; // default
}
if (args.length >= 2) {
minSup = (Double.valueOf(args[1]).doubleValue());
} else {
minSup = .8;
}
if (minSup > 1 || minSup < 0) {
throw new Exception("minSup: bad value");
}
numItems = 0;
numTransactions = 0;
BufferedReader data_in = new BufferedReader(new FileReader(transaFile));
while (data_in.ready()) {
String line = data_in.readLine();
if (line.matches("\\s*")) {
continue;
}
numTransactions++;
StringTokenizer t = new StringTokenizer(line, " ");
while (t.hasMoreTokens()) {
int x = Integer.parseInt(t.nextToken());
if (x + 1 > numItems) {
numItems = x + 1;
}
}
}
outputConfig();
}
private void outputConfig() {
log("Input configuration: " + numItems + " items, " + numTransactions + " transactions, ");
log("minsup = " + minSup + "%");
}
private void createItemsetsOfSize1() {
itemsets = new ArrayList<int[]>();
for (int i = 0; i < numItems; i++) {
int[] cand = {i};
itemsets.add(cand);
}
}
private void createNewItemsetsFromPreviousOnes() {
int currentSizeOfItemsets = itemsets.get(0).length;
log("Creating itemsets of size " + (currentSizeOfItemsets + 1) + " based on " + itemsets.size() + " itemsets of size " + currentSizeOfItemsets);
HashMap<String, int[]> tempCandidates = new HashMap<String, int[]>(); //temporary candidates
for (int i = 0; i < itemsets.size(); i++) {
for (int j = i + 1; j < itemsets.size(); j++) {
int[] X = itemsets.get(i);
int[] Y = itemsets.get(j);
assert (X.length == Y.length);
int[] newCand = new int[currentSizeOfItemsets + 1];
for (int s = 0; s < newCand.length - 1; s++) {
newCand[s] = X[s];
}
int ndifferent = 0;
for (int s1 = 0; s1 < Y.length; s1++) {
boolean found = false;
for (int s2 = 0; s2 < X.length; s2++) {
if (X[s2] == Y[s1]) {
found = true;
break;
}
}
if (!found) {
ndifferent++;
newCand[newCand.length - 1] = Y[s1];
}
}
assert (ndifferent > 0);
if (ndifferent == 1) {
Arrays.sort(newCand);
tempCandidates.put(Arrays.toString(newCand), newCand);
}
}
}
itemsets = new ArrayList<int[]>(tempCandidates.values());
log("Created " + itemsets.size() + " unique itemsets of size " + (currentSizeOfItemsets + 1));
}
private void line2booleanArray(String line, boolean[] trans) {
Arrays.fill(trans, false);
StringTokenizer stFile = new StringTokenizer(line, " ");
while (stFile.hasMoreTokens()) {
int parsedVal = Integer.parseInt(stFile.nextToken());
trans[parsedVal] = true;
}
}
private void calculateFrequentItemsets() throws Exception {
log("Passing through the data to compute the frequency of " + itemsets.size() + " itemsets of size " + itemsets.get(0).length);
List<int[]> frequentCandidates = new ArrayList<int[]>();
boolean match;
int count[] = new int[itemsets.size()];
BufferedReader data_in = new BufferedReader(new InputStreamReader(new FileInputStream(transaFile)));
boolean[] trans = new boolean[numItems];
for (int i = 0; i < numTransactions; i++) {
String line = data_in.readLine();
line2booleanArray(line, trans);
for (int c = 0; c < itemsets.size(); c++) {
match = true;
int[] cand = itemsets.get(c);
for (int xx : cand) {
if (trans[xx] == false) {
match = false;
break;
}
}
if (match) {
count[c]++;
}
}
}
data_in.close();
for (int i = 0; i < itemsets.size(); i++) {
if ((count[i] / (double) (numTransactions)) >= minSup) {
foundFrequentItemSet(itemsets.get(i), count[i]);
frequentCandidates.add(itemsets.get(i));
}
}
itemsets = frequentCandidates;
}
}

illegal start of expression error, working with methods

So I keep getting illegal start of expression errors around line 30 when trying to run my DiceGame program which is practice with methods. Here's my code:
import java.util.Scanner;
public class DiceGame
{
public static void main(String[] args)
{
final int RANGE = 6;
Scanner input = new Scanner(System.in);
int userGuess = input.next();
int throwResult = throw2Dice(RANGE);
int programGuess = throw2Dice(RANGE);
int userError = Math.abs(throwResult - userGuess);
int programError = Math.abs(throwResult - programGuess);
boolean userWins = false;
if(userError < programError)
{
userWins = true;
{
System.out.println("Your guess was: " + userGuess + " the program's guess was: " + programGuess + " and the result was: " + throwResult);
if(userWins == false)
System.out.println("Program Wins!!!");
else
System.out.println("User Wins!!!");
}
public static int throw2Dice(int r)
{
int number1 = (Math.random() * r + 1);
int number2 = (Math.random() * r + 1);
int sum = number1 + number2;
return sum;
}
}
if(userError < programError)
{
userWins = true;
{
You have two open braces instead of an open brace and a close brace.

Reverse the ordering of words in a string

I have this string s1 = "My name is X Y Z" and I want to reverse the order of the words so that s1 = "Z Y X is name My".
I can do it using an additional array. I thought hard but is it possible to do it inplace (without using additional data structures) and with the time complexity being O(n)?
Reverse the entire string, then reverse the letters of each individual word.
After the first pass the string will be
s1 = "Z Y X si eman yM"
and after the second pass it will be
s1 = "Z Y X is name My"
reverse the string and then, in a second pass, reverse each word...
in c#, completely in-place without additional arrays:
static char[] ReverseAllWords(char[] in_text)
{
int lindex = 0;
int rindex = in_text.Length - 1;
if (rindex > 1)
{
//reverse complete phrase
in_text = ReverseString(in_text, 0, rindex);
//reverse each word in resultant reversed phrase
for (rindex = 0; rindex <= in_text.Length; rindex++)
{
if (rindex == in_text.Length || in_text[rindex] == ' ')
{
in_text = ReverseString(in_text, lindex, rindex - 1);
lindex = rindex + 1;
}
}
}
return in_text;
}
static char[] ReverseString(char[] intext, int lindex, int rindex)
{
char tempc;
while (lindex < rindex)
{
tempc = intext[lindex];
intext[lindex++] = intext[rindex];
intext[rindex--] = tempc;
}
return intext;
}
Not exactly in place, but anyway: Python:
>>> a = "These pretzels are making me thirsty"
>>> " ".join(a.split()[::-1])
'thirsty me making are pretzels These'
In Smalltalk:
'These pretzels are making me thirsty' subStrings reduce: [:a :b| b, ' ', a]
I know noone cares about Smalltalk, but it's so beautiful to me.
You cannot do the reversal without at least some extra data structure. I think the smallest structure would be a single character as a buffer while you swap letters. It can still be considered "in place", but it's not completely "extra data structure free".
Below is code implementing what Bill the Lizard describes:
string words = "this is a test";
// Reverse the entire string
for(int i = 0; i < strlen(words) / 2; ++i) {
char temp = words[i];
words[i] = words[strlen(words) - i];
words[strlen(words) - i] = temp;
}
// Reverse each word
for(int i = 0; i < strlen(words); ++i) {
int wordstart = -1;
int wordend = -1;
if(words[i] != ' ') {
wordstart = i;
for(int j = wordstart; j < strlen(words); ++j) {
if(words[j] == ' ') {
wordend = j - 1;
break;
}
}
if(wordend == -1)
wordend = strlen(words);
for(int j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
char temp = words[j];
words[j] = words[wordend - (j - wordstart)];
words[wordend - (j - wordstart)] = temp;
}
i = wordend;
}
}
What language?
If PHP, you can explode on space, then pass the result to array_reverse.
If its not PHP, you'll have to do something slightly more complex like:
words = aString.split(" ");
for (i = 0; i < words.length; i++) {
words[i] = words[words.length-i];
}
public static String ReverseString(String str)
{
int word_length = 0;
String result = "";
for (int i=0; i<str.Length; i++)
{
if (str[i] == ' ')
{
result = " " + result;
word_length = 0;
} else
{
result = result.Insert(word_length, str[i].ToString());
word_length++;
}
}
return result;
}
This is C# code.
In Python...
ip = "My name is X Y Z"
words = ip.split()
words.reverse()
print ' '.join(words)
Anyway cookamunga provided good inline solution using python!
This is assuming all words are separated by spaces:
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "What are you looking at";
int i, n = strlen(string);
int tail = n-1;
for(i=n-1;i>=0;i--)
{
if(string[i] == ' ' || i == 0)
{
int cursor = (i==0? i: i+1);
while(cursor <= tail)
printf("%c", string[cursor++]);
printf(" ");
tail = i-1;
}
}
return 0;
}
class Program
{
static void Main(string[] args)
{
string s1 =" My Name varma:;
string[] arr = s1.Split(' ');
Array.Reverse(arr);
string str = string.Join(" ", arr);
Console.WriteLine(str);
Console.ReadLine();
}
}
This is not perfect but it works for me right now. I don't know if it has O(n) running time btw (still studying it ^^) but it uses one additional array to fulfill the task.
It is probably not the best answer to your problem because i use a dest string to save the reversed version instead of replacing each words in the source string. The problem is that i use a local stack variable named buf to copy all the words in and i can not copy but into the source string as this would lead to a crash if the source string is const char * type.
But it was my first attempt to write s.th. like this :) Ok enough blablub. here is code:
#include <iostream>
using namespace std;
void reverse(char *des, char * const s);
int main (int argc, const char * argv[])
{
char* s = (char*)"reservered. rights All Saints. The 2011 (c) Copyright 11/10/11 on Pfundstein Markus by Created";
char *x = (char*)"Dogfish! White-spotted Shark, Bullhead";
printf("Before: |%s|\n", x);
printf("Before: |%s|\n", s);
char *d = (char*)malloc((strlen(s)+1)*sizeof(char));
char *i = (char*)malloc((strlen(x)+1)*sizeof(char));
reverse(d,s);
reverse(i,x);
printf("After: |%s|\n", i);
printf("After: |%s|\n", d);
free (i);
free (d);
return 0;
}
void reverse(char *dest, char *const s) {
// create a temporary pointer
if (strlen(s)==0) return;
unsigned long offset = strlen(s)+1;
char *buf = (char*)malloc((offset)*sizeof(char));
memset(buf, 0, offset);
char *p;
// iterate from end to begin and count how much words we have
for (unsigned long i = offset; i != 0; i--) {
p = s+i;
// if we discover a whitespace we know that we have a whole word
if (*p == ' ' || *p == '\0') {
// we increment the counter
if (*p != '\0') {
// we write the word into the buffer
++p;
int d = (int)(strlen(p)-strlen(buf));
strncat(buf, p, d);
strcat(buf, " ");
}
}
}
// copy the last word
p -= 1;
int d = (int)(strlen(p)-strlen(buf));
strncat(buf, p, d);
strcat(buf, "\0");
// copy stuff to destination string
for (int i = 0; i < offset; ++i) {
*(dest+i)=*(buf+i);
}
free(buf);
}
We can insert the string in a stack and when we extract the words, they will be in reverse order.
void ReverseWords(char Arr[])
{
std::stack<std::string> s;
char *str;
int length = strlen(Arr);
str = new char[length+1];
std::string ReversedArr;
str = strtok(Arr," ");
while(str!= NULL)
{
s.push(str);
str = strtok(NULL," ");
}
while(!s.empty())
{
ReversedArr = s.top();
cout << " " << ReversedArr;
s.pop();
}
}
This quick program works..not checks the corner cases though.
#include <stdio.h>
#include <stdlib.h>
struct node
{
char word[50];
struct node *next;
};
struct stack
{
struct node *top;
};
void print (struct stack *stk);
void func (struct stack **stk, char *str);
main()
{
struct stack *stk = NULL;
char string[500] = "the sun is yellow and the sky is blue";
printf("\n%s\n", string);
func (&stk, string);
print (stk);
}
void func (struct stack **stk, char *str)
{
char *p1 = str;
struct node *new = NULL, *list = NULL;
int i, j;
if (*stk == NULL)
{
*stk = (struct stack*)malloc(sizeof(struct stack));
if (*stk == NULL)
printf("\n####### stack is not allocated #####\n");
(*stk)->top = NULL;
}
i = 0;
while (*(p1+i) != '\0')
{
if (*(p1+i) != ' ')
{
new = (struct node*)malloc(sizeof(struct node));
if (new == NULL)
printf("\n####### new is not allocated #####\n");
j = 0;
while (*(p1+i) != ' ' && *(p1+i) != '\0')
{
new->word[j] = *(p1 + i);
i++;
j++;
}
new->word[j++] = ' ';
new->word[j] = '\0';
new->next = (*stk)->top;
(*stk)->top = new;
}
i++;
}
}
void print (struct stack *stk)
{
struct node *tmp = stk->top;
int i;
while (tmp != NULL)
{
i = 0;
while (tmp->word[i] != '\0')
{
printf ("%c" , tmp->word[i]);
i++;
}
tmp = tmp->next;
}
printf("\n");
}
Most of these answers fail to account for leading and/or trailing spaces in the input string. Consider the case of str=" Hello world"... The simple algo of reversing the whole string and reversing individual words winds up flipping delimiters resulting in f(str) == "world Hello ".
The OP said "I want to reverse the order of the words" and did not mention that leading and trailing spaces should also be flipped! So, although there are a ton of answers already, I'll provide a [hopefully] more correct one in C++:
#include <string>
#include <algorithm>
void strReverseWords_inPlace(std::string &str)
{
const char delim = ' ';
std::string::iterator w_begin, w_end;
if (str.size() == 0)
return;
w_begin = str.begin();
w_end = str.begin();
while (w_begin != str.end()) {
if (w_end == str.end() || *w_end == delim) {
if (w_begin != w_end)
std::reverse(w_begin, w_end);
if (w_end == str.end())
break;
else
w_begin = ++w_end;
} else {
++w_end;
}
}
// instead of reversing str.begin() to str.end(), use two iterators that
// ...represent the *logical* begin and end, ignoring leading/traling delims
std::string::iterator str_begin = str.begin(), str_end = str.end();
while (str_begin != str_end && *str_begin == delim)
++str_begin;
--str_end;
while (str_end != str_begin && *str_end == delim)
--str_end;
++str_end;
std::reverse(str_begin, str_end);
}
My version of using stack:
public class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
String ns= s.trim();
Stack<Character> reverse = new Stack<Character>();
boolean hadspace=false;
//first pass
for (int i=0; i< ns.length();i++){
char c = ns.charAt(i);
if (c==' '){
if (!hadspace){
reverse.push(c);
hadspace=true;
}
}else{
hadspace=false;
reverse.push(c);
}
}
Stack<Character> t = new Stack<Character>();
while (!reverse.empty()){
char temp =reverse.pop();
if(temp==' '){
//get the stack content out append to StringBuilder
while (!t.empty()){
char c =t.pop();
sb.append(c);
}
sb.append(' ');
}else{
//push to stack
t.push(temp);
}
}
while (!t.empty()){
char c =t.pop();
sb.append(c);
}
return sb.toString();
}
}
Store Each word as a string in array then print from end
public void rev2() {
String str = "my name is ABCD";
String A[] = str.split(" ");
for (int i = A.length - 1; i >= 0; i--) {
if (i != 0) {
System.out.print(A[i] + " ");
} else {
System.out.print(A[i]);
}
}
}
In Python, if you can't use [::-1] or reversed(), here is the simple way:
def reverse(text):
r_text = text.split(" ")
res = []
for word in range(len(r_text) - 1, -1, -1):
res.append(r_text[word])
return " ".join(res)
print (reverse("Hello World"))
>> World Hello
[Finished in 0.1s]
Printing words in reverse order of a given statement using C#:
void ReverseWords(string str)
{
int j = 0;
for (int i = (str.Length - 1); i >= 0; i--)
{
if (str[i] == ' ' || i == 0)
{
j = i == 0 ? i : i + 1;
while (j < str.Length && str[j] != ' ')
Console.Write(str[j++]);
Console.Write(' ');
}
}
}
Here is the Java Implementation:
public static String reverseAllWords(String given_string)
{
if(given_string == null || given_string.isBlank())
return given_string;
char[] str = given_string.toCharArray();
int start = 0;
// Reverse the entire string
reverseString(str, start, given_string.length() - 1);
// Reverse the letters of each individual word
for(int end = 0; end <= given_string.length(); end++)
{
if(end == given_string.length() || str[end] == ' ')
{
reverseString(str, start, end-1);
start = end + 1;
}
}
return new String(str);
}
// In-place reverse string method
public static void reverseString(char[] str, int start, int end)
{
while(start < end)
{
char temp = str[start];
str[start++] = str[end];
str[end--] = temp;
}
}
Actually, the first answer:
words = aString.split(" ");
for (i = 0; i < words.length; i++) {
words[i] = words[words.length-i];
}
does not work because it undoes in the second half of the loop the work it did in the first half. So, i < words.length/2 would work, but a clearer example is this:
words = aString.split(" "); // make up a list
i = 0; j = words.length - 1; // find the first and last elements
while (i < j) {
temp = words[i]; words[i] = words[j]; words[j] = temp; //i.e. swap the elements
i++;
j--;
}
Note: I am not familiar with the PHP syntax, and I have guessed incrementer and decrementer syntax since it seems to be similar to Perl.
How about ...
var words = "My name is X Y Z";
var wr = String.Join( " ", words.Split(' ').Reverse().ToArray() );
I guess that's not in-line tho.
In c, this is how you might do it, O(N) and only using O(1) data structures (i.e. a char).
#include<stdio.h>
#include<stdlib.h>
main(){
char* a = malloc(1000);
fscanf(stdin, "%[^\0\n]", a);
int x = 0, y;
while(a[x]!='\0')
{
if (a[x]==' ' || a[x]=='\n')
{
x++;
}
else
{
y=x;
while(a[y]!='\0' && a[y]!=' ' && a[y]!='\n')
{
y++;
}
int z=y;
while(x<y)
{
y--;
char c=a[x];a[x]=a[y];a[y]=c;
x++;
}
x=z;
}
}
fprintf(stdout,a);
return 0;
}
It can be done more simple using sscanf:
void revertWords(char *s);
void revertString(char *s, int start, int n);
void revertWordsInString(char *s);
void revertString(char *s, int start, int end)
{
while(start<end)
{
char temp = s[start];
s[start] = s[end];
s[end]=temp;
start++;
end --;
}
}
void revertWords(char *s)
{
int start = 0;
char *temp = (char *)malloc(strlen(s) + 1);
int numCharacters = 0;
while(sscanf(&s[start], "%s", temp) !=EOF)
{
numCharacters = strlen(temp);
revertString(s, start, start+numCharacters -1);
start = start+numCharacters + 1;
if(s[start-1] == 0)
return;
}
free (temp);
}
void revertWordsInString(char *s)
{
revertString(s,0, strlen(s)-1);
revertWords(s);
}
int main()
{
char *s= new char [strlen("abc deff gh1 jkl")+1];
strcpy(s,"abc deff gh1 jkl");
revertWordsInString(s);
printf("%s",s);
return 0;
}
import java.util.Scanner;
public class revString {
static char[] str;
public static void main(String[] args) {
//Initialize string
//str = new char[] { 'h', 'e', 'l', 'l', 'o', ' ', 'a', ' ', 'w', 'o',
//'r', 'l', 'd' };
getInput();
// reverse entire string
reverse(0, str.length - 1);
// reverse the words (delimeted by space) back to normal
int i = 0, j = 0;
while (j < str.length) {
if (str[j] == ' ' || j == str.length - 1) {
int m = i;
int n;
//dont include space in the swap.
//(special case is end of line)
if (j == str.length - 1)
n = j;
else
n = j -1;
//reuse reverse
reverse(m, n);
i = j + 1;
}
j++;
}
displayArray();
}
private static void reverse(int i, int j) {
while (i < j) {
char temp;
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
private static void getInput() {
System.out.print("Enter string to reverse: ");
Scanner scan = new Scanner(System.in);
str = scan.nextLine().trim().toCharArray();
}
private static void displayArray() {
//Print the array
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]);
}
}
}
In Java using an additional String (with StringBuilder):
public static final String reverseWordsWithAdditionalStorage(String string) {
StringBuilder builder = new StringBuilder();
char c = 0;
int index = 0;
int last = string.length();
int length = string.length()-1;
StringBuilder temp = new StringBuilder();
for (int i=length; i>=0; i--) {
c = string.charAt(i);
if (c == SPACE || i==0) {
index = (i==0)?0:i+1;
temp.append(string.substring(index, last));
if (index!=0) temp.append(c);
builder.append(temp);
temp.delete(0, temp.length());
last = i;
}
}
return builder.toString();
}
In Java in-place:
public static final String reverseWordsInPlace(String string) {
char[] chars = string.toCharArray();
int lengthI = 0;
int lastI = 0;
int lengthJ = 0;
int lastJ = chars.length-1;
int i = 0;
char iChar = 0;
char jChar = 0;
while (i<chars.length && i<=lastJ) {
iChar = chars[i];
if (iChar == SPACE) {
lengthI = i-lastI;
for (int j=lastJ; j>=i; j--) {
jChar = chars[j];
if (jChar == SPACE) {
lengthJ = lastJ-j;
swapWords(lastI, i-1, j+1, lastJ, chars);
lastJ = lastJ-lengthI-1;
break;
}
}
lastI = lastI+lengthJ+1;
i = lastI;
} else {
i++;
}
}
return String.valueOf(chars);
}
private static final void swapWords(int startA, int endA, int startB, int endB, char[] array) {
int lengthA = endA-startA+1;
int lengthB = endB-startB+1;
int length = lengthA;
if (lengthA>lengthB) length = lengthB;
int indexA = 0;
int indexB = 0;
char c = 0;
for (int i=0; i<length; i++) {
indexA = startA+i;
indexB = startB+i;
c = array[indexB];
array[indexB] = array[indexA];
array[indexA] = c;
}
if (lengthB>lengthA) {
length = lengthB-lengthA;
int end = 0;
for (int i=0; i<length; i++) {
end = endB-((length-1)-i);
c = array[end];
shiftRight(endA+i,end,array);
array[endA+1+i] = c;
}
} else if (lengthA>lengthB) {
length = lengthA-lengthB;
for (int i=0; i<length; i++) {
c = array[endA];
shiftLeft(endA,endB,array);
array[endB+i] = c;
}
}
}
private static final void shiftRight(int start, int end, char[] array) {
for (int i=end; i>start; i--) {
array[i] = array[i-1];
}
}
private static final void shiftLeft(int start, int end, char[] array) {
for (int i=start; i<end; i++) {
array[i] = array[i+1];
}
}
Here is a C implementation that is doing the word reversing inlace, and it has O(n) complexity.
char* reverse(char *str, char wordend=0)
{
char c;
size_t len = 0;
if (wordend==0) {
len = strlen(str);
}
else {
for(size_t i=0;str[i]!=wordend && str[i]!=0;i++)
len = i+1;
}
for(size_t i=0;i<len/2;i++) {
c = str[i];
str[i] = str[len-i-1];
str[len-i-1] = c;
}
return str;
}
char* inplace_reverse_words(char *w)
{
reverse(w); // reverse all letters first
bool is_word_start = (w[0]!=0x20);
for(size_t i=0;i<strlen(w);i++){
if(w[i]!=0x20 && is_word_start) {
reverse(&w[i], 0x20); // reverse one word only
is_word_start = false;
}
if (!is_word_start && w[i]==0x20) // found new word
is_word_start = true;
}
return w;
}
c# solution to reverse words in a sentence
using System;
class helloworld {
public void ReverseString(String[] words) {
int end = words.Length-1;
for (int start = 0; start < end; start++) {
String tempc;
if (start < end ) {
tempc = words[start];
words[start] = words[end];
words[end--] = tempc;
}
}
foreach (String s1 in words) {
Console.Write("{0} ",s1);
}
}
}
class reverse {
static void Main() {
string s= "beauty lies in the heart of the peaople";
String[] sent_char=s.Split(' ');
helloworld h1 = new helloworld();
h1.ReverseString(sent_char);
}
}
output:
peaople the of heart the in lies beauty Press any key to continue . . .
Better version
Check my blog http://bamaracoulibaly.blogspot.co.uk/2012/04/19-reverse-order-of-words-in-text.html
public string reverseTheWords(string description)
{
if(!(string.IsNullOrEmpty(description)) && (description.IndexOf(" ") > 1))
{
string[] words= description.Split(' ');
Array.Reverse(words);
foreach (string word in words)
{
string phrase = string.Join(" ", words);
Console.WriteLine(phrase);
}
return phrase;
}
return description;
}
public class manip{
public static char[] rev(char[] a,int left,int right) {
char temp;
for (int i=0;i<(right - left)/2;i++) {
temp = a[i + left];
a[i + left] = a[right -i -1];
a[right -i -1] = temp;
}
return a;
}
public static void main(String[] args) throws IOException {
String s= "i think this works";
char[] str = s.toCharArray();
int i=0;
rev(str,i,s.length());
int j=0;
while(j < str.length) {
if (str[j] != ' ' && j != str.length -1) {
j++;
} else
{
if (j == (str.length -1)) {
j++;
}
rev(str,i,j);
i=j+1;
j=i;
}
}
System.out.println(str);
}
I know there are several correct answers. Here is the one in C that I came up with.
This is an implementation of the excepted answer. Time complexity is O(n) and no extra string is used.
#include<stdio.h>
char * strRev(char *str, char tok)
{
int len = 0, i;
char *temp = str;
char swap;
while(*temp != tok && *temp != '\0') {
len++; temp++;
}
len--;
for(i = 0; i < len/2; i++) {
swap = str[i];
str[i] = str[len - i];
str[len - i] = swap;
}
// Return pointer to the next token.
return str + len + 1;
}
int main(void)
{
char a[] = "Reverse this string.";
char *temp = a;
if (a == NULL)
return -1;
// Reverse whole string character by character.
strRev(a, '\0');
// Reverse every word in the string again.
while(1) {
temp = strRev(temp, ' ');
if (*temp == '\0')
break;
temp++;
}
printf("Reversed string: %s\n", a);
return 0;
}

Resources