Search Results

Search found 50 results on 2 pages for 'ys'.

Page 1/2 | 1 2  | Next Page >

  • Zipping with padding in Haskell

    - by Travis Brown
    A couple of times I've found myself wanting a zip in Haskell that adds padding to the shorter list instead of truncating the longer one. This is easy enough to write. (Monoid works for me here, but you could also just pass in the elements that you want to use for padding.) zipPad :: (Monoid a, Monoid b) => [a] -> [b] -> [(a, b)] zipPad xs [] = zip xs (repeat mempty) zipPad [] ys = zip (repeat mempty) ys zipPad (x:xs) (y:ys) = (x, y) : zipPad xs ys This approach gets ugly when trying to define zipPad3. I typed up the following and then realized that of course it doesn't work: zipPad3 :: (Monoid a, Monoid b, Monoid c) => [a] -> [b] -> [c] -> [(a, b, c)] zipPad3 xs [] [] = zip3 xs (repeat mempty) (repeat mempty) zipPad3 [] ys [] = zip3 (repeat mempty) ys (repeat mempty) zipPad3 [] [] zs = zip3 (repeat mempty) (repeat mempty) zs zipPad3 xs ys [] = zip3 xs ys (repeat mempty) zipPad3 xs [] zs = zip3 xs (repeat mempty) zs zipPad3 [] ys zs = zip3 (repeat mempty) ys zs zipPad3 (x:xs) (y:ys) (z:zs) = (x, y, z) : zipPad3 xs ys zs At this point I cheated and just used length to pick the longest list and pad the others. Am I overlooking a more elegant way to do this, or is something like zipPad3 already defined somewhere?

    Read the article

  • Why does s ++ t not lead to a stack overflow for large s?

    - by martingw
    I'm wondering why Prelude> head $ reverse $ [1..10000000] ++ [99] 99 does not lead to a stack overflow error. The ++ in the prelude seems straight forward and non-tail-recursive: (++) :: [a] -> [a] -> [a] (++) [] ys = ys (++) (x:xs) ys = x : xs ++ ys So just with this, it should run into a stack overflow, right? So I figure it probably has something to do with the ghc magic that follows the definition of ++: {-# RULES "++" [~1] forall xs ys. xs ++ ys = augment (\c n -> foldr c n xs) ys #-} Is that what helps avoiding the stack overflow? Could someone provide some hint for what's going on in this piece of code?

    Read the article

  • Changes to the LINQ-to-StreamInsight Dialect

    - by Roman Schindlauer
    In previous versions of StreamInsight (1.0 through 2.0), CepStream<> represents temporal streams of many varieties: Streams with ‘open’ inputs (e.g., those defined and composed over CepStream<T>.Create(string streamName) Streams with ‘partially bound’ inputs (e.g., those defined and composed over CepStream<T>.Create(Type adapterFactory, …)) Streams with fully bound inputs (e.g., those defined and composed over To*Stream – sequences or DQC) The stream may be embedded (where Server.Create is used) The stream may be remote (where Server.Connect is used) When adding support for new programming primitives in StreamInsight 2.1, we faced a choice: Add a fourth variety (use CepStream<> to represent streams that are bound the new programming model constructs), or introduce a separate type that represents temporal streams in the new user model. We opted for the latter. Introducing a new type has the effect of reducing the number of (confusing) runtime failures due to inappropriate uses of CepStream<> instances in the incorrect context. The new types are: IStreamable<>, which logically represents a temporal stream. IQStreamable<> : IStreamable<>, which represents a queryable temporal stream. Its relationship to IStreamable<> is analogous to the relationship of IQueryable<> to IEnumerable<>. The developer can compose temporal queries over remote stream sources using this type. The syntax of temporal queries composed over IQStreamable<> is mostly consistent with the syntax of our existing CepStream<>-based LINQ provider. However, we have taken the opportunity to refine certain aspects of the language surface. Differences are outlined below. Because 2.1 introduces new types to represent temporal queries, the changes outlined in this post do no impact existing StreamInsight applications using the existing types! SelectMany StreamInsight does not support the SelectMany operator in its usual form (which is analogous to SQL’s “CROSS APPLY” operator): static IEnumerable<R> SelectMany<T, R>(this IEnumerable<T> source, Func<T, IEnumerable<R>> collectionSelector) It instead uses SelectMany as a convenient syntactic representation of an inner join. The parameter to the selector function is thus unavailable. Because the parameter isn’t supported, its type in StreamInsight 1.0 – 2.0 wasn’t carefully scrutinized. Unfortunately, the type chosen for the parameter is nonsensical to LINQ programmers: static CepStream<R> SelectMany<T, R>(this CepStream<T> source, Expression<Func<CepStream<T>, CepStream<R>>> streamSelector) Using Unit as the type for the parameter accurately reflects the StreamInsight’s capabilities: static IQStreamable<R> SelectMany<T, R>(this IQStreamable<T> source, Expression<Func<Unit, IQStreamable<R>>> streamSelector) For queries that succeed – that is, queries that do not reference the stream selector parameter – there is no difference between the code written for the two overloads: from x in xs from y in ys select f(x, y) Top-K The Take operator used in StreamInsight causes confusion for LINQ programmers because it is applied to the (unbounded) stream rather than the (bounded) window, suggesting that the query as a whole will return k rows: (from win in xs.SnapshotWindow() from x in win orderby x.A select x.B).Take(k) The use of SelectMany is also unfortunate in this context because it implies the availability of the window parameter within the remainder of the comprehension. The following compiles but fails at runtime: (from win in xs.SnapshotWindow() from x in win orderby x.A select win).Take(k) The Take operator in 2.1 is applied to the window rather than the stream: Before After (from win in xs.SnapshotWindow() from x in win orderby x.A select x.B).Take(k) from win in xs.SnapshotWindow() from b in     (from x in win     orderby x.A     select x.B).Take(k) select b Multicast We are introducing an explicit multicast operator in order to preserve expression identity, which is important given the semantics about moving code to and from StreamInsight. This also better matches existing LINQ dialects, such as Reactive. This pattern enables expressing multicasting in two ways: Implicit Explicit var ys = from x in xs          where x.A > 1          select x; var zs = from y1 in ys          from y2 in ys.ShiftEventTime(_ => TimeSpan.FromSeconds(1))          select y1 + y2; var ys = from x in xs          where x.A > 1          select x; var zs = ys.Multicast(ys1 =>     from y1 in ys1     from y2 in ys1.ShiftEventTime(_ => TimeSpan.FromSeconds(1))     select y1 + y2; Notice the product translates an expression using implicit multicast into an expression using the explicit multicast operator. The user does not see this translation. Default window policies Only default window policies are supported in the new surface. Other policies can be simulated by using AlterEventLifetime. Before After xs.SnapshotWindow(     WindowInputPolicy.ClipToWindow,     SnapshotWindowInputPolicy.Clip) xs.SnapshotWindow() xs.TumblingWindow(     TimeSpan.FromSeconds(1),     HoppingWindowOutputPolicy.PointAlignToWindowEnd) xs.TumblingWindow(     TimeSpan.FromSeconds(1)) xs.TumblingWindow(     TimeSpan.FromSeconds(1),     HoppingWindowOutputPolicy.ClipToWindowEnd) Not supported … LeftAntiJoin Representation of LASJ as a correlated sub-query in the LINQ surface is problematic as the StreamInsight engine does not support correlated sub-queries (see discussion of SelectMany). The current syntax requires the introduction of an otherwise unsupported ‘IsEmpty()’ operator. As a result, the pattern is not discoverable and implies capabilities not present in the server. The direct representation of LASJ is used instead: Before After from x in xs where     (from y in ys     where x.A > y.B     select y).IsEmpty() select x xs.LeftAntiJoin(ys, (x, y) => x.A > y.B) from x in xs where     (from y in ys     where x.A == y.B     select y).IsEmpty() select x xs.LeftAntiJoin(ys, x => x.A, y => y.B) ApplyWithUnion The ApplyWithUnion methods have been deprecated since their signatures are redundant given the standard SelectMany overloads: Before After xs.GroupBy(x => x.A).ApplyWithUnion(gs => from win in gs.SnapshotWindow() select win.Count()) xs.GroupBy(x => x.A).SelectMany(     gs =>     from win in gs.SnapshotWindow()     select win.Count()) xs.GroupBy(x => x.A).ApplyWithUnion(gs => from win in gs.SnapshotWindow() select win.Count(), r => new { r.Key, Count = r.Payload }) from x in xs group x by x.A into gs from win in gs.SnapshotWindow() select new { gs.Key, Count = win.Count() } Alternate UDO syntax The representation of UDOs in the StreamInsight LINQ dialect confuses cardinalities. Based on the semantics of user-defined operators in StreamInsight, one would expect to construct queries in the following form: from win in xs.SnapshotWindow() from y in MyUdo(win) select y Instead, the UDO proxy method is referenced within a projection, and the (many) results returned by the user code are automatically flattened into a stream: from win in xs.SnapshotWindow() select MyUdo(win) The “many-or-one” confusion is exemplified by the following example that compiles but fails at runtime: from win in xs.SnapshotWindow() select MyUdo(win) + win.Count() The above query must fail because the UDO is in fact returning many values per window while the count aggregate is returning one. Original syntax New alternate syntax from win in xs.SnapshotWindow() select win.UdoProxy(1) from win in xs.SnapshotWindow() from y in win.UserDefinedOperator(() => new Udo(1)) select y -or- from win in xs.SnapshotWindow() from y in win.UdoMacro(1) select y Notice that this formulation also sidesteps the dynamic type pitfalls of the existing “proxy method” approach to UDOs, in which the type of the UDO implementation (TInput, TOuput) and the type of its constructor arguments (TConfig) need to align in a precise and non-obvious way with the argument and return types for the corresponding proxy method. UDSO syntax UDSO currently leverages the DataContractSerializer to clone initial state for logical instances of the user operator. Initial state will instead be described by an expression in the new LINQ surface. Before After xs.Scan(new Udso()) xs.Scan(() => new Udso()) Name changes ShiftEventTime => AlterEventStartTime: The alter event lifetime overload taking a new start time value has been renamed. CountByStartTimeWindow => CountWindow

    Read the article

  • Changes to the LINQ-to-StreamInsight Dialect

    - by Roman Schindlauer
    In previous versions of StreamInsight (1.0 through 2.0), CepStream<> represents temporal streams of many varieties: Streams with ‘open’ inputs (e.g., those defined and composed over CepStream<T>.Create(string streamName) Streams with ‘partially bound’ inputs (e.g., those defined and composed over CepStream<T>.Create(Type adapterFactory, …)) Streams with fully bound inputs (e.g., those defined and composed over To*Stream – sequences or DQC) The stream may be embedded (where Server.Create is used) The stream may be remote (where Server.Connect is used) When adding support for new programming primitives in StreamInsight 2.1, we faced a choice: Add a fourth variety (use CepStream<> to represent streams that are bound the new programming model constructs), or introduce a separate type that represents temporal streams in the new user model. We opted for the latter. Introducing a new type has the effect of reducing the number of (confusing) runtime failures due to inappropriate uses of CepStream<> instances in the incorrect context. The new types are: IStreamable<>, which logically represents a temporal stream. IQStreamable<> : IStreamable<>, which represents a queryable temporal stream. Its relationship to IStreamable<> is analogous to the relationship of IQueryable<> to IEnumerable<>. The developer can compose temporal queries over remote stream sources using this type. The syntax of temporal queries composed over IQStreamable<> is mostly consistent with the syntax of our existing CepStream<>-based LINQ provider. However, we have taken the opportunity to refine certain aspects of the language surface. Differences are outlined below. Because 2.1 introduces new types to represent temporal queries, the changes outlined in this post do no impact existing StreamInsight applications using the existing types! SelectMany StreamInsight does not support the SelectMany operator in its usual form (which is analogous to SQL’s “CROSS APPLY” operator): static IEnumerable<R> SelectMany<T, R>(this IEnumerable<T> source, Func<T, IEnumerable<R>> collectionSelector) It instead uses SelectMany as a convenient syntactic representation of an inner join. The parameter to the selector function is thus unavailable. Because the parameter isn’t supported, its type in StreamInsight 1.0 – 2.0 wasn’t carefully scrutinized. Unfortunately, the type chosen for the parameter is nonsensical to LINQ programmers: static CepStream<R> SelectMany<T, R>(this CepStream<T> source, Expression<Func<CepStream<T>, CepStream<R>>> streamSelector) Using Unit as the type for the parameter accurately reflects the StreamInsight’s capabilities: static IQStreamable<R> SelectMany<T, R>(this IQStreamable<T> source, Expression<Func<Unit, IQStreamable<R>>> streamSelector) For queries that succeed – that is, queries that do not reference the stream selector parameter – there is no difference between the code written for the two overloads: from x in xs from y in ys select f(x, y) Top-K The Take operator used in StreamInsight causes confusion for LINQ programmers because it is applied to the (unbounded) stream rather than the (bounded) window, suggesting that the query as a whole will return k rows: (from win in xs.SnapshotWindow() from x in win orderby x.A select x.B).Take(k) The use of SelectMany is also unfortunate in this context because it implies the availability of the window parameter within the remainder of the comprehension. The following compiles but fails at runtime: (from win in xs.SnapshotWindow() from x in win orderby x.A select win).Take(k) The Take operator in 2.1 is applied to the window rather than the stream: Before After (from win in xs.SnapshotWindow() from x in win orderby x.A select x.B).Take(k) from win in xs.SnapshotWindow() from b in     (from x in win     orderby x.A     select x.B).Take(k) select b Multicast We are introducing an explicit multicast operator in order to preserve expression identity, which is important given the semantics about moving code to and from StreamInsight. This also better matches existing LINQ dialects, such as Reactive. This pattern enables expressing multicasting in two ways: Implicit Explicit var ys = from x in xs          where x.A > 1          select x; var zs = from y1 in ys          from y2 in ys.ShiftEventTime(_ => TimeSpan.FromSeconds(1))          select y1 + y2; var ys = from x in xs          where x.A > 1          select x; var zs = ys.Multicast(ys1 =>     from y1 in ys1     from y2 in ys1.ShiftEventTime(_ => TimeSpan.FromSeconds(1))     select y1 + y2; Notice the product translates an expression using implicit multicast into an expression using the explicit multicast operator. The user does not see this translation. Default window policies Only default window policies are supported in the new surface. Other policies can be simulated by using AlterEventLifetime. Before After xs.SnapshotWindow(     WindowInputPolicy.ClipToWindow,     SnapshotWindowInputPolicy.Clip) xs.SnapshotWindow() xs.TumblingWindow(     TimeSpan.FromSeconds(1),     HoppingWindowOutputPolicy.PointAlignToWindowEnd) xs.TumblingWindow(     TimeSpan.FromSeconds(1)) xs.TumblingWindow(     TimeSpan.FromSeconds(1),     HoppingWindowOutputPolicy.ClipToWindowEnd) Not supported … LeftAntiJoin Representation of LASJ as a correlated sub-query in the LINQ surface is problematic as the StreamInsight engine does not support correlated sub-queries (see discussion of SelectMany). The current syntax requires the introduction of an otherwise unsupported ‘IsEmpty()’ operator. As a result, the pattern is not discoverable and implies capabilities not present in the server. The direct representation of LASJ is used instead: Before After from x in xs where     (from y in ys     where x.A > y.B     select y).IsEmpty() select x xs.LeftAntiJoin(ys, (x, y) => x.A > y.B) from x in xs where     (from y in ys     where x.A == y.B     select y).IsEmpty() select x xs.LeftAntiJoin(ys, x => x.A, y => y.B) ApplyWithUnion The ApplyWithUnion methods have been deprecated since their signatures are redundant given the standard SelectMany overloads: Before After xs.GroupBy(x => x.A).ApplyWithUnion(gs => from win in gs.SnapshotWindow() select win.Count()) xs.GroupBy(x => x.A).SelectMany(     gs =>     from win in gs.SnapshotWindow()     select win.Count()) xs.GroupBy(x => x.A).ApplyWithUnion(gs => from win in gs.SnapshotWindow() select win.Count(), r => new { r.Key, Count = r.Payload }) from x in xs group x by x.A into gs from win in gs.SnapshotWindow() select new { gs.Key, Count = win.Count() } Alternate UDO syntax The representation of UDOs in the StreamInsight LINQ dialect confuses cardinalities. Based on the semantics of user-defined operators in StreamInsight, one would expect to construct queries in the following form: from win in xs.SnapshotWindow() from y in MyUdo(win) select y Instead, the UDO proxy method is referenced within a projection, and the (many) results returned by the user code are automatically flattened into a stream: from win in xs.SnapshotWindow() select MyUdo(win) The “many-or-one” confusion is exemplified by the following example that compiles but fails at runtime: from win in xs.SnapshotWindow() select MyUdo(win) + win.Count() The above query must fail because the UDO is in fact returning many values per window while the count aggregate is returning one. Original syntax New alternate syntax from win in xs.SnapshotWindow() select win.UdoProxy(1) from win in xs.SnapshotWindow() from y in win.UserDefinedOperator(() => new Udo(1)) select y -or- from win in xs.SnapshotWindow() from y in win.UdoMacro(1) select y Notice that this formulation also sidesteps the dynamic type pitfalls of the existing “proxy method” approach to UDOs, in which the type of the UDO implementation (TInput, TOuput) and the type of its constructor arguments (TConfig) need to align in a precise and non-obvious way with the argument and return types for the corresponding proxy method. UDSO syntax UDSO currently leverages the DataContractSerializer to clone initial state for logical instances of the user operator. Initial state will instead be described by an expression in the new LINQ surface. Before After xs.Scan(new Udso()) xs.Scan(() => new Udso()) Name changes ShiftEventTime => AlterEventStartTime: The alter event lifetime overload taking a new start time value has been renamed. CountByStartTimeWindow => CountWindow

    Read the article

  • Tail-recursive implementation of take-while

    - by Giorgio
    I am trying to write a tail-recursive implementation of the function take-while in Scheme (but this exercise can be done in another language as well). My first attempt was (define (take-while p xs) (if (or (null? xs) (not (p (car xs)))) '() (cons (car xs) (take-while p (cdr xs))))) which works correctly but is not tail-recursive. My next attempt was (define (take-while-tr p xs) (let loop ((acc '()) (ys xs)) (if (or (null? ys) (not (p (car ys)))) (reverse acc) (loop (cons (car ys) acc) (cdr ys))))) which is tail recursive but needs a call to reverse as a last step in order to return the result list in the proper order. I cannot come up with a solution that is tail-recursive, does not use reverse, only uses lists as data structure (using a functional data structure like a Haskell's sequence which allows to append elements is not an option), has complexity linear in the size of the prefix, or at least does not have quadratic complexity (thanks to delnan for pointing this out). Is there an alternative solution satisfying all the properties above? My intuition tells me that it is impossible to accumulate the prefix of a list in a tail-recursive fashion while maintaining the original order between the elements (i.e. without the need of using reverse to adjust the result) but I am not able to prove this. Note The solution using reverse satisfies conditions 1, 3, 4.

    Read the article

  • 2D isometric: screen to tile coordinates

    - by Dr_Asik
    I'm writing an isometric 2D game and I'm having difficulty figuring precisely on which tile the cursor is. Here's a drawing: where xs and ys are screen coordinates (pixels), xt and yt are tile coordinates, W and H are tile width and tile height in pixels, respectively. My notation for coordinates is (y, x) which may be confusing, sorry about that. The best I could figure out so far is this: int xtemp = xs / (W / 2); int ytemp = ys / (H / 2); int xt = (xs - ys) / 2; int yt = ytemp + xt; This seems almost correct but is giving me a very imprecise result, making it hard to select certain tiles, or sometimes it selects a tile next to the one I'm trying to click on. I don't understand why and I'd like if someone could help me understand the logic behind this. Thanks!

    Read the article

  • find if list 1 is a sequence of list 2 in haskell

    - by Isaak Wahb
    im trying to check if a given list is a subsequence of another list: here are example of lists which gives true: subseq "" "w" subseq "w" "w" subseq "ab" "cab" subseq "cb" "cab" subseq "aa" "xaxa" not (subseq "aa" "xax") not (subseq "ab" "ba") i just come to this but in some cases it gives a wrong result subseq :: Eq a => [a] -> [a] -> Bool subseq [] [] = True subseq [] ys = True subseq xs [] = False subseq (x:xs) (y:ys) = x == y || subseq xs ( 1 `drop` ys )

    Read the article

  • Cartesian Plane

    - by NuNu
    I'm trying to define a function in Haskell that takes an integer argument c and returns the list of all points on the cartesian plane of the form (x/c,y/c) where x and y are integers. x/c is between -2 and 1 and y/r is between -1 and 1 This is what I've gotten so far which I'm almost sure is right but I'm getting a parse error on input = when I run it particularly at this line: cart xs ys c = [(y/c,x/c) | x <- xs, y <- ys] plane :: Int -> [a] plane c = cart [-1*c .. 1*c] [-2*c .. 1*c] c cart xs ys c = [(y/c,x/c) | x <- xs, y <- ys] A sample output would be: plane 1 would generate: [(-2.0, -1.0), (-1.0, -1.0), ( 0.0, -1.0), ( 1.0, -1.0), (-2.0, 0.0), (-1.0, 0.0), ( 0.0, 0.0), ( 1.0, 0.0), (-2.0, 1.0), (-1.0, 1.0), ( 0.0, 1.0), ( 1.0, 1.0)] Anyone have any idea how I can fix this! Thanks

    Read the article

  • Bouncing off a circular Boundary with multiple balls?

    - by Anarkie
    I am making a game like this : Yellow Smiley has to escape from red smileys, when yellow smiley hits the boundary game is over, when red smileys hit the boundary they should bounce back with the same angle they came, like shown below: Every 10 seconds a new red smiley comes in the big circle, when red smiley hits yellow, game is over, speed and starting angle of red smileys should be random. I control the yellow smiley with arrow keys. The biggest problem I have reflecting the red smileys from the boundary with the angle they came. I don't know how I can give a starting angle to a red smiley and bouncing it with the angle it came. I would be glad for any tips! My js source code : var canvas = document.getElementById("mycanvas"); var ctx = canvas.getContext("2d"); // Object containing some global Smiley properties. var SmileyApp = { radius: 15, xspeed: 0, yspeed: 0, xpos:200, // x-position of smiley ypos: 200 // y-position of smiley }; var SmileyRed = { radius: 15, xspeed: 0, yspeed: 0, xpos:350, // x-position of smiley ypos: 65 // y-position of smiley }; var SmileyReds = new Array(); for (var i=0; i<5; i++){ SmileyReds[i] = { radius: 15, xspeed: 0, yspeed: 0, xpos:350, // x-position of smiley ypos: 67 // y-position of smiley }; SmileyReds[i].xspeed = Math.floor((Math.random()*50)+1); SmileyReds[i].yspeed = Math.floor((Math.random()*50)+1); } function drawBigCircle() { var centerX = canvas.width / 2; var centerY = canvas.height / 2; var radiusBig = 300; ctx.beginPath(); ctx.arc(centerX, centerY, radiusBig, 0, 2 * Math.PI, false); // context.fillStyle = 'green'; // context.fill(); ctx.lineWidth = 5; // context.strokeStyle = '#003300'; // green ctx.stroke(); } function lineDistance( positionx, positiony ) { var xs = 0; var ys = 0; xs = positionx - 350; xs = xs * xs; ys = positiony - 350; ys = ys * ys; return Math.sqrt( xs + ys ); } function drawSmiley(x,y,r) { // outer border ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(x,y,r, 0, 2*Math.PI); //red ctx.fillStyle="rgba(255,0,0, 0.5)"; ctx.fillStyle="rgba(255,255,0, 0.5)"; ctx.fill(); ctx.stroke(); // mouth ctx.beginPath(); ctx.moveTo(x+0.7*r, y); ctx.arc(x,y,0.7*r, 0, Math.PI, false); // eyes var reye = r/10; var f = 0.4; ctx.moveTo(x+f*r, y-f*r); ctx.arc(x+f*r-reye, y-f*r, reye, 0, 2*Math.PI); ctx.moveTo(x-f*r, y-f*r); ctx.arc(x-f*r+reye, y-f*r, reye, -Math.PI, Math.PI); // nose ctx.moveTo(x,y); ctx.lineTo(x, y-r/2); ctx.lineWidth = 1; ctx.stroke(); } function drawSmileyRed(x,y,r) { // outer border ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(x,y,r, 0, 2*Math.PI); //red ctx.fillStyle="rgba(255,0,0, 0.5)"; //yellow ctx.fillStyle="rgba(255,255,0, 0.5)"; ctx.fill(); ctx.stroke(); // mouth ctx.beginPath(); ctx.moveTo(x+0.4*r, y+10); ctx.arc(x,y+10,0.4*r, 0, Math.PI, true); // eyes var reye = r/10; var f = 0.4; ctx.moveTo(x+f*r, y-f*r); ctx.arc(x+f*r-reye, y-f*r, reye, 0, 2*Math.PI); ctx.moveTo(x-f*r, y-f*r); ctx.arc(x-f*r+reye, y-f*r, reye, -Math.PI, Math.PI); // nose ctx.moveTo(x,y); ctx.lineTo(x, y-r/2); ctx.lineWidth = 1; ctx.stroke(); } // --- Animation of smiley moving with constant speed and bounce back at edges of canvas --- var tprev = 0; // this is used to calculate the time step between two successive calls of run function run(t) { requestAnimationFrame(run); if (t === undefined) { t=0; } var h = t - tprev; // time step tprev = t; SmileyApp.xpos += SmileyApp.xspeed * h/1000; // update position according to constant speed SmileyApp.ypos += SmileyApp.yspeed * h/1000; // update position according to constant speed for (var i=0; i<SmileyReds.length; i++){ SmileyReds[i].xpos += SmileyReds[i].xspeed * h/1000; // update position according to constant speed SmileyReds[i].ypos += SmileyReds[i].yspeed * h/1000; // update position according to constant speed } // change speed direction if smiley hits canvas edges if (lineDistance(SmileyApp.xpos, SmileyApp.ypos) + SmileyApp.radius > 300) { alert("Game Over"); } // redraw smiley at new position ctx.clearRect(0,0,canvas.height, canvas.width); drawBigCircle(); drawSmiley(SmileyApp.xpos, SmileyApp.ypos, SmileyApp.radius); for (var i=0; i<SmileyReds.length; i++){ drawSmileyRed(SmileyReds[i].xpos, SmileyReds[i].ypos, SmileyReds[i].radius); } } // uncomment these two lines to get every going // SmileyApp.speed = 100; run(); // --- Control smiley motion with left/right arrow keys function arrowkeyCB(event) { event.preventDefault(); if (event.keyCode === 37) { // left arrow SmileyApp.xspeed = -100; SmileyApp.yspeed = 0; } else if (event.keyCode === 39) { // right arrow SmileyApp.xspeed = 100; SmileyApp.yspeed = 0; } else if (event.keyCode === 38) { // up arrow SmileyApp.yspeed = -100; SmileyApp.xspeed = 0; } else if (event.keyCode === 40) { // right arrow SmileyApp.yspeed = 100; SmileyApp.xspeed = 0; } } document.addEventListener('keydown', arrowkeyCB, true); JSFiddle : http://jsfiddle.net/gj4Q7/

    Read the article

  • Comparing lists in Standard ML

    - by user1050640
    I am extremely new to SML and we just got out first programming assignment for class and I need a little insight. The question is: write an ML function, called minus: int list * int list -> int list, that takes two non-decreasing integer lists and produces a non-decreasing integer list obtained by removing the elements from the first input list which are also found in the second input list. For example, minus( [1,1,1,2,2], [1,1,2,3] ) = [1,2] minus( [1,1,2,3],[1,1,1,2,2] ) = [3] Here is my attempt at answering the question. Can anyone tell me what I am doing incorrectly? I don't quite understand parsing lists. fun minus(xs,nil) = [] | minus(nil,ys) = [] | minus(x::xs,y::ys) = if x=y then minus(xs,ys) else x :: minus(x,ys); Here is a fix I just did, I think this is right now? fun minus(L1,nil) = L1 | minus(nil,L2) = [] | minus(L1,L2) = if hd(L1) > hd(L2) then minus(L1,tl(L2)) else if hd(L1) = hd(L2) then minus(tl(L1),tl(L2)) else hd(L1) :: minus(tl(L1), L2);

    Read the article

  • Generic foreach loop in C#.

    - by mcoolbeth
    The compiler, given the following code, tells me "Use of unassigned local variable 'x'." Any thoughts? public delegate Y Function<X,Y>(X x); public class Map<X,Y> { private Function<X,Y> F; public Map(Function f) { F = f; } public Collection<Y> Over(Collection<X> xs){ List<Y> ys = new List<Y>(); foreach (X x in xs) { X x2 = x;//ys.Add(F(x)); } return ys; } }

    Read the article

  • Resources on how to relate structured and semi- / un-structured information

    - by Fritz Meissner
    I don't have a great background in information organisation / retrieval, but I know of a few ways of dealing with the problem. For structured information, it's possible to go OOish - everything "has-a" or "has-many" something else, and you navigate the graph to find relationships between things. For unstructured information, you have techniques like text search and tagging. What resources - articles or books - are there that summarise the CS theory behind these techniques or could introduce me to others? I'm developing a system that needs to handle capture and retrieval of information that ranges from necessarily unstructured (advice about X) to structured (list of Xs that relate to Ys) to a combination (Ys that relate to the advice about X) and I'd like to get some insight into how to do it properly.

    Read the article

  • Circle-Rectangle collision in a tile map game

    - by furiousd
    I am making a 2D tile map based putt-putt game. I have collision detection working between the ball and the walls of the map, although when the ball collides at the meeting point between 2 tiles I offset it by 0.5 so that it doesn't get stuck in the wall. This aint a huge issue though. if(y % 20 == 0) { y+=0.5; } if(x % 20 == 0) { x+=0.5; } Collisions work as follows Find the closest point between each tile and the center of the ball If distance(ball_x, ball_y, close_x, close_y) <= ball_radius and the closest point belongs to a solid object, collision has occured Invert X/Y speed according to side of object collided with The next thing I tried to do was implement floating blocks in the middle of the map for the ball to bounce off of. When a ball collides with a corner of the block, it gets stuck in it. So I changed my determineRebound() function to treat corners as if they were circles. Here's that functon: `i and j are indexes of the solid object in the 2d map array. x & y are centre point of ball.` void determineRebound(int _i, int _j) { if(y > _i*tile_w && y < _i*tile_w + tile_w) { //Not a corner xs*=-1; } else if(x > _j*tile_w && x < _j*tile_w + tile_w) { //Not a corner ys*=-1; } else { //Corner float nx = x - close_x; float ny = y - close_y; float len = sqrt(nx * nx + ny * ny); nx /= len; ny /= len; float projection = xs * nx + ys * ny; xs -= 2 * projection * nx; ys -= 2 * projection * ny; } } This is where things have gotten messy. Collisions with 'floating' corners work fine, but now when the ball collides near the meeting point of 2 tiles, it detects a corner collision and does not rebound as expected. I'm a bit in over my head at this point. I guess I'm wondering if I'm going about making this sort of game in the right way. Is a 2d tile map the way to go? If so, is there a problem with my collision logic and where am I going wrong? Any advice/feedback would be great.

    Read the article

  • C++11 support for higher-order list functions

    - by Giorgio
    Most functional programming languages (e.g. Common Lisp, Scheme / Racket, Clojure, Haskell, Scala, Ocaml, SML) support some common higher-order functions on lists, such as map, filter, takeWhile, dropWhile, foldl, foldr (see e.g. Common Lisp, Scheme / Racket, Clojure side-by-side reference sheet, the Haskell, Scala, OCaml, and the SML documentation.) Does C++11 have equivalent standard methods or functions on lists? For example, consider the following Haskell snippet: let xs = [1, 2, 3, 4, 5] let ys = map (\x -> x * x) xs How can I express the second expression in modern standard C++? std::list<int> xs = ... // Initialize the list in some way. std::list<int> ys = ??? // How to translate the Haskell expression? What about the other higher-order functions mentioned above? Can they be directly expressed in C++?

    Read the article

  • Template Matching 2 ROI in a single video capture in real time

    - by YS
    Hi, I am working on a project to perform template matching on a video captured via my webcam. I am able to create 2 template from the webcam capture, but I am unable to perform template matching for both. The program can run only with either template matching, but not both. My program sequence is: Capture from webcam get template 1 get template 2 perform template 1 matching with webcam capture then perform template 2 matching with webcam capture if fail, stop. Can any expert advice me on this?

    Read the article

  • Doctrine_Query update with float value

    - by YS-PRO
    I need to increment User's balance, so I do: Doctrine_Query::create()->from('User')->update('balance', 'balance + 0.15')->execute(); And I got an error "Unknown component alias 0". I think its because of 0.15 So how can I update (using DQL) balance without additional SELECT queries to User's table to fetch his balance, calculate new balance and do query like Doctrine_Query::create()->from('User')->update('balance', '?', $new_balance)->execute();

    Read the article

  • sphinx cuts symbol

    - by YS-PRO
    I have a music collection and use sphinx for searching in it. Search mode is SPH_MATCH_PHRASE, but when I search f.e. for "B'Day" album - sphinx cuts "'" and searching by "Day" query. How can I force sphinx to search by exact phrase without filtering any symbols?

    Read the article

  • Precisely Compare 2 images for differences using OpenCV

    - by YS
    Hi, I am working on a project to capture images via webcam in a predefined time interval, and continuously compare the images to a template (good image) and give an error if the difference is tolerance set. I working out using OpenCV. Would like to have advice how should I do it, e.g. best method, etc. Appreciate if any one can help me on this. Thanks.

    Read the article

  • Haskell search an element on a List

    - by user1887556
    I want a function that changes (1 to 0) on a list, when number of 1's isn't even. I have done these functions: 1) Sees if the lines in a list are even or not: parityLine :: [[Int]] -> [Bool] parityLine [] =[] parityLine (x:xs) |sum(x) `mod` 2 == 0 = True:(parityLine(xs)) |otherwise = False:(parityLine(xs)) 2) Sum the corresponding elements on a list of lists: sumPositions :: [[Int]] -> [Int] sumPositions [] = [] sumPositions (x:xs) = foldl (zipWith (+)) (repeat 0) (x:xs) 3) Sees if the columns in a list are even or not: parityColumn :: [Int] -> [Bool] parityColumn [] = [] parityColumn (x:xs) |head(x:xs) `mod` 2 == 0 = True:parityColumn(xs) |otherwise = False:parityColumn(xs) 4) Does the operation or with two boolean lists: bol :: [Bool] -> [Bool] -> [[Bool]] bol [] _ = [] bol (x:xs) (y:ys)= (map (||x) (y:ys)):(bol xs (y:ys)) 5) Correct List: correct :: [[Int]] -> [[Bool]] correct [] = [] correct (x:xs)=(bol(parityLine (x:xs))(parityColumn(sumPositions(x:xs)))) So what I want is to alter the function correct to [[Int]]-[[Int]] that does this: My Int list(x:xs) With my correct function applied [[0,0,1,1], [[True,True,False,True], [1,0,1,1], [True,True,True,True], [0,1,0,1], [True,True,True,True] [1,1,1,1]] [True,True,True,True]] Now I can see that in the first line third column, False, so I have to correct that number 1 to have a number of 1's even. Result I want that function correct does: [[0,0,0,1], [1,0,1,1], [0,1,0,1], [1,1,1,1]] Thanks.

    Read the article

  • Folding a list in F#

    - by bytebuster
    I have a pretty trivial task but I can't figure out how to make the solution prettier. The goal is taking a List and returning results, based on whether they passed a predicate. The results should be grouped. Here's a simplified example: Predicate: isEven Inp : [2; 4; 3; 7; 6; 10; 4; 5] Out: [[^^^^]......[^^^^^^^^]..] Here's the code I have so far: let f p ls = List.foldBack (fun el (xs, ys) -> if p el then (el::xs, ys) else ([], xs::ys)) ls ([], []) |> List.Cons // (1) |> List.filter (not << List.isEmpty) // (2) let even x = x % 2 = 0 let ret = [2; 4; 3; 7; 6; 10; 4; 5] |> f even // expected [[2; 4]; [6; 10; 4]] This code does not seem to be readable that much. Also, I don't like lines (1) and (2). Is there any better solution?

    Read the article

  • Find an element in a JavaScript array

    - by Aligned
    Originally posted on: http://geekswithblogs.net/Aligned/archive/2014/08/22/find-an-element-in-a-javascript-array.aspxI needed a C# Dictionary like data structure in JavaScript and then a way to find that object by a key. I had forgotten how to do this, so did some searching and talked to a colleague and came up with this JsFiddle. See the code in my jsFiddle or below: var processingProgressTimeoutIds = []; var file = { name: 'test', timeId: 1 }; var file2 = { name: 'test2', timeId: 2 }; var file3 = { name: 'test3', timeId: 3 }; processingProgressTimeoutIds.push({ name: file.name, timerId: file.id }); processingProgressTimeoutIds.push({ name: file2.name, timerId: file2.id }); processingProgressTimeoutIds.push({ name: file3.name, timerId: file3.id }); console.log(JSON.stringify(processingProgressTimeoutIds)); var keyName = 'test'; var match = processingProgressTimeoutIds.filter(function (item) { return item.name === keyName; })[0]; console.log(JSON.stringify(match)); // optimization var match2 = processingProgressTimeoutIds.some(function (element, index, array) { return element.name === keyName; }); console.log(JSON.stringify(match2)); // if you have the full object var match3 = processingProgressTimeoutIds.indexOf(file); console.log(JSON.stringify(match3)); // http://jsperf.com/array-find-equal – from Dave // indexOf is faster, but I need to find it by the key, so I can’t use it here //ES6 will rock though, array comprehension! – also from Dave // var ys = [x of xs if x == 3]; // var y = ys[0]; Here’s a good blog post on Array comprehension.

    Read the article

  • Using foldr to append two lists together (Haskell)

    - by Luke Murphy
    I have been given the following question as part of a college assignment. Due to the module being very short, we are using only a subset of Haskell, without any of the syntactic sugar or idiomatic shortcuts....I must write: append xs ys : The list formed by joining the lists xs and ys, in that order append (5:8:3:[]) (4:7:[]) => 5:8:3:4:7:[] I understand the concept of how foldr works, but I am only starting off in Functional programming. I managed to write the following working solution (hidden for the benefit of others in my class...) : However, I just can't for the life of me, explain what the hell is going on!? I wrote it by just fiddling around in the interpreter, for example, the following line : foldr (\x -> \y -> x:y) [] (2:3:4:[]) which returned [2:3:4] , which led me to try, foldr (\x -> \y -> x:y) (2:3:4:[]) (5:6:7:[]) which returned [5,6,7,2,3,4] so I worked it out from there. I came to the correct solution through guess work and a bit of luck... I am working from the following definition of foldr: foldr = \f -> \s -> \xs -> if null xs then s else f (head xs) (foldr f s (tail xs) ) Can someone baby step me through my correct solution? I can't seem to get it....I already have scoured the web, and also read a bunch of SE threads, such as How foldr works

    Read the article

  • Simplex Noise Help

    - by Alex Larsen
    Im Making A Minecraft Like Gae In XNA C# And I Need To Generate Land With Caves This Is The Code For Simplex I Have /// <summary> /// 1D simplex noise /// </summary> /// <param name="x"></param> /// <returns></returns> public static float Generate(float x) { int i0 = FastFloor(x); int i1 = i0 + 1; float x0 = x - i0; float x1 = x0 - 1.0f; float n0, n1; float t0 = 1.0f - x0 * x0; t0 *= t0; n0 = t0 * t0 * grad(perm[i0 & 0xff], x0); float t1 = 1.0f - x1 * x1; t1 *= t1; n1 = t1 * t1 * grad(perm[i1 & 0xff], x1); // The maximum value of this noise is 8*(3/4)^4 = 2.53125 // A factor of 0.395 scales to fit exactly within [-1,1] return 0.395f * (n0 + n1); } /// <summary> /// 2D simplex noise /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public static float Generate(float x, float y) { const float F2 = 0.366025403f; // F2 = 0.5*(sqrt(3.0)-1.0) const float G2 = 0.211324865f; // G2 = (3.0-Math.sqrt(3.0))/6.0 float n0, n1, n2; // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in float s = (x + y) * F2; // Hairy factor for 2D float xs = x + s; float ys = y + s; int i = FastFloor(xs); int j = FastFloor(ys); float t = (float)(i + j) * G2; float X0 = i - t; // Unskew the cell origin back to (x,y) space float Y0 = j - t; float x0 = x - X0; // The x,y distances from the cell origin float y0 = y - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords if (x0 > y0) { i1 = 1; j1 = 0; } // lower triangle, XY order: (0,0)->(1,0)->(1,1) else { i1 = 0; j1 = 1; } // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords float y1 = y0 - j1 + G2; float x2 = x0 - 1.0f + 2.0f * G2; // Offsets for last corner in (x,y) unskewed coords float y2 = y0 - 1.0f + 2.0f * G2; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds int ii = i % 256; int jj = j % 256; // Calculate the contribution from the three corners float t0 = 0.5f - x0 * x0 - y0 * y0; if (t0 < 0.0f) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii + perm[jj]], x0, y0); } float t1 = 0.5f - x1 * x1 - y1 * y1; if (t1 < 0.0f) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii + i1 + perm[jj + j1]], x1, y1); } float t2 = 0.5f - x2 * x2 - y2 * y2; if (t2 < 0.0f) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii + 1 + perm[jj + 1]], x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return 40.0f * (n0 + n1 + n2); // TODO: The scale factor is preliminary! } public static float Generate(float x, float y, float z) { // Simple skewing factors for the 3D case const float F3 = 0.333333333f; const float G3 = 0.166666667f; float n0, n1, n2, n3; // Noise contributions from the four corners // Skew the input space to determine which simplex cell we're in float s = (x + y + z) * F3; // Very nice and simple skew factor for 3D float xs = x + s; float ys = y + s; float zs = z + s; int i = FastFloor(xs); int j = FastFloor(ys); int k = FastFloor(zs); float t = (float)(i + j + k) * G3; float X0 = i - t; // Unskew the cell origin back to (x,y,z) space float Y0 = j - t; float Z0 = k - t; float x0 = x - X0; // The x,y,z distances from the cell origin float y0 = y - Y0; float z0 = z - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords /* This code would benefit from a backport from the GLSL version! */ if (x0 >= y0) { if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // X Y Z order else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } // X Z Y order else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } // Z X Y order } else { // x0<y0 if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } // Z Y X order else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } // Y Z X order else { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // Y X Z order } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where // c = 1/6. float x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords float y1 = y0 - j1 + G3; float z1 = z0 - k1 + G3; float x2 = x0 - i2 + 2.0f * G3; // Offsets for third corner in (x,y,z) coords float y2 = y0 - j2 + 2.0f * G3; float z2 = z0 - k2 + 2.0f * G3; float x3 = x0 - 1.0f + 3.0f * G3; // Offsets for last corner in (x,y,z) coords float y3 = y0 - 1.0f + 3.0f * G3; float z3 = z0 - 1.0f + 3.0f * G3; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds int ii = i % 256; int jj = j % 256; int kk = k % 256; // Calculate the contribution from the four corners float t0 = 0.6f - x0 * x0 - y0 * y0 - z0 * z0; if (t0 < 0.0f) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii + perm[jj + perm[kk]]], x0, y0, z0); } float t1 = 0.6f - x1 * x1 - y1 * y1 - z1 * z1; if (t1 < 0.0f) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii + i1 + perm[jj + j1 + perm[kk + k1]]], x1, y1, z1); } float t2 = 0.6f - x2 * x2 - y2 * y2 - z2 * z2; if (t2 < 0.0f) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii + i2 + perm[jj + j2 + perm[kk + k2]]], x2, y2, z2); } float t3 = 0.6f - x3 * x3 - y3 * y3 - z3 * z3; if (t3 < 0.0f) n3 = 0.0f; else { t3 *= t3; n3 = t3 * t3 * grad(perm[ii + 1 + perm[jj + 1 + perm[kk + 1]]], x3, y3, z3); } // Add contributions from each corner to get the final noise value. // The result is scaled to stay just inside [-1,1] return 32.0f * (n0 + n1 + n2 + n3); // TODO: The scale factor is preliminary! } private static byte[] perm = new byte[512] { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180, 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; private static int FastFloor(float x) { return (x > 0) ? ((int)x) : (((int)x) - 1); } private static float grad(int hash, float x) { int h = hash & 15; float grad = 1.0f + (h & 7); // Gradient value 1.0, 2.0, ..., 8.0 if ((h & 8) != 0) grad = -grad; // Set a random sign for the gradient return (grad * x); // Multiply the gradient with the distance } private static float grad(int hash, float x, float y) { int h = hash & 7; // Convert low 3 bits of hash code float u = h < 4 ? x : y; // into 8 simple gradient directions, float v = h < 4 ? y : x; // and compute the dot product with (x,y). return ((h & 1) != 0 ? -u : u) + ((h & 2) != 0 ? -2.0f * v : 2.0f * v); } private static float grad(int hash, float x, float y, float z) { int h = hash & 15; // Convert low 4 bits of hash code into 12 simple float u = h < 8 ? x : y; // gradient directions, and compute dot product. float v = h < 4 ? y : h == 12 || h == 14 ? x : z; // Fix repeats at h = 12 to 15 return ((h & 1) != 0 ? -u : u) + ((h & 2) != 0 ? -v : v); } private static float grad(int hash, float x, float y, float z, float t) { int h = hash & 31; // Convert low 5 bits of hash code into 32 simple float u = h < 24 ? x : y; // gradient directions, and compute dot product. float v = h < 16 ? y : z; float w = h < 8 ? z : t; return ((h & 1) != 0 ? -u : u) + ((h & 2) != 0 ? -v : v) + ((h & 4) != 0 ? -w : w); } This Is My World Generation Code Block[,] BlocksInMap = new Block[1024, 256]; public bool IsWorldGenerated = false; Random r = new Random(); private void RunThread() { for (int BH = 0; BH <= 256; BH++) { for (int BW = 0; BW <= 1024; BW++) { Block b = new Block(); if (BH >= 192) { } BlocksInMap[BW, BH] = b; } } IsWorldGenerated = true; } public void GenWorld() { new Thread(new ThreadStart(RunThread)).Start(); } And This Is A Example Of How I Set Blocks Block b = new Block(); b.BlockType = = Block.BlockTypes.Air; This Is A Example Of How I Set Models foreach (Block b in MyWorld) { switch(b.BlockType) { case Block.BlockTypes.Dirt: b.Model = DirtModel; break; ect. } } How Would I Use These To Generate To World (The Block Array) And If Possible Thread It More? btw It's 1024 Wide And 256 Tall

    Read the article

1 2  | Next Page >