Work only on Processing app.
Download Link : https://processing.org/download/
void setup()
{
String s="Hello World";
int count=count_word(s);
println("Sentence : "+s);
println("Number of words : "+count);
}
int count_word(String s)
{
if(s.length()==0)
{
return 0;
}
int c=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)==' '||s.charAt(i)=='.'||s.charAt(i)=='?')
{
c++;
}
}
if(s.charAt(s.length()-1)!=' '&&s.charAt(s.length()-1)!='.'&&s.charAt(s.length()-1)!='?')
{
c++;
}
return c;
}
วันจันทร์ที่ 29 กันยายน พ.ศ. 2557
วันอาทิตย์ที่ 28 กันยายน พ.ศ. 2557
Lab 3[continue] : Task#3 - write a function to create random values in an array (with parameter to specify whether duplicate values are allowed)
boolean d=false;
int n=10;
void setup()
{
int[] x=new int[n];
for(int i=0;i<n;i++)
{x[i]=-1;}
for(int i=0;i<n;i++)
{x[i]=random_array(x);}
for(int i=0;i<n;i++)
{println("x["+i+"] = "+x[i]);}
}
int random_array(int[] x)
{
int y;
y=round(random(0,n));
if(!d)
{
for(int i=0;i<n;i++)
{
if(y==x[i])
{
y=random_array(x);
}
}
}
return y;
}
Lab 3[continue] : Task#2 - Write a function to create random values in an array (duplicate values are allowed)
int n=10;
void setup()
{
int[] x=new int[n];
for(int i=0;i<n;i++)
{x[i]=-1;}
for(int i=0;i<n;i++)
{x[i]=random_array(x);}
for(int i=0;i<n;i++)
{println("x["+i+"] = "+x[i]);}
}
int random_array(int[] x)
{
int y;
y=round(random(0,n));
return y;
}
Lab 3[continue] : Task#1 - Find the index of a value in an array
void setup()
{
int[] x={4,8,5};
int value,pos;
value=5;
pos=find_index(x,value);
print_index(x,value,pos);
}
int find_index(int[] x,int value)
{
int pos=-1;
for(int i=0;i<x.length;i++)
{
if(x[i]==value)
{
pos=i;
}
}
return pos;
}
void print_index(int[] x,int value, int pos)
{
print("X = {");
for(int i=0;i<x.length;i++)
{
print(x[i]);
if(i<x.length-1)
{
print(",");
}
else
{
println("}");
}
}
if(pos==-1)
{
print(value+" is not in X[]");
}
else
{
print(value+" has index = "+pos+" in X");
}
}
สมัครสมาชิก:
บทความ (Atom)