int sumOfDigits(int n)
{
if(n<=9)
return n;
else
{
int r=0;
while(n!=0)
{
r=r+n%10;
n=n/10;
}
sumOfDigits(r);
}
}
This function finds sum of digits of a number till it becomes less than 10.
e.g.if n=12345
then output=6
as 1+2+3+4+5=15,
again 1+5=6.
I guess what you try to achieve is something like this:
class St2 {
static int sumOfDigits(int n) {
if(n<=9) {
return n;
}
else {
int d = n%10;
return d + sumOfDigits((n-d)/10);
}
}
public static void main(String[] args) {
System.out.println(St2.sumOfDigits(345678));
}
}
This would sum the digits. The complexity is linear in the number of digits thus logarithmic in the scale of the input number.
Related
Beginner here. This piece of code converts number into roman numerals in multiples of 50 if not 10 if not 9 and down to 0. Methods are so intertwined. Is there something (just at a glance) you could suggest I should avoid doing? Thank You.
public static void main(String[] args) {
System.out.println(fiftyAndAbove(37));
}
public static String nineAndDown(int number) {
String one = "I", five = "V", ten = "X", sum = "";
if(number == 5) {
return five;
} else if(number == 9) {
return one + ten;
}
else if(number > 5) {
for(int i=1; i<=number-5; i++) {
sum += one;
}
return five + sum;
} else {
if(number == 4 ) {
return one + five;
} else
for(int i=1; i <=number; i++) {
sum += one;
}
} return sum;
}
public static String tenAndAbove(int number) {
int remainder = number % 10, numberOftens = number/10;
String ten = "X", sum = "";
if(numberOftens > 0) {
while(numberOftens > 0) {
sum += ten;
numberOftens -= 1;
}
}
return sum + nineAndDown(remainder);
}
public static String fiftyAndAbove(int number) {
int remainder = number % 50, numberOfFifty = number/50;
String fifty = "L", sum = "";
if(numberOfFifty > 0) {
while(numberOfFifty > 0) {
sum += fifty;
numberOfFifty -= 1;
}
}
return sum + tenAndAbove(remainder);
}
Is there something (just at a glance) you could suggest I should avoid doing?
I'd not unnecessarily complicate the logic as with
if(numberOfFifty > 0) {
while(numberOfFifty > 0) {
…
}
}
which is equivalent to
while (numberOfFifty > 0)
{
…
}
You could also have a look at this implementation and see what you prefer:
import java.util.Arrays;
…
public static String fiftyAndAbove(int number)
{
int remainder = number%50, numberOfFifty = number/50;
char [] Ls = new char [numberOfFifty];
Arrays.fill(Ls, 'L');
return new String(Ls) + tenAndAbove(remainder);
}
You have four places like this in your program where you need a string of a character repeated. If you're willing to require a certain Java version or above, you can also use one of the methods described at Java: String - add character n-times; otherwise I'd suggest to use a function to do it.
You could also think about whether you find
String one = "I", five = "V", ten = "X", sum = "";
if(number == 5) {
return five;
} else if(number == 9) {
return one + ten;
}
really better than
if (number == 5) return "V";
if (number == 9) return "IX";
Below is a Sudoku initializer, I am attempting to create a function that based on User input, erases a random element from the the board. The random element can be removed from any part of the board.
class cell{
bool m_occu; //occupied is shown '.'
int m_num;
public:
cell() : m_occu(false), m_num(0) {}
void setMark(const int num){m_num = num; m_occu = true;}
bool isMarked() const { return m_occu; }
int getNum(){ return m_num;}
friend ostream& operator << (ostream& o, const cell& c){
if (!c.m_occu) return o << setw(2) << '-';
return o << setw(2) << c.m_num;
}
};
class board {
vector<vector <cell> >m_map;
bool col_row;
public:
board() {
vector<cell> a_row(9);
col_row = false;
for (int i = 0; i < 9; ++i)
{
for(int j = 0; j < 9; j++)
{
a_row[j].setMark(j+1);
}
random_shuffle(a_row.begin(), a_row.end());
m_map.push_back(a_row);
}
}
void erase(){
}
Here is the code for erase function:
void erase(std::vector your_vector){
your_vector.erase(your_vector.begin() + random(1,your_vector.size()));
}
and this the code for random number generation:
int random(int min, int max) //range(min, max)
{
bool first = true;
if ( first )
{
srand(time(NULL)); //seeding only for the first time
first = false;
}
return min + rand() % (max - min);
}
Is there an event in 1.7.10 for when a block is generated, so i can place something above it. Or do i have to do that within the generation?
I already have looked online but i could not find an
onBlockGenerated
event or something like that.
You need to extend WorldGenerator
class Foo extends WorldGenerator {
protected Block[] GetValidSpawnBlocks() {
return new Block[] { Blocks.quartz };
}
public boolean generate(final World world, final Random rand, final int x, final int y, final int z) {
world.setBlock(x,y+1,z,FooModBlocks.yourFancyBlock,0,2);
}
}
And register it in your iworldgenerator
public class MagicCookieWorldGen implements IWorldGenerator {
private Foo myGenerator;
public MagicCookieWorldGen() {
super();
myGenerator = new Foo();
}
#Override
public void generate(Random random, int chunkX, int chunkZ, World world,
IChunkProvider chunkGenerator, IChunkProvider chunkProvider) {
this.worldGeneration(random, chunkX, chunkZ, world, true);
}
public void worldGeneration(final Random random, final int chunkX, final int chunkZ, final World world, final boolean newGen) {
switch (world.provider.dimensionId) {
case -1: {
this.generateNether(world, random, chunkX, chunkZ, newGen);
break;
}
case 1: {
break;
}
default: {
break;
}
}
}
private void generateNether(final World world, final Random random, final int chunkX, final int chunkZ, final boolean newGen) {
int startX = chunkX * 16;
int startZ = chunkZ * 16;
int startY = 5;
int endX = startX + 16;
int endZ = startZ + 16;
int endY = 65;
for(int x=startX;x<endX;x++)for(int z=startZ;z<endZ;z++)for(int y = startY;y<endY;y++) {
Block block = world.getBlock(x,y,z);
for(Block match : Foo.GetValidSpawnBlocks()) {
if(match == block) {
Foo.generate(world, final Random random, x, y, z);
break;
}
}
}
}
}
Then in your commonproxy in the init phase
GameRegistry.registerWorldGenerator((IWorldGenerator)(StuffLoader.worldGenerator = new MagicCookieWorldGen()), 0);
MagicCookie.log.info("Registered worldgenerator" + StuffLoader.worldGenerator);
I wonder how I can address a variable by putting together a string and an int in Arduino.
I´m using many variables of the same type and with almost the same name. I´m just append a number to each variable.
The names of the variables are e.g. int sensorValue_1; int sensorValue_2; and so on.
I´d like to write less because my code is becoming too long.
When addressing the variables, I´d like to write something like this: sensorValue_[+ intVariable];
Here is an example of what I mean:
int sensorIndex_1 = 1;
int sensorIndex_2 = 2;
int sensorIndex_3 = 3;
int sensorValue_1;
int sensorValue_2;
int sensorValue_3;
void setup()
{
Serial.begin(9600);
}
void loop()
{
doSomething(sensorIndex_1);
//doSomething(sensorIndex_2);
//doSomething(sensorIndex_3);
}
void doSomething(int sensorIndex)
{
if(sensorIndex == 1)
{
Serial.print("Sensor 1: ");
sensorValue_1 = analogRead(A1);
Serial.println(sensorValue_1);
}
if(sensorIndex == 2)
{
Serial.print("Sensor 2: ");
sensorValue_2 = analogRead(A2);
Serial.println(sensorValue_2);
}
if(sensorIndex == 3)
{
Serial.print("Sensor 3: ");
sensorValue_3 = analogRead(A3);
Serial.println(sensorValue_3);
}
delay(1000);
}
And I want to shorten the code in the doSomething() method.
I want to have something like this:
Notice the "[+ sensorIndex]"
void doSomething(int sensorIndex)
{
Serial.print("Sensor [+ sensorIndex]: ");
sensorValue_[+ sensorIndex] = analogRead(A[+ sensorIndex]);
Serial.println(sensorValue_[+ sensorIndex]);
delay(1000);
}
By the way: I´d like to avoid for-loops, if possible.
In my case, the code would become too complicated.
How do I manage this?
User2461391 has a great start but the rest of the puzzle I think you want is:
int array1[3];
int array2[3];
int arrayx[3];
void setup()
{
}
void loop()
{
int index=1;
array1[2]=doSomething(2);
arrayx[index]=doSomething(index);
Serial.print("Sensor ");
Serial.print(index);
Serial.print(": ");
Serial.println(arrayx[index]);
while(1);
}
int doSomething(int sensorIndex) // It probably makes more sense to return the value
{
return (analogRead(sensorIndex));
}
You don't need to use A1 and A2 and the likes to define the analog pin you want to read. Just 1 or 2 will do.
void doSomething(int sensorIndex)
{
Serial.print("Sensor ");
Serial.print(sensorIndex);
Serial.print(": ");
sensorValue = analogRead(sensorIndex);
Serial.println(sensorValue);
delay(1000);
}
i would like to assign my array vals to properties of my object.
like:
For i = 1 To 32
myClass.Prop_i = val[i]
Next
VB.NET isn't a dynamic language: you can't do such things.
Since VB.NET doesn't have a "dynamic" keyword like C#, your option is reflection:
myClass.GetType().GetProperty("Prop_" + i.ToString()).SetValue(myClass, val[i], null);
But if you're more explicit with your problem maybe there's a more elegant solution than reflection ;)
Your property needs to define Set. This will allow you to modify the property.
If you are willing to write some code in C# and use it in VB.NET, and need to store primitive types like int, float or byte, and all your properties are of the same type. Then you can create a union structure with an array covering the fields.
Then you can use code like this:
Sub Main() ' vb.net
Dim bag As New PropertyBag()
bag.AllProperties = New Single() {1, 2, 3, 4, 5, 6, 7, 8}
Dim three As Single = bag.Prop_3 'returns 3
Dim five As Single = bag(4) 'returns 5 (0-based index)
End Sub
When declared like
[StructLayout(LayoutKind.Explicit, Size=Size)]
public unsafe struct PropertyBag
{
const int Count = 8; //8 fields
const int Size = 8 * 4; //4 bytes per field
[FieldOffset(0)]
fixed float list[Count];
[FieldOffset(0)] float x1;
[FieldOffset(4)] float x2;
[FieldOffset(8)] float x3;
[FieldOffset(12)] float x4;
[FieldOffset(16)] float x5;
[FieldOffset(20)] float x6;
[FieldOffset(24)] float x7;
[FieldOffset(28)] float x8;
public float Prop_1 { get { return x1; } set { x1 = value; } }
public float Prop_2 { get { return x2; } set { x2 = value; } }
public float Prop_3 { get { return x3; } set { x3 = value; } }
public float Prop_4 { get { return x4; } set { x4 = value; } }
public float Prop_5 { get { return x5; } set { x5 = value; } }
public float Prop_6 { get { return x6; } set { x6 = value; } }
public float Prop_7 { get { return x7; } set { x7 = value; } }
public float Prop_8 { get { return x8; } set { x8 = value; } }
public float this[int index]
{
get
{
fixed (float* ptr = list)
{
return ptr[index];
}
}
set
{
fixed (float* ptr = list)
{
ptr[index] = value;
}
}
}
public float[] AllProperties
{
get
{
float[] res = new float[Count];
fixed (float* ptr = list)
{
for (int i = 0; i < Count; i++)
{
res[i] = ptr[i];
}
}
return res;
}
set
{
fixed (float* ptr = list)
{
for (int i = 0; i < Count; i++)
{
ptr[i] = value[i];
}
}
}
}
}
Note that reflection should work in your case (like others have answered), but this is just a different approach to the problem (and a very fast one too). The main limitation is what types can be made into pointers in C# (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool)