making function is number is odd or even - function

I want to make a function to find a number is odd or even by using only increment or decrement function . no another operator like equal or modular operator

def isOdd(n:Int) = {
if(n <= 1) n;
else isOdd(n - 2);
}
this will return 1 or 0 (true or false) whether or not the number n is odd.
I forgot to mention that this code is runnable in Scala.
It's tail-recursive, too.

check something like this with % mod operator
using System;
class Program
{
static void Main()
{
for (int i = 0; i <= 100; i++)
{
if (IsOdd(i))
{
Console.WriteLine(i);
}
}
}
public static bool IsOdd(int value)
{
return value % 2 != 0;
}
}

Maybe something like this? This solution however does use assignment and logical operators.
var isEven = true;
function makeDivayanshusHomework (number) {
if (number < 0) {
for(i = 0; i < 2*number; i++) {
number++;
}
}
while (number > 0) {
number--;
isEven = isEven ? false : true;
}
return isEven;
}
edit: as per sascha10000's comments, the solution below is perhaps even somewhat more functional:
function makeDivayanshusHomework (number) {
if (Math.sqrt(number*number) > 1) {
return makeDivayanshusHomework(number-2)
}
else {
return Math.sqrt(number*number); // 1 when odd, 0 otherwise
}
}
which brings me almost to sascha10000's original answer, although this method gracefully handles negative integers. Did your teacher specify to what extent the input has to be sanitised?

perhaps
public bool isEven(int number){
return number/2.0 == Convert.ToInt32(number/2.0)
}
I'm not quite sure how you intend to test a number for being even without an equals or mod operator.
Lucas

Related

element.length not working when using generics

My problem is this. I am passing arguments to a function that uses generics. For example I am passing element. I need to use element.length in the function but it gives me this error:
The property 'length' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!'). dartunchecked_use_of_nullable_value
void main(List<String> args) {
const List keyList = ['asd', 3, 'tyu', 67];
const List valueList = ['dfg', 'ert', 4, 'lkj'];
print(myMap(keyList, valueList));
}
Map myMap<K, V>(K key, V val) {
final Map<K, V> myMap = {};
for (int i = 0; i < key.length; i++) {
myMap[key[i]] = val[i];
}
return myMap;
}
I don't know if null aware operators can be used here, or if they solve the problem and how to use it.
You defined your generic types, but your parameters are lists of that type. You did not make this clear to your compiler. For your compiler, K is now of type List<dynamic> while what you wanted it to be is just dynamic.
Changing it to make it fit (my guess of) your requirements:
Map<K, V> myMap<K, V>(List<K> keys, List<V> values) {
final result = <K, V>{};
for (int i = 0; i < keys.length; i++) {
result[keys[i]] = values[i];
}
return result;
}
Please note that you are reinventing the wheel here. There already is a constructor that does this:
void main(List<String> args) {
const List keyList = ['asd', 3, 'tyu', 67];
const List valueList = ['dfg', 'ert', 4, 'lkj'];
print(Map.fromIterables(keyList, valueList));
}

How to adress elements of a recursive function?

Take a recursive function, say:
public static long rekurs(long n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return 1;
} else {
return rekurs(n - 1)*(rekurs(n - 2)+4;
}
}
When n=20, the function has to find all the values S(n) for n=2,...,19 first.
When I let n go from 20 to 21, it does the same thing again (plus finding S(20)).
Now I want to create an array, in which the found values S(n) for n=2,...,19 are filled into, so that the function for n=21 does not have to do the same thing again, but how do I get those elements?
This is the solution I figured out, it's a little bit different from the lecture example.
The keyword that helped me is "dynamic programming".
import java.util.Arrays;
public class Bsp13 {
public static final int N = 0;
public static final int Ende = 20;
public static long[] schroe = new long[N + Ende + 1];
public static void main(String[] args) {
schroe[0] = 1;
schroe[1] = 1;
for (int n = 2; n <= Ende + N; n++) {
schroe[n] = ((6 * n - 3) * (schroe[n-1]) - (n - 2) * (schroe[n-2])) / (n + 1);
}
System.out.println(schroe[N]);
System.out.println(Arrays.toString(schroe));
System.out.println(schroe[N+Ende]);
}
}
What you are trying to do is called dynamic programming. Basically it is bookkeeping in order to not compute subsolutions more than once.
So basically, you need a mapping of n values to solution values. I would suggest you use a dictionary-like-datastructure for this task.
When a value for n needs to be computed, you first check whether the solution is in the dictionary, if yes you return the result. If not, you compute the result and put it into the dictionary.
Think about how you would initialize this dictionary and how you would pass it down to the recursive function calls.
Here's a lecture video on dynamic programming where the computation of Fibonnaci-numbers using dynamic programming is explained, which is very similar to what you are trying to do:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-19-dynamic-programming-i-fibonacci-shortest-paths/

