Here is a short code below to count words and more, but I face a strange problem:
when I run it some words of the original string don’t appear on the screen!? How come?
Did I forgot something using splitTokens ?! Thanks a lot for your help in advance.
All the best,
L
IntDict counts;
String[] tokens;
void setup() {
size(1000, 1000);
background(0);
counts = new IntDict();
String[] lines = {
"If only you were paying a bit attention to me sometimes.",
"I am not just a care giver I also need soemone to hug me tenderly."
};
String alltext = join(lines, " ");
tokens = splitTokens(alltext, "\n\";.?!'():\n ");
for (int i = 0; i < tokens.length; i++) {
String word = tokens[i].toLowerCase();
if (counts.hasKey(word)) {
counts.increment(word);
} else {
counts.set(word, 1);
}
println(word);
}
String[] keys = counts.keyArray();
for (int i = 0; i < keys.length; i++) {
textSize(20);
float x = 50;
float y = 50 + 15 * i;
text(keys[i], x, y);
}
}
void draw() {}
What you're rendering on the screen is not the split tokens, it's only the unique words(counts' keys).
If you call printArray(tokens); you'll see in console that each word appears, including duplicates:
IntDict counts;
String [] tokens;
void setup() {
size(1000, 1000);
background(0);
counts = new IntDict();
String [] lines = {"If only you were paying a bit attention to me sometimes.",
"I am not just a care giver I also need soemone to hug me tenderly."};
String alltext = join(lines, " ");
tokens = splitTokens(alltext, "\n\";.?!'():\n ");
println("with duplicates");
printArray(tokens);
for (int i =0; i<tokens.length; i++) {
String word = tokens[i].toLowerCase();
if (counts.hasKey(word)) {
counts.increment(word);
println("\tfound duplicate", word);
} else {
counts.set(word, 1);
}
//println(word);
}
String []keys = counts.keyArray();
println("without duplicates");
printArray(keys);
for (int i=0; i<keys.length; i++) {
textSize(20);
float x = 50;
float y= 50+15*i;
text(keys[i], x, y);
}
}
void draw() {
}
If you want to render all the words simply iterate (and access) tokens instead of keys in the second for loop where you call text()
Related
If the given input is a1bc2def3 then output should be abcbcdefdefdef
Whenever the number comes then we should repeat previous substring that many number of times.
Please provide the algorithm or code to accomplish this.
Here's another approach that doesn't rely on regex.
public String splitRepeat(String str)
{
StringBuilder out = new StringBuilder();
boolean number = false;
for(int i=0,j=0,k=0; i<=str.length(); i++)
{
if(i==str.length() || Character.isDigit(str.charAt(i)) != number)
{
if(number)
{
for(int r = Integer.parseInt(str.substring(j, i)); r>0; r--)
{
out.append(str.substring(k, j));
}
}
else
{
k=j;
}
j=i;
number = !number;
}
}
return out.toString();
}
My suggestion would be:
Try using regex so you can get an array of numbers and characters,
then convert the number Parsable elements of the array into an integer,
after that loop with the index of the arrays to append n-times the characters of the array
then print the final result
Example:
public static void main(String[] args) {
String stringToProcess = "a1bc2def3";
String[] regexSplitted = stringToProcess.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
StringBuilder sb = new StringBuilder();
String appender = "";
for (int i = 0; i < regexSplitted.length; i++) {
try {
int kilo = Integer.parseInt(regexSplitted[i]);
for (int j = 0; j < kilo; j++) {
sb.append(appender).append(regexSplitted[i - 1]);
appender = "-";
}
} catch (NumberFormatException e) {
}
}
System.out.println(sb.toString());
}
this will print
a-bc-bc-def-def-def
that is pretty much what you are looking for.
I want to make a group of array fade out until the last array in this group was appended. for example, I use append to create zoog[0], zoog[1], zoog[2], and I want these three objects not fadeout until zoog[2] is created and wait for a second, the same situation with zoog[3], zoog[4],zoog[5], these three objects don't fadeout until zoog[5] is created. But now what I can do is make each object fadeout as soon as it is created.
Zoog[]zoog = new Zoog[1];
float count=0;
int xpos =0;
int ypos =0;
String message="haha";
int ntextsize = 20;
int nopacity =200;
int thistime = 0;
int thiscount = 0;
//Zoog zoog;
void setup() {
size(400, 400);
xpos = int(random(width/2-200, width/2+40));
ypos = int(random(height/2, height/2-40));
zoog[0] = new Zoog(xpos,ypos,message,nopacity);
}
void draw(){
background(255,255,255);
for(int i=0; i<zoog.length; i++){
// if(millis()-thistime>4000){
// zoog[i].disappear();
// }
zoog[i].jiggle();
zoog[i].display();
}
}
void mousePressed(){
count = count + 1;
// int thiscount = 0;
if(count%3 ==0){
xpos=int(random(30, width-30));
ypos=int(random(10, height-10));
}
else{
ypos = ypos+50;
// thiscount = thiscount +1;
// thistime = millis();
// }
}
nopacity = int(random(100,255));
// text(message, xpos, ypos);
Zoog b = new Zoog(xpos,ypos,message,nopacity);
zoog =(Zoog[]) append(zoog,b);
}
Zoog class
class Zoog {
int x;
int y;
String thatmessage;
int opaci =0;
Zoog(int xpo, int ypo, String thismessage, int opa) {
x = xpo;
y = ypo;
thatmessage = thismessage;
opaci = opa;
}
void jiggle() {
x = x+int(random(-2, 2));
y = y+int(random(-2, 2));
}
void display() {
fill(0, opaci);
text(thatmessage, x, y);
print("x position is "+ x);
print("y position is "+y);
}
void disappear() {
for (int j=0; j<255; j++) {
opaci = opaci -j;
}
}
}
If I understand correctly you want to make 3 zoogs and then start fading those three out until they're gone. If this is correct there are a couple of ways I'd go about doing this.
First, I wouldn't use an array especially if you're dynamically updating the amount inside it. If you want to do that I'd use, arraylists. Here's the javadocs reference. Basically you'd initialize an arraylist of Zoogs and put the zoog.add(new Zoog...) in the mousepressed. The good thing about arraylists is that they have a number of member functions that can help you manipulate them. For instance, you can check the size of the arraylist in your draw function instead of the time. Once you're above 3 start fading the first 3 out until they're dead (using a Zoog member function to say they're dead). You can check that "isDead" member function in your draw loop and remove the correct dead Zoog while in your for loop.
Here's a rough implementation, assuming you created an isDead function in your Zoog class that just returns whether the opacity is greater than 0:
void Draw()
{
for (Zoog zoog : zoogs) //for each statement simplifying the code -
//says for each Zoog in zoogs do
{
zoog.jiggle();
zoog.display();
}
if(zoogs.size() >= 3) {
for(int i = 0; i < 3; i++) {
zoogs.get(i).disappear();
}
}
if (zoogs.get(0).isDead() && zoogs.get(1).isDead() && zoogs.get(2).isDead()) {
zoogs.remove(2);
zoogs.remove(1);
zoogs.remove(0);
}
}
This is by no means a perfect example but it shows how to remove 3 zoogs at a time by lessening their opacity and checking whether they are dead. If you're clicking a million times then it will take a while for each chain of three to die.
I'm missing something fundamental here but I can't seem to find out what from all my research.
I have imported a csv file, split the string into floats, and now wish to connect all points to all other points with a line. My code is as follows:
String [] data;
void setup () {
size(300, 300);
background(255);
data = loadStrings("points.csv");
for (int i = 0; i < data.length; i++) {
String [] fields = split(data[i], ',');
float t = float(fields[0]);
float n = float(fields[1]);
float x = float(fields[2]);
float y = float(fields[3]);
ellipse(x, y, 10, 10);
line(x, y, x[i], y[i]);
}
}
The error message is "The type of expression must be an array type but it resolved to float"
I'm sure this is extremely basic but, I dont understand why x[i] or y[i] are not seen as an array type.
I would really appreciate any help with this. Many thanks in advance.
Sam
*UPDATE***
An exract from the points.csv file is as follows:
219185750 rabih_takkoush 20.88521 19.49821
219185716 MoustaphaAjram 100.870896 59.515259
219185709 jinanejghosh 56.886441 35.489087
219185557 MoustaphaAjram 34.870904 78.515243
219185555 Mohammad8Itani 12.8946 49.48179
What I am trying to accomplish is plotting the various geolocations (whereby col 3 = x, col 4 = y) and then connecting all points with all other points with a line.
The following script works plotting all locations specified in the array within the script:
float[] x = { 50, 100, 150, 200,20,20 };
float[] y = { 10, 30, 20, 250,20,90 };
void setup () {
size(300, 300);
background(255);
}
void draw() {
for (int i = 0; i < x.length; i++) {
ellipse(x[i], y[i], 10, 10);
for (int j = 0; j < x.length; j++) {
line(x[j], y[j], x[i], y[i]);
}
}
}
What I wish to do is do the same, but reading columns 3 and 4 of the csv file.
You're splitting your data into iteration-scoped floats, then you try to access them as if they're both floats as well as arrays in your line() call. Try this:
String[] data;
float[] x, y, t, n;
void setup () {
size(300, 300);
data = loadStrings("points.csv");
int len = data.length;
x = new float[len];
x = new float[len];
t = new float[len];
n = new float[len];
for (int i=0; i<len; i++) {
String line = data[i];
String[] fields = split(line, ',');
t[i] = float(fields[0]),
n[i] = float(fields[1]),
x[i] = float(fields[2]),
y[i] = float(fields[3]);
}
// don't put draw instructions in setup,
// put them in draw. if you want to run once,
// issue a noLoop() so that happens.
noLoop();
}
void draw() {
float prevx = x[0], prevy = y[0];
for (int i=0, last=x.length; i<last; i++) {
ellipse(x[i], y[i], 10, 10);
line(prevx,prevy, x[i],y[i]);
prevx=x[i];
prevy=y[i];
}
}
Now we're storing the data from CVS in linked arrays that we can access throughout the sketch, rather than throwing them away after setup().
ok so if you go with the first code you made, you only need to change a few things, here is what you can do:
float[] x;
float[] y;
string[] data;
void setup () {
size(300, 300);
background(255);
data = loadStrings("points.csv");
x = new float[data.length];
y = new float[data.length];
for (int i = 0; i < data.length; i++) {
String [] fields = split(data[i], ',');
float t = float(fields[0]);
float n = float(fields[1]);
float x = float(fields[2]);
float y = float(fields[3]);
}
}
void draw() {
for (int i = 0; i < x.length; i++) {
ellipse(x[i], y[i], 10, 10);
for (int j = 0; j < x.length; j++) {
line(x[j], y[j], x[i], y[i]);
}
}
}
As you can see nothing really new, it's a mix between your initial code and the one you made for the csv.
And actually you mainly needed to declare your x and y variables as float[] instead of just float. But also there were some changes to make in the loop.
In this code you load the data in your arrays first (exactly like you did by declaring array's values in your code, but this time you read these values from your file), and then call your draw method as before.
hope it works now
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
void getstring(char str1[],char str2[],char hash[])
{
int len=strlen(str1);
int i=0,j; //i keeps the previous index
int min=INT_MAX;
int cnt=0;
for(j=0;j<len;j++)
{
if(hash[str1[j]]==-1) //means uninitialized, will be checked for first time only
{
cnt++;
hash[str1[j]]=j;
if(cnt==1)
i=j;
int y=check(hash,str2); //checking for the characters
//printf("y=%d",y);
if(y) //means all the characters are present
{
if( (j-i+1)<min)
{
min=j-i+1;
I=i;
J=j;
}
}
}
else if(hash[str1[j]]>=0)
{
hash[str1[j]]=j;
if(check(hash,str2) )
{
if( hash[str1[i]]==hash[str1[j]] ) //it means that we are moving the first
{ //index only
i=getmin(hash,str2); //get minimum index of the element
if( (j-i+1)<min)
{
min=j-i+1;
I=i;
J=j;
}
}
//else
}
else
{
if( hash[str1[i]]==hash[str1[j]] )
i=hash[str1[i]];
}
}//end of else-if
}//end of for
}
I have made the code for it using hash i.e. i am keeping the index values of the characters of the string T in the hash and using two indexes, as soon as i get any character ahead same as the character at the lower index, i first check the length and then updates the index.
This approach would take O(nk) in worst case.
n - is the number of characters in S
k - is the number of characters in T
Is there any approach which will take O(n) time for this problem?
So make a pass of S keeping track of when you last saw each letter in T.
At each point the farthest of the last seen letters will delimit the left edge of a window (with the current point being the right edge).
Of these windows, simply keep track of the smallest one seen so far. At the end of the algorithm this will be the smallest window overall.
Here is my java code which has passed all the test cases. I hope it might help you as well.
public class Solution {
public String minWindow(String s, String t) {
if(t.length()>s.length())
return "";
String result = "";
HashMap <Character, Integer> shouldFind = new HashMap<Character, Integer>();
HashMap <Character, Integer> hasFound = new HashMap<Character, Integer>();
int count =0, j=0, minWindow = s.length()+1, start=0, finish =0;
Integer sLength = s.length();
Integer tLength = t.length();
for(int i = 0 ; i < tLength ; i++)
{
char tChar = t.charAt(i);
if(!shouldFind.containsKey(tChar))
shouldFind.put(tChar,1);
else
shouldFind.put (tChar ,shouldFind.get(tChar)+1);
}
for (int i =0; i <sLength; i ++)
{
char sChar = s.charAt(i);
if(shouldFind.containsKey(sChar))
{
if(!hasFound.containsKey(sChar)){
hasFound.put(sChar, 1);
count++;
}
else {
if(hasFound.get(sChar) < shouldFind.get(sChar) )
count ++;
hasFound.put(sChar, hasFound.get(sChar) +1);
}
}
if(count == tLength)
{
char ch = s.charAt(j);
while (!hasFound.containsKey(ch) || hasFound.get(ch) > shouldFind.get(ch))
{
if(hasFound.containsKey(ch) && hasFound.get(ch)>shouldFind.get(ch))
hasFound.put(ch , hasFound.get(ch) -1);
j++;
ch = s.charAt(j);
}
//lets find the minimum window
if(minWindow > (i-j+1) )
{
minWindow = i - j + 1;
start = j;
finish = i+1;
result = s.substring(start, finish);
}
}}
return result;
}}
I have been playing around with programming for arduino but today i've come across a problem that i can't solve with my very limited C knowledge.
Here's how it goes.
I'm creating a pc application that sends serial input to the arduino (deviceID, command, commandparameters). This arduino will transmit that command over RF to other arduino's. depending on the deviceID the correct arduino will perform the command.
To be able to determine the deviceID i want to split that string on the ",".
this is my problem, i know how to do this easily in java (even by not using the standard split function), however in C it's a totally different story.
Can any of you guys tell me how to get this working?
thanks
/*
Serial Event example
When new serial data arrives, this sketch adds it to a String.
When a newline is received, the loop prints the string and
clears it.
A good test for this is to try it with a GPS receiver
that sends out NMEA 0183 sentences.
Created 9 May 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/SerialEvent
*/
String inputString; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
String[] receivedData;
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
if (inChar == '\n') {
stringComplete = true;
}
// add it to the inputString:
if(stringComplete == false) {
inputString += inChar;
}
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
}
}
String[] splitCommand(String text, char splitChar) {
int splitCount = countSplitCharacters(text, splitChar);
String returnValue[splitCount];
int index = -1;
int index2;
for(int i = 0; i < splitCount - 1; i++) {
index = text.indexOf(splitChar, index + 1);
index2 = text.indexOf(splitChar, index + 1);
if(index2 < 0) index2 = text.length() - 1;
returnValue[i] = text.substring(index, index2);
}
return returnValue;
}
int countSplitCharacters(String text, char splitChar) {
int returnValue = 0;
int index = -1;
while (index > -1) {
index = text.indexOf(splitChar, index + 1);
if(index > -1) returnValue+=1;
}
return returnValue;
}
I have decided I'm going to use the strtok function.
I'm running into another problem now. The error happened is
SerialEvent.cpp: In function 'void splitCommand(String, char)':
SerialEvent:68: error: cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'
SerialEvent:68: error: 'null' was not declared in this scope
Code is like,
String inputString; // a string to hold incoming data
void splitCommand(String text, char splitChar) {
String temp;
int index = -1;
int index2;
for(temp = strtok(text, splitChar); temp; temp = strtok(null, splitChar)) {
Serial.println(temp);
}
for(int i = 0; i < 3; i++) {
Serial.println(command[i]);
}
}
This is an old question, but i have created some piece of code that may help:
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
This function returns a single string separated by a predefined character at a given index. For example:
String split = "hi this is a split test";
String word3 = getValue(split, ' ', 2);
Serial.println(word3);
Should print 'is'. You also can try with index 0 returning 'hi' or safely trying index 5 returning 'test'.
Hope this help!
Implementation:
int sa[4], r=0, t=0;
String oneLine = "123;456;789;999;";
for (int i=0; i < oneLine.length(); i++)
{
if(oneLine.charAt(i) == ';')
{
sa[t] = oneLine.substring(r, i).toInt();
r=(i+1);
t++;
}
}
Result:
// sa[0] = 123
// sa[1] = 456
// sa[2] = 789
// sa[3] = 999
For dynamic allocation of memory, you will need to use malloc, ie:
String returnvalue[splitcount];
for(int i=0; i< splitcount; i++)
{
String returnvalue[i] = malloc(maxsizeofstring * sizeof(char));
}
You will also need the maximum string length.
The C way to split a string based on a delimiter is to use strtok (or strtok_r).
See also this question.
I think your idea is a good start point. Here is a code that i use (to parse HTTP GET REST requests with an Ethernet shield).
The idea is to use a while loop and lastIndexOf of and store the strings into an array (but your could do something else).
"request" is the string you want to parse (for me it was called request because.. it was).
int goOn = 1;
int count = -1;
int pos1;
int pos2 = request.length();
while( goOn == 1 ) {
pos1 = request.lastIndexOf("/", pos2);
pos2 = request.lastIndexOf("/", pos1 - 1);
if( pos2 <= 0 ) goOn = 0;
String tmp = request.substring(pos2 + 1, pos1);
count++;
params[count] = tmp;
// Serial.println( params[count] );
if( goOn != 1) break;
}
// At the end you can know how many items the array will have: count + 1 !
I have used this code successfully, but i thing their is an encoding problem when i try to print params[x]... i'm alos a beginner so i don't master chars vs string...
Hope it helps.
I believe this is the most straight forward and quickest way:
String strings[10]; // Max amount of strings anticipated
void setup() {
Serial.begin(9600);
int count = split("L,-1,0,1023,0", ',');
for (int j = 0; j < count; ++j)
{
if (strings[j].length() > 0)
Serial.println(strings[j]);
}
}
void loop() {
delay(1000);
}
// string: string to parse
// c: delimiter
// returns number of items parsed
int split(String string, char c)
{
String data = "";
int bufferIndex = 0;
for (int i = 0; i < string.length(); ++i)
{
char c = string[i];
if (c != ',')
{
data += c;
}
else
{
data += '\0';
strings[bufferIndex++] = data;
data = "";
}
}
return bufferIndex;
}