private static int[] GetListContoursAdjust(VectorOfVectorOfPoint contours, Size FOV, int NumGet = 3, double MaxArea = 3) { Tuple <double, int>[] cntInfo = new Tuple <double, int> [contours.Size]; for (int i = 0; i < contours.Size; i++) { double s = CvInvoke.ContourArea(contours[i]); cntInfo[i] = new Tuple <double, int>(s, i); } Tuple <double, int>[] sorted = cntInfo.OrderBy(item => item.Item1).ToArray(); List <int> id = new List <int>(); for (int i = sorted.Length - 1; i >= 0; i--) { if (sorted[i].Item1 * 100 / (FOV.Width * FOV.Height) < MaxArea) { if (id.Count <= NumGet) { id.Add(sorted[i].Item2); } else { break; } } } return(id.ToArray()); }
static void Main(string[] args) { var _ = Console.ReadLine().Split(); var n = int.Parse(_[0]); var m = int.Parse(_[1]); var t = new Tuple <int, int, int> [m]; for (var i = 0; i < m; i++) { var __ = Console.ReadLine().Split(); var p = int.Parse(__[0]); var y = int.Parse(__[1]); t[i] = Tuple.Create(i, p, y); } var id = new string[m]; var count = new int[n]; foreach (var x in t.OrderBy(i => i.Item2).ThenBy(i => i.Item3)) { id[x.Item1] = string.Format("{0:D6}{1:D6}", x.Item2, count[x.Item2 - 1] + 1); count[x.Item2 - 1]++; } foreach (var x in id) { Console.WriteLine(x); } }
private void SetClosestIndex(Color color) { ColorMine.ColorSpaces.Rgb rgbColorStop = new ColorMine.ColorSpaces.Rgb() { R = color.R, G = color.G, B = color.B }; Tuple <Color, double, int>[] colorWeights = new Tuple <Color, double, int> [Width]; // Create a color weight for every cell compared to the color stop for (int x = 0; x < Width; x++) { ColorMine.ColorSpaces.Rgb rgbColor = new ColorMine.ColorSpaces.Rgb() { R = this[x, 0].Foreground.R, G = this[x, 0].Foreground.G, B = this[x, 0].Foreground.B }; ColorMine.ColorSpaces.Cmy cmyColor = rgbColor.To <ColorMine.ColorSpaces.Cmy>(); colorWeights[x] = new Tuple <Color, double, int>(this[x, 0].Foreground, rgbColorStop.Compare(cmyColor, new ColorMine.ColorSpaces.Comparisons.Cie1976Comparison()), x); } var foundColor = colorWeights.OrderBy(t => t.Item2).First(); _selectedPosition = foundColor.Item3; this.IsDirty = true; }
public Form1() { InitializeComponent(); result = new Matrix(6); Tuple <int, int>[] pairs = new Tuple <int, int> [n * (n - 1) / 2]; Random rnd = new Random(); int index = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { pairs[index] = new Tuple <int, int>(i, j); index++; } } for (int i = 0; i < n; i++) { result.m[i, i] = 1; } randomPairs = pairs.OrderBy(i => rnd.Next()).ToArray(); nextQuestion(); }
/// <summary> /// Compare y and the iterative selection value /// </summary> /// <param name="x0">x0 start</param> /// <param name="dx">difference</param> /// <param name="y">y to find</param> /// <param name="n">digit n</param> /// <param name="b">coeff b</param> /// <param name="c">coeff c</param> /// <returns>1, 0, -1</returns> private int CompareY(double x0, double dx, double y, out int n, double b, double c) { List <Tuple <int, double> > res; Tuple <int, double>[] tab = new Tuple <int, double> [10]; for (int cnt = 0; cnt < 10; ++cnt) { tab[cnt] = new Tuple <int, double>(cnt, y - this.ComputeY0(x0 + cnt * dx + dx, b, c)); } res = tab.OrderBy(key => key.Item2).ToList(); n = res.ElementAt(0).Item1; if (res.ElementAt(0).Item2 == 0) { return(0); } else if (res.ElementAt(0).Item2 > 0) { return(1); } else { foreach (Tuple <int, double> t in res) { if (t.Item2 >= 0) { n = t.Item1; return(1); } } n = res.ElementAt(9).Item1; return(-1); } }
static void Main(string[] args) { //long[] input = Console.ReadLine().Split().Select(long.Parse).ToArray(); //string S = Console.ReadLine(); long N = long.Parse(Console.ReadLine()); Tuple <long, long>[] t = new Tuple <long, long> [N]; for (int i = 0; i < N; i++) { long[] input = Console.ReadLine().Split().Select(long.Parse).ToArray(); t[i] = Tuple.Create(input[0] - input[1], input[0] + input[1]); } t = t.OrderBy(x => x.Item2).ToArray(); /* * foreach (var item in t) * { * Console.WriteLine("{0} {1}", item.Item1, item.Item2); * } */ long res = 0; long end = int.MinValue; for (int i = 0; i < N; i++) { if (end <= t[i].Item1) { res++; end = t[i].Item2; } } Console.WriteLine(res); }
public int[] KWeakestRows(int[][] mat, int k) { int width = mat[0].Length; int height = mat.GetLength(0); Tuple <int, int>[] arr = new Tuple <int, int> [height]; for (int i = 0; i < height; i++) { int soldierCount = 0; for (int j = 0; j < width; j++) { if (mat[i][j] == 1) { soldierCount++; } } arr[i] = new Tuple <int, int>(i, soldierCount); } int[] newArray = arr.OrderBy(a => a.Item2).ThenBy(b => b.Item1).Select(c => c.Item1).ToArray(); int[] result = new int[k]; Array.Copy(newArray, result, k); return(result); }
private void SetClosestIndex(Color color) { ColorMine.ColorSpaces.Rgb rgbColorStop = new ColorMine.ColorSpaces.Rgb() { R = color.R, G = color.G, B = color.B }; Tuple <Color, double, int>[] colorWeights = new Tuple <Color, double, int> [TextSurface.Cells.Length]; // Create a color weight for every cell compared to the color stop for (int x = 0; x < TextSurface.Cells.Length; x++) { ColorMine.ColorSpaces.Rgb rgbColor = new ColorMine.ColorSpaces.Rgb() { R = this[x].Background.R, G = this[x].Background.G, B = this[x].Background.B }; ColorMine.ColorSpaces.Cmy cmyColor = rgbColor.To <ColorMine.ColorSpaces.Cmy>(); colorWeights[x] = new Tuple <Color, double, int>(this[x].Background, rgbColorStop.Compare(cmyColor, new ColorMine.ColorSpaces.Comparisons.Cie1976Comparison()), x); } var foundColor = colorWeights.OrderBy(t => t.Item2).First(); this[_selectedColorPosition.X, _selectedColorPosition.Y].Glyph = 0; _selectedColorPosition = SadConsole.Surfaces.BasicSurface.GetPointFromIndex(foundColor.Item3, Width); this[_selectedColorPosition.X, _selectedColorPosition.Y].Glyph = 4; this.IsDirty = true; }
public void TestCustomComparer() { Tuple <int, string>[] oriTuples = new Tuple <int, string>[] { Tuple.Create(1, "stasi"), Tuple.Create(2, "cheka") }; var orderByIdQuery = oriTuples.OrderBy(t => t, new ComparerWithId()); CollectionAssert.AreEqual(oriTuples, orderByIdQuery); var orderByNameQuery = oriTuples.OrderBy(t => t, new ComparerWithName()); CollectionAssert.AreEqual(oriTuples.Reverse(), orderByNameQuery); }
void Solve() { //input N = io.Int; var wh = new Tuple <int, int> [N]; for (int i = 0; i < N; ++i) { var w = io.Int; var h = io.Int; wh[i] = Tuple.Create(w, h); } //cal wh = wh.OrderBy(t => t.Item1).ThenByDescending(t => t.Item2).ToArray(); var arr = new int[N + 1]; for (int i = 0; i < arr.Length; ++i) { arr[i] = INF; } for (int i = 0; i < N; ++i) { arr[LowerBound(arr, wh[i].Item2)] = wh[i].Item2; } //ret Console.WriteLine(LowerBound(arr, INF)); }
private void RandomDiceRoll(Player player) { var diceDict = DiceValues.Dice; player.DiceRolled = new Tuple <string, int> [3][]; Random random = new Random(); var pokerRules = new PokerRules(); for (int i = 1; i <= 3; i++) { var handArray = new Tuple <string, int> [5]; Console.WriteLine($"{player.Name} press enter to take dice roll number {i}"); Console.ReadLine(); for (int j = 0; j <= 4; j++) { var randomDice = diceDict.ElementAt(random.Next(0, diceDict.Count)).Key; handArray[j] = Tuple.Create(randomDice, diceDict[randomDice]); } player.DiceRolled[i - 1] = handArray.OrderBy(x => x.Item2).ToArray(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"{player.Name} rolled {player.DiceRolled[i - 1][0].Item1}, " + $"{player.DiceRolled[i - 1][1].Item1}, " + $"{player.DiceRolled[i - 1][2].Item1}, " + $"{player.DiceRolled[i - 1][3].Item1}, " + $"{player.DiceRolled[i - 1][4].Item1}"); Console.ResetColor(); pokerRules.FindMatchingDice(player.DiceRolled[i - 1]); } Console.WriteLine(); }
public int[] SmallestRange(IList <IList <int> > nums) { var len = nums.Sum(o => o.Count); var arr = new Tuple <int, int> [len]; var arri = 0; for (int i = 0; i < nums.Count; i++) { for (int j = 0; j < nums[i].Count; j++) { arr[arri++] = new Tuple <int, int>(nums[i][j], i); } } arr = arr.OrderBy(o => o.Item1).ToArray(); int li = 0, ri = 0; var kns = new int[nums.Count]; int cnt = 0; int min = int.MaxValue; var ans = new int[2]; while (ri < len) { while (cnt < nums.Count && ri < len) { var idx = arr[ri++].Item2; if (kns[idx] == 0) { cnt += 1; } kns[idx] += 1; } if (cnt != nums.Count) { break; } while (li < ri) { var idx = arr[li].Item2; kns[idx] -= 1; if (kns[idx] == 0) { if (min > arr[ri - 1].Item1 - arr[li].Item1) { min = arr[ri - 1].Item1 - arr[li].Item1; ans[0] = arr[li].Item1; ans[1] = arr[ri - 1].Item1; } cnt -= 1; li += 1; break; } li += 1; } } return(ans); }
/// <summary>Predicts the given o.</summary> /// <param name="y">The Vector to process.</param> /// <returns>An object.</returns> public override double Predict(Vector y) { var distances = new Tuple<int, double>[this.X.Rows]; // happens per slot so we are good to parallelize Parallel.For(0, this.X.Rows, i => distances[i] = new Tuple<int, double>(i, (y - this.X.Row(i)).Norm(2))); var slice = distances.OrderBy(t => t.Item2).Take(this.K).Select(i => i.Item1); return this.Y.Slice(slice).Mode(); }
/// <summary>Predicts the given o.</summary> /// <param name="y">The Vector to process.</param> /// <returns>An object.</returns> public override double Predict(Vector y) { var distances = new Tuple <int, double> [this.X.Rows]; // happens per slot so we are good to parallelize Parallel.For(0, this.X.Rows, i => distances[i] = new Tuple <int, double>(i, (y - this.X.Row(i)).Norm(2))); var slice = distances.OrderBy(t => t.Item2).Take(this.K).Select(i => i.Item1); return(this.Y.Slice(slice).Mode()); }
public void OrderByWithPropertyReturnsProperlyOrderedResult() { var items = new Tuple <string, int>[] { new Tuple <string, int>("2", 2), new Tuple <string, int>("3", 3), new Tuple <string, int>("1", 1) }; var sortedItems = items.OrderBy((t) => t.Item1); Assert.True(items.AsQueryable <Tuple <string, int> >().OrderBy("Item1").SequenceEqual(sortedItems)); }
public void Save(Stream output) { using (var bw = new BinaryWriterX(output)) { // Collect all file entries var fileEntries = new Tuple <FileEntry, FF1DpkArchiveFileInfo> [Files.Count]; var fileEntryPosition = 0; foreach (var file in Files) { var fileName = file.FileName.Substring(0, Math.Min(0x16, file.FileName.Length)); var fileNameSum = fileName.Sum(x => (byte)x); var fileEntry = new FileEntry { fileName = fileName, nameSum = (short)fileNameSum, uncompressedSize = (int)file.FileSize }; fileEntries[fileEntryPosition++] = new Tuple <FileEntry, FF1DpkArchiveFileInfo>(fileEntry, file); } // Write file data ordered file entries name sums fileEntries = fileEntries.OrderBy(x => x.Item1.nameSum).ToArray(); var filesOffset = 0x80 + Files.Count * 0x80; foreach (var fileEntryTuple in fileEntries) { bw.BaseStream.Position = filesOffset; fileEntryTuple.Item2.WriteFile(output); fileEntryTuple.Item1.fileOffset = filesOffset; fileEntryTuple.Item1.compressedSize = (int)bw.BaseStream.Position - filesOffset; bw.WriteAlignment(0x80); filesOffset = (int)bw.BaseStream.Position; } // Write file entries ordered by file sum bw.BaseStream.Position = 0x80; foreach (var fileEntry in fileEntries) { WriteFileEntry(bw, fileEntry.Item1); bw.WriteAlignment(0x80); } // Header bw.BaseStream.Position = 0; bw.Write(Files.Count); bw.Write((int)bw.BaseStream.Length); } }
public override void Invoke(CancellationToken cancellationToken) { // Get the range for the current snapshot ITextSnapshot snapshot = _textView.TextSnapshot; SnapshotPoint target = _target.TranslateTo(snapshot, PointTrackingMode.Positive); int startLineIndex = snapshot.GetLineNumberFromPosition(target); int endLineIndex = startLineIndex; // Find first #include of block while (startLineIndex > 0 && LineIsInclude(snapshot, startLineIndex - 1)) { startLineIndex--; } // Find last #include of block while (endLineIndex < snapshot.LineCount - 1 && LineIsInclude(snapshot, endLineIndex + 1)) { endLineIndex++; } // Get includes int numIncludeLines = endLineIndex - startLineIndex + 1; var lines = new Tuple <string, string> [numIncludeLines]; for (int i = startLineIndex; i <= endLineIndex; i++) { ITextSnapshotLine line = snapshot.GetLineFromLineNumber(i); string lineText = line.GetText(); string includePath = GetIncludePath(snapshot, lineText); lines[i - startLineIndex] = new Tuple <string, string>(lineText, includePath); } // Sort (use LINQ as its stable) lines = lines.OrderBy(x => x.Item2.StartsWith("<") ? 0 : 1) .ThenBy(x => x.Item2) .ToArray(); // Replace the lines with the new sorted lines ITextSnapshotLine startLine = snapshot.GetLineFromLineNumber(startLineIndex); ITextSnapshotLine endLine = snapshot.GetLineFromLineNumber(endLineIndex); string newLineChar = _textView.Options.GetNewLineCharacter(); using (ITextEdit edit = _textBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, null)) { var replaceSpan = Span.FromBounds(startLine.Start, endLine.End); string replaceText = String.Join(newLineChar, lines.Select(x => x.Item1)); edit.Replace(replaceSpan, replaceText); edit.Apply(); } }
private void AddKeys() { if (_keyProperties.Count == 0) { PropertyInfo key = _clrType.GetPropertyIgnoreCase("id"); if (key != null) { var edmProperty = (EdmStructuralProperty)_edmType.Properties().Single(p => p.Name == key.Name); _keyProperties.Add(new KeyValuePair <PropertyInfo, EdmStructuralProperty>(key, edmProperty)); } else { key = _clrType.GetPropertyIgnoreCase(_clrType.Name + "id"); if (key == null) { if (EdmType.Key().Any()) { return; } throw new InvalidOperationException("Key property not matching"); } var edmProperty = (EdmStructuralProperty)_edmType.Properties().Single(p => p.Name == key.Name); _keyProperties.Add(new KeyValuePair <PropertyInfo, EdmStructuralProperty>(key, edmProperty)); } } if (_keyProperties.Count == 1) { _edmType.AddKeys(_keyProperties[0].Value); return; } var keys = new Tuple <EdmStructuralProperty, int> [_keyProperties.Count]; for (int i = 0; i < _keyProperties.Count; i++) { int order = _metadataProvider.GetOrder(_keyProperties[i].Key); if (order == -1) { _edmType.AddKeys(_keyProperties.Select(p => p.Value)); return; } keys[i] = new Tuple <EdmStructuralProperty, int>(_keyProperties[i].Value, order); } _edmType.AddKeys(keys.OrderBy(p => p.Item2).Select(p => p.Item1)); }
protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint) { var childrenCount = Children.Count; var desiredWidth = 0.0; var height = 0.0; var mustWidth = constraint.Width; var widths = new Tuple <int, double> [childrenCount]; var size = new System.Windows.Size(double.PositiveInfinity, constraint.Height); for (int i = 0; i < childrenCount; i++) { var child = Children[i]; child.Measure(size); var width = child.DesiredSize.Width + 1.0; height = Math.Max(height, child.DesiredSize.Height); desiredWidth += width; widths[i] = Tuple.Create(i, width); } _newWidths = new double[childrenCount]; if (mustWidth > 0 && desiredWidth > mustWidth) { // Переполнение, нужно ужаться desiredWidth = mustWidth; var left = childrenCount; foreach (var item in widths.OrderBy(t => t.Item2)) { var newWidth = Math.Min(item.Item2, mustWidth / left); _newWidths[item.Item1] = newWidth; mustWidth -= newWidth; Children[item.Item1].Measure(new System.Windows.Size(newWidth, height)); left--; } } else { for (int i = 0; i < childrenCount; i++) { _newWidths[i] = widths[i].Item2; } } return(new System.Windows.Size(desiredWidth, height)); }
public static Color GetBloomColor() { var tex = Shader.GetGlobalTexture("_BloomPrePassTexture"); if (tex == null) { return(Color.white); } if (colorTex == null || colorRenderTex == null || colorTex.width != tex.width || colorTex.height != tex.height || colorRenderTex.width != tex.width || colorRenderTex.height != tex.height) { colorTex = new Texture2D(tex.width, tex.height, TextureFormat.RGBA32, false); colorRenderTex = new RenderTexture(tex.width, tex.height, 32); } var currentRT = RenderTexture.active; Graphics.Blit(tex, colorRenderTex); RenderTexture.active = colorRenderTex; colorTex.ReadPixels(new Rect(0, 0, colorRenderTex.width, colorRenderTex.height), 0, 0); colorTex.Apply(); var color1 = colorTex.GetPixel(colorTex.width / 3, colorTex.height - 1); var color2 = colorTex.GetPixel(colorTex.width / 3 * 2, colorTex.height - 1); var color3 = colorTex.GetPixel(colorTex.width / 3, 0); var color4 = colorTex.GetPixel(colorTex.width / 3 * 2, 0); var color5 = colorTex.GetPixel(colorTex.width / 3, colorTex.height / 2); var color6 = colorTex.GetPixel(colorTex.width / 3 * 2, colorTex.height / 2); var colors = new Tuple <Color, float>[] { Tuple.Create(color1, color1.grayscale), Tuple.Create(color2, color2.grayscale), Tuple.Create(color3, color3.grayscale), Tuple.Create(color4, color4.grayscale), Tuple.Create(color5, color5.grayscale), Tuple.Create(color6, color6.grayscale) }; var color = colors.OrderBy(t => t.Item2).ElementAt(1).Item1; RenderTexture.active = currentRT; return(color); }
private Tuple <float, bool>[] GenerateAnswers(Operator op, Tuple <float, float> operands) { float correctAnswer = GetCalculator(op)(operands.Item1, operands.Item2); // If the difficulty is easy or medium, return the set of answers { correctAnswer - 1, correctAnswer, correctAnswer + 1) if (difficulty == Difficulty.EASY || difficulty == Difficulty.MEDIUM) { return((new Tuple <float, bool>[] { new Tuple <float, bool>((correctAnswer - 1) < 0 ? correctAnswer + 2 : correctAnswer - 1, false), new Tuple <float, bool>(correctAnswer, true), new Tuple <float, bool>(correctAnswer + 1, false) }).OrderBy(x => Guid.NewGuid()).ToArray()); } Tuple <float, bool>[] correctAnswers = new Tuple <float, bool>[3] { new Tuple <float, bool>(correctAnswer, true), null, null }; // If the difficulty is hard // Do not allow the player to get the answer based on the last digit switch (op) { case Operator.ADD: case Operator.MUL: correctAnswers[1] = new Tuple <float, bool>(correctAnswer + 10, false); correctAnswers[2] = new Tuple <float, bool>(correctAnswer - (random.Next(9) + 1), false); break; case Operator.SUB: if (correctAnswer - 10 < 0) { correctAnswers[1] = new Tuple <float, bool>(correctAnswer + (random.Next(9) + 1), false); correctAnswers[2] = new Tuple <float, bool>(correctAnswer - (random.Next((int)correctAnswer) + 1), false); } else { correctAnswers[1] = new Tuple <float, bool>(correctAnswer - 10, false); correctAnswers[2] = new Tuple <float, bool>(correctAnswer - (random.Next(9) + 1), false); } break; default: correctAnswers[1] = new Tuple <float, bool>(correctAnswer + 10, false); correctAnswers[2] = new Tuple <float, bool>((correctAnswer - 10 < 0) ? (correctAnswer + (random.Next(9) + 1)) : correctAnswer - 10, false); break; } // Shuffle the set of answers return(correctAnswers.OrderBy(x => Guid.NewGuid()).ToArray()); }
public static (IList <IList <IPassenger> > vehicles, double totalDistance) CalculateMultipleCarsPathForSmallestDistanceTraveled(GeoLoc startingPoint, List <IPassenger> allPassengers, List <Distance> allDistances) { IEnumerable <IList <IList <IPassenger> > > partitions = allPassengers.Partitions(); int partitionCount = partitions.Count(); var partitionIndexAndItsDistance = new Tuple <int, double> [partitionCount]; var vehiclesWithDistances = new HashSet <Vehicle>(); for (int i = 0; i < partitionCount; i++) //Parallel.For(0, partitions.Count(), i => { IList <IList <IPassenger> > groups = partitions.ElementAt(i); double totalDistance = 0; foreach (var passengers in groups) { var vehicle = new Vehicle(startingPoint, passengers, allDistances); Vehicle withDistance; bool isFound = vehiclesWithDistances.TryGetValue(vehicle, out withDistance); if (isFound) { totalDistance += withDistance.GetDistance(); } else { totalDistance += vehicle.GetDistance(); vehiclesWithDistances.Add(vehicle); } } partitionIndexAndItsDistance[i] = new Tuple <int, double>(i, totalDistance); Console.SetCursorPosition(0, 1); Console.Write(partitionCount + " - " + i); } ; var winner = partitionIndexAndItsDistance.OrderBy(i => i.Item2).First(); return(vehicles : partitions.ElementAt(winner.Item1), totalDistance : winner.Item2); }
public override double Predict(Vector y) { Tuple<int, double>[] distances = new Tuple<int, double>[y.Length]; //for (int i = 0; i < X.RowCount; i++) // distance (y - x[i]).Norm // distances[i] = new Tuple<int, double>(i, (y - X.Row(i)).Norm(2)); // happens per slot so we are good to parallelize Parallel.For(0, X.Rows, i => distances[i] = new Tuple<int, double>(i, (y - X.Row(i)).Norm(2))); var slice = distances .OrderBy(t => t.Item2) .Take(K) .Select(i => i.Item1); return Y.Slice(slice).Mode(); }
void Solve() { io.i(out N); io.ini(out W, out H, N); var pair = new Tuple <int, int> [N]; N.REP(i => pair[i] = Tuple.Create(W[i], H[i])); pair = pair.OrderBy(t => t.Item1).ThenByDescending(t => t.Item2).ToArray(); var arr = new int[N + 1]; arr.Set((int)1e9); N.REP(i => { lb = -1; ub = N; while (ub - lb > 1) { int mid = (lb + ub) / 2; if (arr[mid] >= pair[i].Item2) { ub = mid; } else { lb = mid; } } arr[ub] = pair[i].Item2; }); lb = -1; ub = N; while (ub - lb > 1) { int mid = (lb + ub) / 2; if (arr[mid] >= (int)1e9) { ub = mid; } else { lb = mid; } } io.o(ub); }
static void Main(string[] args) { int N = Input.Int(); var tpl = new Tuple <string, int, int> [N]; for (int i = 0; i < N; i++) { string[] s = Console.ReadLine().Split(' '); tpl[i] = Tuple.Create(s[0], int.Parse(s[1]), i + 1); } var ans1 = tpl.OrderBy(x => x.Item1); var ans2 = ans1.ThenByDescending(x => x.Item2); foreach (var item in ans2) { Console.WriteLine(item.Item3); } }
/// <summary>Predicts the given o.</summary> /// <param name="y">The Vector to process.</param> /// <returns>An object.</returns> public override double Predict(Vector y) { this.Preprocess(y); Tuple<int, double>[] distances = new Tuple<int, double>[X.Rows]; // happens per slot so we are good to parallelize for (int i = 0; i < X.Rows; i++) { distances[i] = new Tuple<int, double>(i, (y - X.Row(i)).Norm(2)); } var slice = distances .OrderBy(t => t.Item2) .Take(K) .Select(i => i.Item1); return Y.Slice(slice).Mode(); }
// Returns an array of (data.GetLength(0)) by (remaining + 1) of double public override double[][] FilterTrainingData(double[][] data, uint remaining) { uint _vectorNumber = (uint)data.Length; uint _vectorSize = (uint)data[0].Length; // Sets the remaining to the (length of the vector - 1) if (remaining > _vectorSize - 1) { remaining = _vectorSize - 1; } else if (remaining == 0) { throw new Exception("No. The Great Correlation Goat does not approve of you not passing number of remaining columns (or passing a 0)."); } // Creates an array of coefficients between (n-th column) and (the last column) double[] coefficientsArray = Coefficient(data); // Copies the array to a tuple (absolute value of coefficient[i], index of that particulr column) Tuple <double, int>[] coefficients = new Tuple <double, int> [_vectorSize - 1]; for (int i = 0; i < _vectorSize - 1; i++) { coefficients[i] = new Tuple <double, int>(Math.Abs(coefficientsArray[i]), i); } // Orders them by the coefficient coefficients = coefficients.OrderBy(i => i.Item1).ToArray(); _filter = new bool[_vectorSize]; for (int i = 0; i < _filter.Length; i++) { _filter[i] = false; } for (int i = 0; i < remaining; i++) { _filter[coefficients[i].Item2] = true; } _filter[_vectorSize - 1] = true; return(FilterTestData(data)); }
/// <summary>Predicts the given o.</summary> /// <param name="y">The Vector to process.</param> /// <returns>An object.</returns> public override double Predict(Vector y) { Preprocess(y); var distances = new Tuple <int, double> [X.Rows]; // happens per slot so we are good to parallelize for (var i = 0; i < X.Rows; i++) { distances[i] = new Tuple <int, double>(i, (y - X.Row(i)).Norm(2)); } var slice = distances .OrderBy(t => t.Item2) .Take(K) .Select(i => i.Item1); return(Y.Slice(slice).Mode()); }
public static Tuple <int, string, int, DateTime>[] GetTopScores(int seed, int numScores) { //public getter method that reads the top numScores scores from the file and returns them //first we need to read in the scores String[] scores = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "/saved_scores.txt"); Tuple <int, string, int, DateTime>[] tupleScores = new Tuple <int, string, int, DateTime> [scores.Count()]; //now we need to iterate over the scores, turn them into tuples for (int i = 0; i < scores.Count(); i++) { string[] splitString = scores[i].Split(':'); Tuple <int, string, int, DateTime> score = Tuple.Create(int.Parse(splitString[0]), splitString[1], int.Parse(splitString[2]), DateTime.Parse(splitString[3])); tupleScores[i] = (score); } //now we sort the list //code for sorting from MSDN, found here: //https://msdn.microsoft.com/en-us/library/bb534966(v=vs.110).aspx //also filtering out results with With keyword, code for that found here: //https://stackoverflow.com/questions/22449888/filtering-a-tuple-based-on-item-3-in-the-tuple?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa tupleScores.OrderBy(tuple => tuple.Item1).Where(tuple => tuple.Item3 == seed); Tuple <int, string, int, DateTime>[] topTupleScores = new Tuple <int, string, int, DateTime> [numScores]; int j = 0; foreach (Tuple <int, string, int, DateTime> tuple in tupleScores.Take(numScores)) { topTupleScores[j] = tuple; j++; } //in case there aren't enough scores for the daily scoreboard, we'll pad it with junk values while (j < numScores - 1) { topTupleScores[j] = new Tuple <int, string, int, DateTime>(int.MaxValue, "", 0, DateTime.MinValue); } return(topTupleScores); }
public static List <int> computePrices(List <int> s, List <int> p, List <int> q) { var result = new List <int>(q.Count); var tuples = new Tuple <int, int> [s.Count]; for (int i = 0; i < s.Count; i++) { var temp = new Tuple <int, int>(s[i], p[i]); tuples[i] = temp; } tuples = tuples.OrderBy(x => x.Item1).ToArray(); foreach (var query in q) { result.Add(BinarySearchClosestStock(tuples, query)); } return(result); }
public static string Execute(int[] iceCreamRawValues, int money) { var iceCreamValues = new Tuple <int, int> [iceCreamRawValues.Length]; for (int i = 0; i < iceCreamRawValues.Length; i++) { iceCreamValues[i] = Tuple.Create(iceCreamRawValues[i], i + 1); } iceCreamValues = iceCreamValues.OrderBy(x => x.Item1).ToArray(); for (int i = 0; i < iceCreamValues.Length; i++) { var residualMoney = money - iceCreamValues[i].Item1; var found = BinarySearch(iceCreamValues, residualMoney, i + 1, iceCreamValues.Length - 1); if (found != null) { return(iceCreamValues[i].Item2 < found.Item2 ? $"{iceCreamValues[i].Item2} {found.Item2}" : $"{found.Item2} {iceCreamValues[i].Item2}"); } } throw new InvalidOperationException("It is guaranteed that there will always be a unique solution"); }
public int solution(int[] A) { // write your code in C# 6.0 with .NET 4.5 (Mono) //if sum of any two elements > a single element //return 1 //else return 0; //if any two elements after the smallest sum Tuple <int, long>[] tuplesArray = new Tuple <int, long> [A.Length]; for (int i = 0; i < A.Length; i++) { tuplesArray[i] = new Tuple <int, long>(i, A[i]); } tuplesArray = tuplesArray.OrderBy(x => x.Item2).ToArray(); double sumA = 0; double sumB = 0; double sumC = 0; for (int i = 0; i < A.Length - 2; i++) { for (int j = i + 1; j < A.Length - 1 && tuplesArray[j].Item1 > tuplesArray[i].Item1; j++) { for (int k = j + 1; k < A.Length && tuplesArray[k].Item1 > tuplesArray[j].Item1; k++) { sumA = tuplesArray[i].Item2 + tuplesArray[j].Item2; sumB = tuplesArray[k].Item2 + tuplesArray[j].Item2; sumC = tuplesArray[i].Item2 + tuplesArray[k].Item2; if (sumA > tuplesArray[k].Item2 && sumB > tuplesArray[i].Item2 && sumC > tuplesArray[j].Item2) { return(1); } } } } return(0); }
public int solution(int[] A) { // write your code in C# 6.0 with .NET 4.5 (Mono) // max J + A[J] // min J - A[j] //pair intersect if // J != K // if J < K // intersect if // Max J > min K // if J > K // intersect if // Min J < Max K // first will intersect with all // if 0 + A[0] > k - A[k] Tuple <int, long, long>[] tuplesArray = new Tuple <int, long, long> [A.Length]; for (long i = 0; i < A.Length; i++) { tuplesArray[i] = new Tuple <int, long, long>(A[i], i - A[i], i + A[i]); } tuplesArray = tuplesArray.OrderBy(x => x.Item2).ToArray(); int counter = 0; for (int i = 0; i < A.Length - 1; i++) { for (int j = i + 1; j < A.Length && tuplesArray[j].Item2 <= tuplesArray[i].Item3; j++) { counter += 1; if (counter > 10000000) { return(-1); } } } return(counter); }
private Expression BuildIndexExpression(SqlTableExpression table, string indexName, Tuple<IndexAttribute, PropertyDescriptor>[] properties) { var unique = properties.Select(c => c.Item1).Any(c => c.Unique); var lowercaseIndex = properties.Select(c => c.Item1).Any(c => c.LowercaseIndex); var indexType = properties.Select(c => c.Item1.IndexType).FirstOrDefault(c => c != IndexType.Default); var sorted = properties.OrderBy(c => c.Item1.CompositeOrder, Comparer<int>.Default); var indexedColumns = new List<SqlIndexedColumnExpression>(); foreach (var attributeAndProperty in sorted) { foreach (var columnInfo in QueryBinder.GetColumnInfos(this.model.TypeDescriptorProvider, attributeAndProperty.Item2)) { indexedColumns.Add(new SqlIndexedColumnExpression(new SqlColumnExpression(columnInfo.DefinitionProperty.PropertyType, null, columnInfo.ColumnName), attributeAndProperty.Item1.SortOrder, attributeAndProperty.Item1.LowercaseIndex)); } } return new SqlCreateIndexExpression(indexName, table, unique, lowercaseIndex, indexType, false, indexedColumns); }
protected virtual RgbSpectrum SamplePath1(int x, int y) { float lambda; Tuple<float, float>[] c = new Tuple<float, float>[MaxSpectralSamples]; float dLambda = (SampledSpectrum.sampledLambdaEnd - SampledSpectrum.sampledLambdaStart) / ((float)MaxSpectralSamples + 1f); for (int l = 0; l < MaxSpectralSamples; l++) { lambda = SampleWavelength(rnd.NextFloat()); RayData cameraRay; Scene.GenerateCameraRay(x, y, out cameraRay); var pix = EvalRadiance(ref cameraRay, lambda, 0); totalSamples++; c[l] = new Tuple<float, float>(lambda, pix); //lambda += dLambda; } c = c.OrderBy(item => item.Item1).ToArray(); var lms = c.Select(p => p.Item1).ToArray(); var vals = c.Select(p => p.Item2).ToArray(); var spd = new IrregularSPD(lms, vals, MaxSpectralSamples, dLambda); //RegularSPD spd = new RegularSPD(vals, SampledSpectrum.sampledLambdaStart, SampledSpectrum.sampledLambdaEnd, MaxSpectralSamples); var pixV = spd.ToRgb(); return pixV; }
private static void DrawNNOutputs(UniformGrid panel, Tuple<LifeEventType, double>[] outputs) { // Keep them sorted so that it's consistent frame to frame (make sure they don't jump around) outputs = outputs. OrderBy(o => o.Item1.ToString()). ToArray(); foreach (var nnout in outputs) { #region OLD //Grid grid = new Grid() //{ // Margin = new Thickness(2), //}; //grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(nnout.Item2, GridUnitType.Star) }); //grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1 - nnout.Item2, GridUnitType.Star) }); //// Filled % //Border border = new Border() //{ // Background = Brushes.DarkTurquoise, // CornerRadius = new CornerRadius(0), // HorizontalAlignment = HorizontalAlignment.Stretch, // VerticalAlignment = VerticalAlignment.Stretch, //}; //Grid.SetColumn(border, 0); //grid.Children.Add(border); //// Remainder //border = new Border() //{ // Background = Brushes.Teal, // CornerRadius = new CornerRadius(0), // HorizontalAlignment = HorizontalAlignment.Stretch, // VerticalAlignment = VerticalAlignment.Stretch, //}; //Grid.SetColumn(border, 1); //grid.Children.Add(border); //// Outline //border = new Border() //{ // BorderBrush = Brushes.Coral, // BorderThickness = new Thickness(1), // CornerRadius = new CornerRadius(0), // HorizontalAlignment = HorizontalAlignment.Stretch, // VerticalAlignment = VerticalAlignment.Stretch, //}; //Grid.SetColumn(border, 0); //Grid.SetColumnSpan(border, 2); //grid.Children.Add(border); //// Text //TextBlock text = new TextBlock() //{ // Text = string.Format("{0} {1}", nnout.Item1, (nnout.Item2 * 100).ToInt_Round()), // Padding = new Thickness(6, 4, 6, 4), // HorizontalAlignment = HorizontalAlignment.Center, // VerticalAlignment = VerticalAlignment.Center, //}; //Grid.SetColumn(text, 0); //Grid.SetColumnSpan(text, 2); //grid.Children.Add(text); #endregion panel.Children.Add(GetNNOutputBar(nnout.Item1.ToString(), nnout.Item2)); } }
public override sealed void Advance(RayBuffer rayBuffer, SampleBuffer consumer) { int currentTriangleIndex = 0; #if VERBOSE try { #endif if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) && (tracedShadowRayCount > 0)) { for (int i = 0; i < tracedShadowRayCount; ++i) { RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].ShadowRayIndex]; RgbSpectrum attenuation; bool continueTrace; if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].ShadowRay, out attenuation, out continueTrace)) { // Radiance.MADD() Radiance += attenuation * ((secRays[i].Throughput) / secRays[i].Pdf); pathWeight *= secRays[i].Pdf; } } if (PathState == PathTracerPathState.ShadowRaysOnly) { Splat(consumer); return; } tracedShadowRayCount = 0; } RayHit rayHit = rayBuffer.rayHits[RayIndex]; Vector wo = -PathRay.Dir; depth++; bool missed = rayHit.Index == 0xffffffffu; if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth) { if (missed) { Radiance += this.scene.SampleEnvironment(ref wo) * Throughput; } Splat(consumer); return; } // Something was hit if (hitInfo == null) { hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit); } else { SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo); } currentTriangleIndex = (int)rayHit.Index; if (hitInfo == null) { Debugger.Break(); } //If Hit light) if (hitInfo.IsLight) { if (specularBounce || depth == 1) { var lt = scene.GetLightByIndex(currentTriangleIndex); if (lt != null) { var le = (RgbSpectrum)(lt.Le(ref wo)); Radiance += Throughput * le; } } Splat(consumer); return; } var hitPoint = PathRay.Point(rayHit.Distance); tracedShadowRayCount = 0; var bsdf = hitInfo.MMaterial; if (!hitInfo.TextureData.Alpha.IsBlack()) { Throughput *= (RgbSpectrum.UnitSpectrum() - (RgbSpectrum) hitInfo.TextureData.Alpha); PathRay = new RayData(hitPoint, -wo); return; } if (bsdf.IsDiffuse()) { float lightStrategyPdf = LightSampler.StrategyPdf; //scene.ShadowRaysPerSample/(float)scene.Lights.Length; RgbSpectrum lightTroughtput = Throughput * hitInfo.Color; int rs = 0; @lstart: LightSampler.EvaluateShadow(ref hitPoint, ref hitInfo.Normal, Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls); for (int index = 0; index < ls.Length; index++) { if (ls[index].Pdf <= 0f) continue; secRays[tracedShadowRayCount].Throughput = (RgbSpectrum)(ls[index].Spectrum); secRays[tracedShadowRayCount].Pdf = ls[index].Pdf; secRays[tracedShadowRayCount].ShadowRay = ls[index].LightRay; Vector lwi = secRays[tracedShadowRayCount].ShadowRay.Dir; RgbSpectrum fs; hitInfo.MMaterial.f(ref secRays[tracedShadowRayCount].ShadowRay.Dir, ref wo, ref hitInfo.ShadingNormal, ref Throughput, out fs, types: BrdfType.Diffuse); secRays[tracedShadowRayCount].Throughput *= lightTroughtput * Vector.AbsDot(ref hitInfo.Normal, ref lwi) * fs; if (!secRays[tracedShadowRayCount].Throughput.IsBlack()) { secRays[tracedShadowRayCount].Pdf /= lightStrategyPdf; tracedShadowRayCount++; } } if (tracedShadowRayCount == 0 && rs < lightResampling) { rs++; goto @lstart; } if (rs > 0) { for (int index = 0; index < secRays.Length; index++) { secRays[index].Pdf /= (1f+rs); } } } float fPdf = 0f; var wi = new Vector(); RgbSpectrum f; if (depth > 1) { f = bsdf.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput, Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), ref hitInfo.TextureData, out fPdf, out specularBounce); } else { int samplesCount = 4; var bsdfData = new Tuple<Vector, float, RgbSpectrum>[samplesCount]; var totalF = new RgbSpectrum(); float totalPdf =0; for (int i = 0; i < samplesCount; i++) { Vector Wi; float pdf; var Fr = bsdf.Sample_f(ref wo, out Wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput, Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), ref hitInfo.TextureData, out pdf, out specularBounce); totalF += Fr; totalPdf += pdf; bsdfData[i] = new Tuple<Vector, float, RgbSpectrum>(Wi, pdf, Fr); } var bsdfSamples = bsdfData.OrderBy(i => i.Item2).ToArray(); fPdf = bsdfSamples[0].Item2; wi = bsdfSamples[0].Item1; f = totalF/4f; } if ((fPdf <= 0.0f) || f.IsBlack()) { if (tracedShadowRayCount > 0) PathState = PathTracerPathState.ShadowRaysOnly; else { Splat(consumer); } return; } pathWeight *= fPdf; Throughput *= (f * hitInfo.Color) / fPdf; if (depth > scene.MaxPathDepth) { float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap); if (prob >= Sample.GetLazyValue()) { Throughput /= prob; pathWeight *= prob; } else { if (tracedShadowRayCount > 0) PathState = PathTracerPathState.ShadowRaysOnly; else { Splat(consumer); } return; } } PathRay.Org = hitPoint; PathRay.Dir = wi.Normalize(); PathState = PathTracerPathState.NextVertex; #if VERBOSE } catch (Exception ex) { RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception"); RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex); RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message); RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace); } #endif }
private void SetClosestIndex(Color color) { ColorMine.ColorSpaces.Rgb rgbColorStop = new ColorMine.ColorSpaces.Rgb() { R = color.R, G = color.G, B = color.B }; Tuple<Color, double, int>[] colorWeights = new Tuple<Color, double, int>[textSurface.Cells.Length]; // Create a color weight for every cell compared to the color stop for (int x = 0; x < textSurface.Cells.Length; x++) { ColorMine.ColorSpaces.Rgb rgbColor = new ColorMine.ColorSpaces.Rgb() { R = this[x].Background.R, G = this[x].Background.G, B = this[x].Background.B }; ColorMine.ColorSpaces.Cmy cmyColor = rgbColor.To<ColorMine.ColorSpaces.Cmy>(); colorWeights[x] = new Tuple<Color, double, int>(this[x].Background, rgbColorStop.Compare(cmyColor, new ColorMine.ColorSpaces.Comparisons.Cie1976Comparison()), x); } var foundColor = colorWeights.OrderBy(t => t.Item2).First(); this[_selectedColorPosition.X, _selectedColorPosition.Y].GlyphIndex = 0; _selectedColorPosition = SadConsole.Consoles.TextSurface.GetPointFromIndex(foundColor.Item3, Width); this[_selectedColorPosition.X, _selectedColorPosition.Y].GlyphIndex = 4; this.IsDirty = true; }
private void SetClosestIndex(Color color) { ColorMine.ColorSpaces.Rgb rgbColorStop = new ColorMine.ColorSpaces.Rgb() { R = color.R, G = color.G, B = color.B }; Tuple<Color, double, int>[] colorWeights = new Tuple<Color, double, int>[Width]; // Create a color weight for every cell compared to the color stop for (int x = 0; x < Width; x++) { ColorMine.ColorSpaces.Rgb rgbColor = new ColorMine.ColorSpaces.Rgb() { R = this[x, 0].Foreground.R, G = this[x, 0].Foreground.G, B = this[x, 0].Foreground.B }; ColorMine.ColorSpaces.Cmy cmyColor = rgbColor.To<ColorMine.ColorSpaces.Cmy>(); colorWeights[x] = new Tuple<Color, double, int>(this[x, 0].Foreground, rgbColorStop.Compare(cmyColor, new ColorMine.ColorSpaces.Comparisons.Cie1976Comparison()), x); } var foundColor = colorWeights.OrderBy(t => t.Item2).First(); _selectedPosition = foundColor.Item3; this.IsDirty = true; }
public override void Compose() { if (this.IsDirty) { this.Fill(Color.White, Color.Black, 0, null); _positions = Width; ColorGradient gradient = new ColorGradient(Color.Red, Color.Yellow, Color.Green, Color.Turquoise, Color.Blue, Color.Purple, Color.Red); for (int x = 0; x < Width; x++) { this[x, 0].GlyphIndex = 219; this[x, 0].Foreground = gradient.Lerp((float)x / (float)(Width - 1)); } this[_selectedPosition, 1].GlyphIndex = 30; this[_selectedPosition, 1].Foreground = Color.LightGray;//this[_selectedPosition, 0].Foreground; // Build an array of all the colors Color[] colors = new Color[Width]; for (int x = 0; x < Width; x++) colors[x] = this[x, 0].Foreground; List<int> colorIndexesFinished = new List<int>(Width); foreach (var stop in gradient.Stops) { ColorMine.ColorSpaces.Rgb rgbColorStop = new ColorMine.ColorSpaces.Rgb() { R = stop.Color.R, G = stop.Color.G, B = stop.Color.B }; Tuple<Color, double, int>[] colorWeights = new Tuple<Color, double, int>[Width]; // Create a color weight for every cell compared to the color stop for (int x = 0; x < Width; x++) { if (!colorIndexesFinished.Contains(x)) { ColorMine.ColorSpaces.Rgb rgbColor = new ColorMine.ColorSpaces.Rgb() { R = colors[x].R, G = colors[x].G, B = colors[x].B }; ColorMine.ColorSpaces.Cmy cmyColor = rgbColor.To<ColorMine.ColorSpaces.Cmy>(); colorWeights[x] = new Tuple<Color, double, int>(colors[x], rgbColorStop.Compare(cmyColor, new ColorMine.ColorSpaces.Comparisons.Cie1976Comparison()), x); } else colorWeights[x] = new Tuple<Color, double, int>(colors[x], 10000, x); } var foundColor = colorWeights.OrderBy(t => t.Item2).First(); this[foundColor.Item3, 0].Foreground = stop.Color; colorIndexesFinished.Add(foundColor.Item3); } this.IsDirty = false; } }