How to find permutation of k in a given length?

How can I find the permutations of k in a given length?
For example:
The word cat has 3 letters: How can I find all the permutations of 2 in the word cat.
Result should be: ac, at, ca, ac, etc...
This is not a homework problem.
Any language could be used but more preferable: C/C++ or C#.
I know how to create the recursion for size LENGTH but not for a custom size.
Here is one in C#, which should work even with repeated characters. For example on "banana" for permutations of length 2 it gives:
ba bn ab aa an nb na nn
The basic idea is to fix the first character, then form all permutations of length k-1, then prepend the character to those k-1 length permutations. To deal with duplicate characters, we keep track of the count left (i.e the ones which can be used for sub-permutations).
Not exemplary code, but should give you the idea. (If you find bugs, let me know and I can edit).
static List<string> Permutations(Dictionary<char, int> input, int length) {
List<string> permutations = new List<string>();
List<char> chars = new List<char>(input.Keys);
// Base case.
if (length == 0) {
permutations.Add(string.Empty);
return permutations;
}
foreach (char c in chars) {
// There are instances of this character left to use.
if (input[c] > 0) {
// Use one instance up.
input[c]--;
// Find sub-permutations of length length -1.
List<string> subpermutations = Permutations(input, length - 1);
// Give back the instance.
input[c]++;
foreach (string s in subpermutations) {
// Prepend the character to be the first character.
permutations.Add(s.Insert(0,new string(c,1)));
}
}
}
return permutations;
}
And here is the full program I have, to use it:
using System;
using System.Collections.Generic;
namespace StackOverflow {
class Program {
static void Main(string[] args) {
List<string> p = Permutations("abracadabra", 3);
foreach (string s in p) {
Console.WriteLine(s);
}
}
static List<string> Permutations(string s, int length) {
Dictionary<char, int> input = new Dictionary<char, int>();
foreach (char c in s) {
if (input.ContainsKey(c)) {
input[c]++;
} else {
input[c] = 1;
}
}
return Permutations(input, length);
}
static List<string> Permutations(Dictionary<char, int> input,
int length) {
List<string> permutations = new List<string>();
List<char> chars = new List<char>(input.Keys);
if (length == 0) {
permutations.Add(string.Empty);
return permutations;
}
foreach (char c in chars) {
if (input[c] > 0) {
input[c]--;
List<string> subpermutations = Permutations(input,
length - 1);
input[c]++;
foreach (string s in subpermutations) {
permutations.Add(s.Insert(0,new string(c,1)));
}
}
}
return permutations;
}
}
}
What's wrong with the recursive solution and passing an extra parameter (depth) so that the recursive function returns immediately for depth > n.
Not the most efficient, but it works:
public class permutation
{
public static List<string> getPermutations(int n, string word)
{
List<string> tmpPermutation = new List<string>();
if (string.IsNullOrEmpty(word) || n <= 0)
{
tmpPermutation.Add("");
}
else
{
for (int i = 0; i < word.Length; i++)
{
string tmpWord = word.Remove(i, 1);
foreach (var item in getPermutations(n - 1, tmpWord))
{
tmpPermutation.Add(word[i] + item);
}
}
}
return tmpPermutation;
}
}
void Prem (char *str, int k, int length) {
if (k == length-1){
printf("%s\n",str);
return;
} else {
for (int i = k ; i < length; ++i) {
char t = str[k];
str[k] = str[i];
str[i] = t;
Prem(str,k+1,length);
t = str[k];
str[k] = str[i];
str[i] = t;
}
}
}
If I'm not mistaken, this problem can be solved by combinadics too, as on http://en.wikipedia.org/wiki/Combinadic/, there are reference implementations there too.
I have used the Java solution (http://docs.google.com/Doc?id=ddd8c4hm_5fkdr3b/) myself for generating all possible triples from a sequence of numbers, this should be no different.
I lack the wherewithal to explain the math behind it, but as I understand this is the least complex way to iterate over all possible nCr (i.e. 3C2 for your cat example) choices within a collection.
First find the possible subsets of your array. You can do this in
a recursive way it was discussed in Iterating over subsets of any size
Second calculate the permutations of every subset with the STL-Algorithm
next_permutation
I haven't implemented it but i think it should work.

AS3: Optimizing Object Memory Size

I have have a class that I wrote, and it seems bigger than it should be. It doesn't extend anything, and has very little going on - or so I thought - but each one is taking up just under 100k100 bytes ( thanks back2dos ). I guess that I don't have a very good understanding of what really affects how much memory an object takes up in AS3.
If anyone can point me to some reading on the subject that might be helpful, or perhaps explain some insight into how to think about this, that would be awesome.
I would like to keep a LOT of these objects in memory - and I thought I could until now, but at this size I'm going to have to create them or use an object pooling technique of some kind.
Thanks for the assistance.
Edit: Although I've got this in order, I'm keeping the code I posted here for completeness. The class has been heavily modified from the original version. Values that were referencing other files have been made static as to allow the code to run for someone else ( in theory hehehe... ).
Although my situation is sorted out, I'll give the answer to a good reference for information on classes and memory.
In this case the class has 15 variables. I'm only using a single String and a bunch of ints, Numbers, and Booleans with some references to more of the same in globally available XML data. It also imports Point for the constructor, though no points are stored. In testing, even without the global XML references or Point class it's still around a ~84k each. There are getters for 7 of the variables and a couple methods in addition to the constructor. All of which are less than 20 lines ( and I have a very sparse coding style ).
The class mentioned for reference, but feel free to generalize:
package
{
public class AObject
{
private var _counter:int;
private var _frames:int;
private var _speed:int;
private var _currentState:String;
private var _currentFrame:int;
private var _offset:int;
private var _endFrame:int;
private var _type:int;
private var _object:int;
private var _state:int;
private var _x:Number;
private var _y:Number;
private var _w:int;
private var _h:int;
private var _update:Boolean;
public function AObject( targetX : int, targetY : int, state : int, object : int, type : int )
{
_x = targetX;
_y = targetY;
_type = type;
_object = object;
_state = state;
_counter = 0;
_w = 32;
_h = 32
_update = true;
setState( state );
}
public function setState( state:int ) : void
{
_currentState = "bob";
var frameCounter : int = 0;
var stateCounter : int = state - 1;
while ( state > 0 )
{
frameCounter += 4;
--stateCounter;
}
_offset = frameCounter;
_currentFrame = _offset;
_speed = 10;
_frames = 4;
_endFrame = _offset + _frames - 1;
}
public function get state() : int
{
return _state;
}
public function animate() : Boolean
{
if ( count() )
{
if( _currentFrame < _endFrame )
{
++_currentFrame;
}
else
{
_currentFrame = _offset;
}
_speed = 10;
return true;
}
else
{
return false;
}
}
private var adder: Number = 0;
private function count():Boolean
{
_counter++;
if ( _counter == _speed )
{
_counter = 0;
return true;
}
else
{
return false;
}
}
public function get x():int
{
return _x;
}
public function get y():int
{
return _y;
}
public function get type():int
{
return _type;
}
public function get object():int
{
return _object;
}
public function get currentFrame():int
{
return _currentFrame;
}
public function get w():int
{
return _w;
}
public function get h():int
{
return _h;
}
}
}
i am amazed, this compiles at all ... when i try to compile it with the flex SDK, it creates an enormous collision with the built-in class Object, which is the base class of any class, making my trace output overflow ...
other than that, this is an infinite loop if you pass a value for state bigger than 0
while ( state > 0 )
{
frameCounter += 4;
--stateCounter;
}
but it seems really strange these objects are so big ... after renaming and taking care not to pass in 0 for the state, i ran a test:
package {
import flash.display.Sprite;
import flash.sampler.getSize;
import flash.system.System;
public class Main extends Sprite {
public function Main():void {
const count:int = 100000;
var start:uint = System.totalMemory;
var a:Array = [];
for (var i:int = 0; i < count; i++) {
a.push(new MyObject(1, 2, 0, 4, 5));
}
var mem:uint = System.totalMemory - start - getSize(a);
trace("total of "+mem+" B for "+count+" objects, aprox. avg. size per object: "+(mem/count));
}
}
}
it yields:
total of 10982744 B for 100000 objects, aprox. avg. size per object: 109.82744
so that's quite ok ... i think the actual size should be 4 (for the bool) + 4 * 11 (for the ints) + 4 (for the reference to the string) + 8 * 3 (for the three floats (you have the adder somewhere over the count) + 8 for an empty class (reference to the traits objects + something else), giving you a total of 88 bytes ... which is, what you get, if you getSize the object ... please note however, that getSize will only give you the size of the object itself (as calculated here) ignoring the size of what strings or other objects your object references ...
so yeah, apart from that name you definitely should change, the problem must be somewhere else ...
greetz
back2dos
If you really want to save on space, you can fake shorts by using unsigned integers, and using upper/lower bits for one thing or another.
ints are 4 bytes by nature, you can reuse that int on anything less than 2^8.
width height
0xFFFF + 0xFFFF
offset endframe
0xFFFF + 0xFFFF
This though gets ugly when you want to write anything or read anything, as to write width or height you'd have to:
writing:
size = (width & 0x0000FFFF) << 16 | (height & 0x0000FFFF);
reading:
get width():uint { return (size & 0xFFFF0000) >> 16 };
That's ugly. Since you're using getters anyways, and assuming computation speed is not an issue, you could use internal byte arrays which could give you even more granularity for how you want to store your information. Assuming your strings are more than 4 bytes, makes more sense to use a number rather than a string.
Also, I believe you will actually get some memory increase by declaring the class as final, as I believe final functions get placed into the traits object, rather than

I have RTRIM; how to make LTRIM with regexp

I have RTRIM; how to make LTRIM one?
public static function rtrim(string:String):String
{
return string.replace(/\s+$/,"");
}
public static function ltrim(string:String):String {
return string.replace(/^\s+/,"");
}
Caveat: Untested! Look up the flex 3.0 documentation here. This is exactly similar to what you have, except that we use a different metacharacter to specify that we want to start searching for whitespaces (\s -- another metacharacter) from the begining(^) instead of from the end($). The + after \s tells the pattern matches to grok one or more whitespaces.
Instead of re-inventing the wheel, why not just use the StringUtil class from Adobe's as3corelib library?
Out of interest, as3corelib defines it's trim functions as follows:
public static function trim(input:String):String
{
return StringUtil.ltrim(StringUtil.rtrim(input));
}
public static function ltrim(input:String):String
{
var size:Number = input.length;
for(var i:Number = 0; i < size; i++)
{
if(input.charCodeAt(i) > 32)
{
return input.substring(i);
}
}
return "";
}
public static function rtrim(input:String):String
{
var size:Number = input.length;
for(var i:Number = size; i > 0; i--)
{
if(input.charCodeAt(i - 1) > 32)
{
return input.substring(0, i);
}
}
return "";
}
Wow, seriously? You're using regular expressions to remove a constant sequence of characters from the ends of a string? Really? I don't know Actionscript/Flex, but this isn't the way to go. After a quick google I found a solution which may or may not be more efficient.