-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayProblems.cs
More file actions
608 lines (513 loc) · 19.7 KB
/
Copy pathArrayProblems.cs
File metadata and controls
608 lines (513 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
using System;
using System.Collections.Generic;
using System.Linq;
namespace dojo
{
public static class ArrayProblems
{
public static int[] LeftCircularRotation(int[] source)
{
var firstElement = source[0];
for (var i = 1; i < source.Length; i++)
{
source[i - 1] = source[i];
}
source[^1] = firstElement;
Console.WriteLine(string.Join(" ", source));
return source;
}
public static int[] RightCircularRotation(int[] source)
{
var lastElement = source[^1];
for (var i = source.Length - 1; i > 0; i--)
{
source[i] = source[i - 1];
}
source[0] = lastElement;
Console.WriteLine(string.Join(' ', source));
return source;
}
private static int MakeAnInt(IEnumerable<int> source)
{
return int.Parse(string.Join(string.Empty, source));
}
public static int FindLargestNumberCombinationInAnArray(int[] source)
{
var counter = 0;
var maxCombination = MakeAnInt(source);
Console.WriteLine(string.Join(' ', source));
Console.WriteLine($"current max value is {maxCombination}");
while (counter < source.Length)
{
source = RightCircularRotation(source);
var numericValueOfNumbers = MakeAnInt(source);
if (numericValueOfNumbers > maxCombination)
{
maxCombination = numericValueOfNumbers;
}
counter++;
Console.WriteLine($"current max value is {maxCombination}");
}
return maxCombination;
}
private static int CalculateArraySize(int numbers)
{
var lengthOfArray = 0;
while (numbers > 0)
{
lengthOfArray++;
numbers /= 10;
}
return lengthOfArray;
}
private static int[] MakeArrayFromIntegers(int numbers)
{
var length = CalculateArraySize(numbers);
var resultArray = new int[length];
for (var i = 0; i < length; i++)
{
resultArray[i] = numbers % 10;
numbers /= 10;
}
return resultArray;
}
public static int GetTheBiggestByValueCombinationOfGivenIntegers(int numbers)
{
return FindLargestNumberCombinationInAnArray(MakeArrayFromIntegers(numbers));
}
public static void SpiralMatrixAlgorithm(int arrSize)
{
// Write a function that accepts an integer N
// and returns a NxN spiral matrix.
// --- Examples
// matrix(2)
// [[1, 2],
// [4, 3]]
// matrix(3)
// [[1, 2, 3],
// [8, 9, 4],
// [7, 6, 5]]
// matrix(4)
// [[1, 2, 3, 4],
// [12, 13, 14, 5],
// [11, 16, 15, 6],
// [10, 9, 8, 7]]
var (lastRowIndex, lastColumnIndex, rowIndex, columnIndex)
= (arrSize - 1, arrSize - 1, 0, 0);
var currentIntValue = 1;
var resultArray = new int[arrSize][];
for (var i = 0; i < resultArray.Length; i++)
{
resultArray[i] = new int[arrSize];
}
while (rowIndex <= lastRowIndex && columnIndex <= lastColumnIndex)
{
for (var topRowIndex = columnIndex; topRowIndex <= lastColumnIndex; topRowIndex++)
{
resultArray[rowIndex][topRowIndex] = currentIntValue;
currentIntValue++;
}
rowIndex++;
for (var rightCornerIndex = rowIndex; rightCornerIndex <= lastRowIndex; rightCornerIndex++)
{
resultArray[rightCornerIndex][lastColumnIndex] = currentIntValue;
currentIntValue++;
}
lastColumnIndex--;
for (var bottomRowIndex = lastColumnIndex; bottomRowIndex >= columnIndex; bottomRowIndex--)
{
resultArray[lastRowIndex][bottomRowIndex] = currentIntValue;
currentIntValue++;
}
lastRowIndex--;
for (var leftCornerIndex = lastRowIndex; leftCornerIndex >= rowIndex; leftCornerIndex--)
{
resultArray[leftCornerIndex][columnIndex] = currentIntValue;
currentIntValue++;
}
columnIndex++;
}
foreach (var item in resultArray)
{
Console.WriteLine(string.Join(' ', item));
}
}
public static int FindMissingNumberInAnArrayOfDistinctConsecutiveElements(IList<int> source)
{
//given an array of len n with consecutive distinct numbers up to n in any order, find the missing number
//u can sort the array and find which number exceeds the previous by more than one, then subtract 1 from it and woila
//or use gauss law sum of consecutive numbers in an array = len(arr) * (len(arr)+1)/2
var lengthArray = source.Contains(0) ? source.Count : source.Count + 1;
var currentSum = source.Sum();
var intendedSum = lengthArray * (lengthArray + 1) / 2;
return intendedSum - currentSum;
}
public static int FindMissingNumberInAnArrayIfEachElementOccursTwiceButThatNumber(IList<int> source)
{
var setInt = source.Distinct();
return 2 * setInt.Sum() - source.Sum();
}
public static int GreatestSumOfConsecutive(IReadOnlyList<int> source, int consecutive)
{
if (source.Count() < consecutive)
{
throw new ArgumentException($"array can not have less than {consecutive} elements");
}
var initialSum = source.Take(consecutive).Sum();
for (var j = 0; j < source.Count() - consecutive; j++)
{
var currentSum = initialSum + source[j + consecutive] - source[j];
if (currentSum > initialSum)
{
initialSum = currentSum;
}
}
return initialSum;
}
public static bool MountainArray(IList<int> source)
{
// array should have more than three elements and the beginning numbers index i=0
// to some index i should be increasing in Value and from that point i to the end
// decreasing in Value;
var arrayLength = source.Count;
if (arrayLength < 4)
{
return false;
}
var j = 1;
while (j < arrayLength && source[j] > source[j - 1])
{
j++;
}
if (j == 1 || j == arrayLength)
{
return false;
}
while (j < arrayLength && source[j] < source[j - 1])
{
j++;
}
return j == arrayLength;
}
public static (int, int) FindFirstAndLastOccurenceOfElementInASortedList(IList<int> source, int target)
{
if (!source.Contains(target))
{
throw new ArgumentException($"the list does not contain {target}");
}
var length = source.Count;
const int left = 0;
var right = length - 1;
var firstOccurence = FindFirstOccurrenceOfANumberInASortedList(source, target, left, right);
var lastOccurence = FindLastOccurenceOfANumberInASortedList(source, target, left, right);
return (firstOccurence, lastOccurence);
}
private static int FindLastOccurenceOfANumberInASortedList(IList<int> source, int target, int left, int right)
{
var lastOccurence = -1;
while (left <= right)
{
var mid = (int)Math.Floor((double)(left + (right - left) / 2));
var currentValue = source[mid];
if (currentValue == target)
{
if (mid == source.Count - 1 || source[mid + 1] != target)
{
lastOccurence = mid;
break;
}
else
{
left = mid + 1;
}
}
else if (currentValue > target)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return lastOccurence;
}
private static int FindFirstOccurrenceOfANumberInASortedList(IList<int> source, int target, int left, int right)
{
var firstOccurence = -1;
while (left <= right)
{
var mid = (int)Math.Floor((left + (right - left) / 2.0));
var currentValue = source[mid];
if (currentValue == target)
{
if (mid == 0 || source[mid - 1] != target)
{
firstOccurence = mid;
break;
}
else
{
right = mid - 1;
}
}
else if (currentValue > target)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return firstOccurence;
}
public static string MoveZeroesToTheEnd(IList<int> source)
{
// Move all zeroes to the end of a given array while maintaining the order
// or elements in the array
var j = 0;
foreach (var num in source)
{
if (num == 0)
{
continue;
}
source[j] = num;
j++;
}
for (var i = j; i < source.Count; i++)
{
source[i] = 0;
}
return string.Join(' ', source);
}
public static (int, int) FindTheIndicesOfFirstTwoElementsThatAddUpToTarget(IList<int> source, int target)
{
// Given an array of integers and a number, say target, find the index of two numbers in the array that sum up to the target:
// e.g given[1, 3, 4, 5, 6, 7, 8] and 9, you should return 1,4 for the values 3 and 6 that sum up to 9
// if no such numbers exist return (-1, -1)
var elementHolders = new Dictionary<int, int>(); // will hold the value of each element and its index
for (var i = 0; i < source.Count; i++)
{
var missingNumber = target - source[i];
if (elementHolders.ContainsKey(missingNumber))
{
return (elementHolders[missingNumber], i);
}
else
{
elementHolders.Add(source[i], i);
}
}
return (-1, -1);
}
public static void GetChunksOfArraysFromAGivenArray(List<int> source, int lengthOfArrayChunks)
{
// --- Directions
// Given an array and chunk size, divide the array into many subarrays
// where each sub array is of length size
// --- Examples
// chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
// chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
// chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
// chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]
var numberOfArraysToBeCreated = (int)Math.Ceiling((double)source.Count / lengthOfArrayChunks);
var counter = 0;
var sourceLength = source.Count - 1;
var indexCounter = 0;
var resultArray = new List<List<int>>();
while (counter < numberOfArraysToBeCreated)
{
if (indexCounter + lengthOfArrayChunks > sourceLength)
{
resultArray.Add(source.GetRange(indexCounter, source.Count - indexCounter));
}
else
{
resultArray.Add(source.GetRange(indexCounter, lengthOfArrayChunks));
indexCounter += lengthOfArrayChunks;
}
counter++;
}
foreach (var arr in resultArray)
{
Console.WriteLine(string.Join(' ', arr));
}
}
public static bool DoesArrayContainDuplicateValues(IEnumerable<int> source)
{
var dataKeeper = new Dictionary<int, int>();
foreach (var num in source)
{
if (dataKeeper.ContainsKey(num))
{
return true;
}
else
{
dataKeeper[num] = num;
}
}
return false;
}
public static int FindTheMostFrequentElement(IEnumerable<int> source)
{
var counter = new Dictionary<int, int>();
foreach (var num in source)
{
if (counter.ContainsKey(num))
{
counter[num] += 1;
}
else
{
counter[num] = 1;
}
}
return counter
.OrderByDescending(m => m.Value)
.Select(m => m.Key)
.First();
}
public static int FindPossibleNumberOfTimesSumsToZero(IEnumerable<int> first,
IEnumerable<int> second, IEnumerable<int> third, IEnumerable<int> fourth)
{
// Given four arrays a, b, c and d, find how many possible combinations
// such that if we took an element from each array and added them together the result would be 0.
var results = new Dictionary<int, int>(); //this will hold sum of two elements from two arrays and the number of times it repeats throughout the calculation
foreach (var num in first)
{
foreach (var num2 in second)
{
var currentSum = num + num2;
if (results.ContainsKey(currentSum))
{
results[currentSum]++;
}
else
{
results[currentSum] = 1;
}
}
}
var numberOfCombinations = third.Sum(num => fourth.Select(num2 => -(num + num2)).Where(currentSum => results.ContainsKey(currentSum)).Sum(currentSum => results[currentSum]));
return numberOfCombinations;
}
public static int FindSecondMaximumValueInOneLoop(int[] source)
{
var maxValue1 = int.MinValue;
var maxValue2 = int.MinValue;
foreach (var number in source)
{
if (number > maxValue1)
{
maxValue2 = maxValue1;
maxValue1 = number;
}
else if (number > maxValue2)
{
maxValue2 = number;
}
}
return maxValue2;
}
public static int FindThirdMaximumValueInOneLoop(int[] source)
{
var (maxValue1, maxValue2, maxValue3) = (int.MinValue, int.MinValue, int.MinValue);
foreach (var number in source)
{
if (number > maxValue1)
{
maxValue3 = maxValue2;
maxValue2 = maxValue1;
maxValue1 = number;
}
else if (number > maxValue2)
{
maxValue3 = maxValue2;
maxValue2 = number;
}
else if (number > maxValue3)
{
maxValue3 = number;
}
}
return maxValue3;
}
public static int[] JoinTwoArraysToOneMultiDimensionalReadingColumnsFirst(int[,] array)
{
var totalNumberOfElements = array.Length;
var index = 0;
var resultArray = new int[totalNumberOfElements];
var rows = array.GetLength(0);
var columns = array.GetLength(1);
for (var row = 0; row < columns; row++)
{
for (var column = 0; column < rows; column++)
{
resultArray[index] = array[column, row];
index++;
}
}
Console.WriteLine($"total elements {totalNumberOfElements} rows: {rows} columns: {columns}");
Console.WriteLine(string.Join(' ', resultArray));
return resultArray;
}
public static int[] EmptyATwoDimensionalArrayIntoAOneDimensional(int[,] array)
{
var totalNumberOfElements = array.Length;
var index = 0;
var resultArray = new int[totalNumberOfElements];
var rows = array.GetLength(0);
var columns = array.GetLength(1);
for (var row = 0; row < rows; row++)
{
for (var column = 0; column < columns; column++)
{
resultArray[index] = array[row, column];
index++;
}
}
Console.WriteLine(string.Join(' ', resultArray));
return resultArray;
}
public static int AddSumOfOddNumbers(int[] array)
{
return array.Where(x => x % 2 == 1).Sum();
}
public static int AddArrayOfArrays(int[,] source)
{
return source.Cast<int>().Sum();
}
public static bool LuckyNumbers(int[] source, int consecutiveNumbers, int amountTheySumUpTo)
{
//check whether in a given array of numbers, and a number of consecutive numbers to check, whether
//any of them add up to the given amount they should sum to.
return source
.Where((t, index) => source[index..].Take(consecutiveNumbers).Sum().Equals(amountTheySumUpTo))
.Any();
}
public static List<List<int>> TwoSumProblem(int[] source, int target)
{
// Given an integer x and a sorted array a of N distinct integers, design a linear-time algorithm to determine if
// there exists two distinct indices i and j such that a[i] + a[j] == x
var resultList = new List<List<int>>();
var elementAndIndexHolder = new Dictionary<int, int>();
for (var index = 0; index < source.Length; index++)
{
var missingNumber = target - source[index];
if (elementAndIndexHolder.ContainsKey(missingNumber))
{
resultList.Add(new List<int>(){source[index], missingNumber});
}
else
{
elementAndIndexHolder[source[index]] = index;
}
}
return resultList;
}
}
}