-
Notifications
You must be signed in to change notification settings - Fork 1
/
coding-examples.html
8421 lines (7318 loc) · 261 KB
/
coding-examples.html
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Coding Challenges in a Technical Interview</title>
<meta charset="utf-8">
<meta charset="utf-8">
<meta name='keywords' content='test, quiz, interview, interview questions, technical interview, technical questions'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
footer { color: gray; }
.item {
display: inline-block;
width: 60px;
font-weight: bold;
}
h3 { color: teal;}
h4 { color: steelblue;}
pre { background-color: #DDDDDD; margin: 5px; font-family: "Courier New", Courier, monospace }
a.index:link, a.index:visited {
text-decoration: none;
color : steelblue;
}
a.list:link, a.list:visited {
text-decoration: none;
color : darkorange;
}
.expand { font-weight: bold; color: darkorange; cursor: pointer }
</style>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-3662373-7', 'auto');
ga('send', 'pageview');
var timing = [];
var send = false;
var session;
function Timestamp( category, id, type ) {
// on first call, setup timer and variables for sending timing metrics to server
if ( send == false ) {
send = true;
session = Math.round( Math.random() * 10000 );
setTimeout( function() { SendServer(); }, 10000 );
}
// store timing metrics until periodic upload to
var time = Math.floor( Date.now() / 1000 );
timing.push( { session: session, category: category, id: id, type: type, time: time } );
}
Timestamp( "coding", "", "" );
/*
* Send Timing Metrics to the Server
*/
function SendServer() {
if ( timing.length > 0 ) {
$.ajax({
url: "/timing.php",
type: 'post',
data: { timing },
success: function( data, status ) { },
error: function(xhr) { console.log( xhr.status + " " + xhr.statusText ); }
});
timing = [];
}
setTimeout( function() { SendServer(); }, 10000 );
}
</script>
</head>
<body ng-app="technical" style='margin: 20px;' ng-controller='tabCtrl'>
<header ng-controller="navCtrl">
<div nav></div>
</header>
<section style='text-align: center'>
<h2 style='color: steelblue'>Coding Challenges</h2>
<h4 style='color: darkgray'>All the coding challenges are hand coded and tested by me. They are not copied from other sources.</h4>
<h5><a href="technical-interview-coding-challenges.pdf">Download as PDF</a></h5>
</section>
<p>
The coding challenges in this section are basic algorithms. A coding portion of a technical interview will likely start with one of these types
of algorithms. Typically, after asking you to code the basic algorithm, you will be ask to make improvements or other variations. If you are
unable to pass this part of the coding portion, you will probably not continue to the next round of an interview.
</p>
<ol class='w3-ul'>
<li><a class='index' href='#prime'>Prime Numbers</a><span class='expand' ng-click='prime=!prime'> +</span>
<ul ng-show='prime'>
<li><a class='list' href="#prime1">Standard</a></li>
<li><a class='list' href="#prime2">Skip Even Numbers</a></li>
<li><a class='list' href="#prime3">Skip Even Numbers, and divide only by numbers one-third or less than the number.</a></li>
</ul>
</li>
<li><a class='index' href='#fibonacci'>Fibonacci Sequence</a><span class='expand' ng-click='fibonacci=!fibonacci'> +</span>
<ul ng-show='fibonacci'>
<li><a class='list' href="#fibonacci1">Recursive</a></li>
<li><a class='list' href="#fibonacci2">Iterative</a></li>
</ul>
</li>
<li><a class='index' href='#dynamic'>Dynamic Arrays</a><span class='expand' ng-click='dynamic=!dynamic'> +</span>
<ul ng-show='dynamic'>
<li><a class='list' href="#dynamic1">Add/Get</a></li>
<li><a class='list' href="#dynamic2">Delete</a></li>
</ul>
</li>
<li><a class='index' href='#queue'>Linked Lists - Queue</a><span class='expand' ng-click='queue=!queue'> +</span>
<ul ng-show='queue'>
<li><a class='list' href="#queue1">Queue</a></li>
<li><a class='list' href="#queue2">Queue with Task Priority</a></li>
<li><a class='list' href="#queue3">Queue with Dynamic Priority Update</a></li>
</ul>
</li>
<li><a class='index' href='#stack'>Linked Lists - Stack</a><span class='expand' ng-click='stack=!stack'> +</span>
<ul ng-show='stack'>
<li><a class='list' href="#stack1">Stack</a></li>
<li><a class='list' href="#stack2">Chain of Stacks</a></li>
<li><a class='list' href="#stack3">Towers of Hanoi</a></li>
</ul>
</li>
<li><a class='index' href='#btree'>Binary Trees</a><span class='expand' ng-click='btree=!btree'> +</span>
<ul ng-show='btree'>
<li><a class='list' href="#btree1">Standard</a></li>
<li><a class='list' href="#btree2">Generalize from K-ary Tree</a></li>
</ul>
</li>
<li><a class='index' href='#bts'>Binary Tree Traversals</a><span class='expand' ng-click='bts=!bts'> +</span>
<ul ng-show='bts'>
<li><a class='list' href="#bts1">Inorder</a></li>
<li><a class='list' href="#bts2">Preorder</a></li>
<li><a class='list' href="#bts3">Postorder</a></li>
<li><a class='list' href="#bts4">Level Order</a></li>
<li><a class='list' href="#bts5">Maximum and Minimum Depth of Binary Tree</a></li>
<li><a class='list' href="#bts6">Maximum and Minimum Value</a></li>
</ul>
</li>
<li><a class='index' href='#kary'>K-ary Trees</a><span class='expand' ng-click='kary=!kary'> +</span>
<ul ng-show='kary'>
<li><a class='list' href="#kary1">Standard</a></li>
</ul>
</li>
<li><a class='index' href='#bst'>Binary Search Trees</a><span class='expand' ng-click='bst=!bst'> +</span>
<ul ng-show='bst'>
<li><a class='list' href="#bst1">Insert</a></li>
<li><a class='list' href="#bst2">Find</a></li>
<li><a class='list' href="#bst3">Delete</a></li>
</ul>
</li>
<li><a class='index' href='#arith'>Arithmetic Operations</a><span class='expand' ng-click='arith=!arith'> +</span>
<ul ng-show='arith'>
<li><a class='list' href="#arith1">Multiply</a></li>
<li><a class='list' href="#arith2">Exponent</a></li>
<li><a class='list' href="#arith3">Exponent with Fewer Multiplication Steps</a></li>
<li><a class='list' href="#arith4">GCD Iterative Solution</a></li>
<li><a class='list' href="#arith5">GCD Recursive Solution</a></li>
<li><a class='list' href="#arith6">LCM</a></li>
</ul>
</li>
<li><a class='index' href='#encoding'>Variable Length Byte Encoding</a><span class='expand' ng-click='encoding=!encoding'> +</span>
<ul ng-show='encoding'>
<li><a class='list' href="#encoding1">Byte Encoding</a></li>
</ul>
</li>
<li><a class='index' href='#sort'>Sorting</a><span class='expand' ng-click='sort=!sort'> +</span>
<ul ng-show='sort'>
<li><a class='list' href="#sort1">Bubble Sort</a></li>
<li><a class='list' href="#sort2">Insertion Sort</a></li>
<li><a class='list' href="#sort3">Quick Sort</a></li>
<li><a class='list' href="#sort4">Merge Sort</a></li>
</ul>
</li>
<li><a class='index' href='#hash'>Hashing</a><span class='expand' ng-click='hash=!hash'> +</span>
<ul ng-show='hash'>
<li><a class='list' href="#hash1">Integer Hash</a></li>
<li><a class='list' href="#hash2">String (Object) Hash</a></li>
<li><a class='list' href="#hash3">Hash Table with Linear Probing</a></li>
</ul>
</li>
<li><a class='index' href='#string'>String Manipulations</a><span class='expand' ng-click='string=!string'> +</span>
<ul ng-show='string'>
<li><a class='list' href="#string1">Reverse String (Iterative)</a></li>
<li><a class='list' href="#string2">Reverse String (Recursive)</a></li>
<li><a class='list' href="#string3">Palindrome</a></li>
<li><a class='list' href="#string4">Palindrome (Phrases)</a></li>
<li><a class='list' href="#string5">Character Count</a></li>
<li><a class='list' href="#string6">Duplicate Characters</a></li>
</ul>
</li>
<li><a class='index' href='#graph'>Graphs</a><span class='expand' ng-click='graph=!graph'> +</span>
<ul ng-show='graph'>
<li><a class='list' href="#graph1">BFS Graph Traversal</a></li>
<li><a class='list' href="#graph2">DFS Graph Traversal (Iterative)</a></li>
<li><a class='list' href="#graph3">DFS Graph Traversal (Recursive)</a></li>
</ul>
</li>
</ol>
<a name="prime"></a>
<h3>1. Prime Numbers</h3>
<p>
The most basic coding example you might get asked is to write an algorithm to output a series of prime numbers.
Prime numbers are numbers that are only divisible by one and itself. The algorithm is a
straight forward iterative algorithm.
</p>
<a name="prime1"></a>
<h4>Standard</h4>
<ul class="w3-navbar w3-light-grey" ng-init="pri1[0] = true; pri1cls[0] = 'w3-black'">
<li><a href="javascript:void(0)" ng-click="pri1=[true,false,false,false]; pri1cls=['w3-black','w3-lightgray','w3-lightgray','w3-lightgray']; Algo('pri1')" ng-class='pri1cls[0]'>Algorithm</a></li>
<li><a href="javascript:void(0)" ng-click="pri1=[false,true,false,false]; pri1cls=['w3-lightgray','w3-black','w3-lightgray','w3-lightgray']; Python('pri1')" ng-class='pri1cls[1]'>Python</a></li>
<li><a href="javascript:void(0)" ng-click="pri1=[false,false,true,false]; pri1cls=['w3-lightgray','w3-lightgray','w3-black','w3-lightgray']; Java('pri1')" ng-class='pri1cls[2]'>Java</a></li>
<li><a href="javascript:void(0)" ng-click="pri1=[false,false,false,true]; pri1cls=['w3-lightgray','w3-lightgray','w3-lightgray','w3-black']; Javascript('pri1')" ng-class='pri1cls[3]'>Javascript</a></li>
</ul>
<div ng-show='pri1[0]'>
<p>
The number one is a prime number, since it can only be divisible by itself. The
number two is also a prime number, since there are no numbers between one and two
to divide by. Therefore, I generally like to start the iterative process at three, though
you may choose to start it at two.
</p>
<ol class='w3-ul'>
<li>For each number, we attempt to divide it by every number less than it, except for one.</li>
<li>The integer modulo operator is used to test if there is a remainder from the integer division.</li>
<li>If there is no remainder, it is divisible by the number and therefore not a prime.</li>
<li>If each of the numbers it is divided by has a remainder, it is a prime.</li>
</ol>
</div>
<pre class='w3-container' ng-show='pri1[1]'>
print( "Prime Numbers between 1 and 100")
# Prime Numbers are numbers only divisible by 1 and itself.
print( "1" )
print( "2" )
# Primes for numbers above 2
for number in range( 3, 101 ):
# Attempt to divide this number by every number between 2 and one less than itself
for div in range(2,number):
# use the mod function to see if their is a remainder in the division
if ( number % div ) == 0:
break
else:
print(number)
</pre>
<pre class='w3-container' ng-show='pri1[2]'>
public class prime {
public static void main( String args[] ) {
System.out.println( "Prime Numbers between 1 and 100");
// Prime Numbers are numbers only divisible by 1 and itself.
System.out.println( "1" );
System.out.println( "2" );
// Primes for numbers above 2
for ( int number = 3; number <=100; number++ ) {
// Attempt to divide this number by every number between 2 and one less than itself
int div = 2;
for ( /**/; div < number; div++ ) {
// use the mod function to see if their is a remainder in the division
if ( ( number % div ) == 0 )
break;
}
if ( div == number )
System.out.println(number);
}
}
}
</pre>
<pre class='w3-container' ng-show='pri1[3]'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
var output = $("#output");
function println( text ) {
output.html( output.html() + "<br/>" + text );
}
println( "Prime Numbers between 1 and 100" );
// Prime Numbers are numbers only divisible by 1 and itself.
println( "1" );
println( "2" );
// Primes for numbers above 2
for ( var number = 3; number <=100; number++ ) {
// Attempt to divide this number by every number between 2 and one less than itself
var div = 2;
for ( /**/; div < number; div++ ) {
// use the mod function to see if their is a remainder in the division
if ( ( number % div ) == 0 )
break;
}
if ( div == number )
println(number);
}
});
</script>
<body>
<div id='output'></div>
</body>
</pre>
<a name="prime2"></a>
<h4>Skip Even Numbers</h4>
<ul class="w3-navbar w3-light-grey" ng-init="pri2[0] = true; pri2cls[0] = 'w3-black'">
<li><a href="javascript:void(0)" ng-click="pri2=[true,false,false,false]; pri2cls=['w3-black','w3-lightgray','w3-lightgray','w3-lightgray']; Algo('pri2')" ng-class='pri2cls[0]'>Algorithm</a></li>
<li><a href="javascript:void(0)" ng-click="pri2=[false,true,false,false]; pri2cls=['w3-lightgray','w3-black','w3-lightgray','w3-lightgray']; Python('pri2')" ng-class='pri2cls[1]'>Python</a></li>
<li><a href="javascript:void(0)" ng-click="pri2=[false,false,true,false]; pri2cls=['w3-lightgray','w3-lightgray','w3-black','w3-lightgray']; Java('pri2')" ng-class='pri2cls[2]'>Java</a></li>
<li><a href="javascript:void(0)" ng-click="pri2=[false,false,false,true]; pri2cls=['w3-lightgray','w3-lightgray','w3-lightgray','w3-black']; Javascript('pri2')" ng-class='pri2cls[3]'>Javascript</a></li>
</ul>
<div ng-show='pri2[0]'>
<p>
Can we make an improvement? Yes. Since we know all even numbers are divisible by two, we
can skip checking even numbers and only check odd numbers. Likewise, since we know odd numbers are not divisible by even numbers,
we can skip dividing by even numbers and only divide by odd numbers.
</p>
<ol class='w3-ul'>
<li>For each odd number, we attempt to divide it by every odd number less than it, except for one.</li>
<li>The integer modulo operator is used to test if there is a remainder from the integer division.</li>
<li>If there is no remainder, it is divisible by the number and therefore not a prime.</li>
<li>If each of the numbers it is divided by has a remainder, it is a prime.</li>
</ol>
</div>
<pre class='w3-container' ng-show='pri2[1]'>
print( "Prime Numbers between 1 and 100")
# Prime Numbers are numbers only divisible by 1 and itself.
print( "1" )
print( "2" )
print( "3" )
# Primes for numbers above 5
for number in range( 5, 101, 2 ):
# Attempt to divide this number by every odd number between 2 and one less than itself
for div in range(3,number,2):
# use the mod function to see if their is a remainder in the division
if ( number % div ) == 0:
break
else:
print(number)
</pre>
<pre class='w3-container' ng-show='pri2[2]'>
public class prime {
public static void main( String args[] ) {
System.out.println( "Prime Numbers between 1 and 100");
// Prime Numbers are numbers only divisible by 1 and itself.
System.out.println( "1" );
System.out.println( "2" );
System.out.println( "3" );
// Primes for numbers above 5
for ( int number = 5; number <=100; number += 2 ) {
int div = 3;
// Attempt to divide this number by every odd number between 3 and one less than itself
for ( /**/; div < number; div += 2 ) {
// use the mod function to see if their is a remainder in the division
if ( ( number % div ) == 0 )
break;
}
if ( div == number )
System.out.println(number);
}
}
}
</pre>
<pre class='w3-container' ng-show='pri2[3]'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
var output = $("#output");
function println( text ) {
output.html( output.html() + "<br/>" + text );
}
println( "Prime Numbers between 1 and 100" );
// Prime Numbers are numbers only divisible by 1 and itself.
println( "1" );
println( "2" );
println( "3" );
// Primes for numbers above 5
for ( var number = 5; number <=100; number += 2 ) {
var div = 3;
// Attempt to divide this number by every odd number between 3 and one less than itself
for ( /**/; div < number; div += 2 ) {
// use the mod function to see if their is a remainder in the division
if ( ( number % div ) == 0 )
break;
}
if ( div == number )
println(number);
}
});
</script>
<body>
<div id='output'></div>
</body>
</pre>
<a name="prime3"></a>
<h4>Skip Even Numbers, and divide only by numbers one-third or less than the number</h4>
<ul class="w3-navbar w3-light-grey" ng-init="pri3[0] = true; pri3cls[0] = 'w3-black'">
<li><a href="javascript:void(0)" ng-click="pri3=[true,false,false,false]; pri3cls=['w3-black','w3-lightgray','w3-lightgray','w3-lightgray']; Algo('pri3')" ng-class='pri3cls[0]'>Algorithm</a></li>
<li><a href="javascript:void(0)" ng-click="pri3=[false,true,false,false]; pri3cls=['w3-lightgray','w3-black','w3-lightgray','w3-lightgray']; Python('pri3')" ng-class='pri3cls[1]'>Python</a></li>
<li><a href="javascript:void(0)" ng-click="pri3=[false,false,true,false]; pri3cls=['w3-lightgray','w3-lightgray','w3-black','w3-lightgray']; Java('pri3')" ng-class='pri3cls[2]'>Java</a></li>
<li><a href="javascript:void(0)" ng-click="pri3=[false,false,false,true]; pri3cls=['w3-lightgray','w3-lightgray','w3-lightgray','w3-black']; Java('pri3')" ng-class='pri3cls[3]'>Javascript</a></li>
</ul>
<div ng-show='pri3[0]'>
<p>
Can we make another improvement? Yes. Since we are skipping even numbers, we know that each number to be prime must be divisible by at least the number three.
Therefore, any divisible number must be one-third or less the value of the number. We can cut down on the number of iterations by only dividing
the first 1/3 of values less than the number.
</p>
<ol class='w3-ul'>
<li>For each odd number, we attempt to divide it by every odd number that is less than one-third of the number, except for one and two.</i>
<li>The integer modulo operator is used to test if there is a remainder from the integer division.</li>
<li>If there is no remainder, it is divisible by the number and therefore not a prime.</li>
<li>If each of the numbers it is divided by has a remainder, it is a prime.</li>
</ol>
</div>
<pre class='w3-container' ng-show='pri3[1]'>
print( "1" )
print( "2" )
print( "3" )
for number in range( 5, 101, 2 ):
# Attempt to divide this number by every number between 3 and one third less than itself
third = int( (number / 3 ) ) + 1
for div in range(3,third,2):
# use the mod function to see if their is a remainder in the division
if ( number % div ) == 0:
break
else:
print(number)
</pre>
<pre class='w3-container' ng-show='pri3[2]'>
public class prime {
public static void main( String args[] ) {
System.out.println( "Prime Numbers between 1 and 100");
// Prime Numbers are numbers only divisible by 1 and itself.
System.out.println( "1" );
System.out.println( "2" );
System.out.println( "3" );
// Primes for numbers above 5
for ( int number = 5; number <=100; number += 2 ) {
int div = 3;
int third = ( number / 3 ); // calculate one-third of the number
// Attempt to divide this number by every number between 3 and one third of the number
for ( /**/; div <= third; div += 2) {
// use the mod function to see if their is a remainder in the division
if ( ( number % div ) == 0 )
break;
}
if ( div >= third )
System.out.println(number);
}
}
}
</pre>
<pre class='w3-container' ng-show='pri3[3]'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
var output = $("#output");
function println( text ) {
output.html( output.html() + "<br/>" + text );
}
println( "Prime Numbers between 1 and 100" );
// Prime Numbers are numbers only divisible by 1 and itself.
println( "1" );
println( "2" );
println( "3" );
// Primes for numbers above 5
for ( var number = 5; number <=100; number += 2 ) {
var div = 3;
var third = ( number / 3 ); // calculate one-third of the number
// Attempt to divide this number by every number between 3 and one third of the number
for ( /**/; div <= third; div += 2) {
// use the mod function to see if their is a remainder in the division
if ( ( number % div ) == 0 )
break;
}
if ( div >= third )
println(number);
}
});
</script>
<body>
<div id='output'></div>
</body>
</pre>
<a name="fibonacci"></a>
<h3>2. Fibonacci Sequence</h3>
<p>
One of the most common and basic coding examples is to code a solution for the Fibonacci sequence. A Fibonacci sequence is a function where F(N) equals
F(n-1) + F(n-2); that is the summation of the previous two values in the sequence. Originally, the seed sequence was F(0) = 1 and F(1) = 1, but modern
solutions use F(0) = 0 and F(1) = 1. This sequence can be written in a very short recursive algorithm.
</p>
<a name="fibonacci1"></a>
<h4>Recursive</h4>
<ul class="w3-navbar w3-light-grey" ng-init="fib1[0] = true; fib1cls[0] = 'w3-black'">
<li><a href="javascript:void(0)" ng-click="fib1=[true,false,false,false]; fib1cls=['w3-black','w3-lightgray','w3-lightgray','w3-lightgray']; Algo('fib1')" ng-class='fib1cls[0]'>Algorithm</a></li>
<li><a href="javascript:void(0)" ng-click="fib1=[false,true,false,false]; fib1cls=['w3-lightgray','w3-black','w3-lightgray','w3-lightgray']; Python('fib1')" ng-class='fib1cls[1]'>Python</a></li>
<li><a href="javascript:void(0)" ng-click="fib1=[false,false,true,false]; fib1cls=['w3-lightgray','w3-lightgray','w3-black','w3-lightgray']; Java('fib1')" ng-class='fib1cls[2]'>Java</a></li>
<li><a href="javascript:void(0)" ng-click="fib1=[false,false,false,true]; fib1cls=['w3-lightgray','w3-lightgray','w3-lightgray','w3-black']; Javascript('fib1')" ng-class='fib1cls[3]'>Javascript</a></li>
</ul>
<div ng-show='fib1[0]'>
<ol class='w3-ul'>
<li>If n = 0, then return 0.</li>
<li>If n = 1, then return 1.</li>
<li>If n > 1, return the sum of F(n-1) + F(n-2).</li>
</ol>
</div>
<pre class='w3-container' ng-show='fib1[1]'>
# Fibonacci Sequence
# Is a sum (addition) of the previous two numbers in the sequence, as
# F(n) = F(n-1) + F(n-2)
# Where
# F(0) = 0 and F(1) = 1
# Hence
# F(2) = 0 + 1 [F(1) + F(0)] = 1
# F(3) = 1 + 1 [F(2) + F(1)] = 2
# Recursive Solution
def Fibonacci(n):
# F(0) and F(1) case
if n==0:
return 0
if n==1:
return 1
return Fibonacci(n-1) + Fibonacci(n-2)
# Fibonacci Sequence to F(10)
for number in range( 0, 10 ):
print( Fibonacci(number) )
</pre>
<pre class='w3-container' ng-show='fib1[2]'>
public class fibonacci {
// Recursive Solution
public static int Fibonacci( int n) {
if ( n == 0 ) return 0;
if ( n == 1 ) return 1;
return Fibonacci( n - 1 ) + Fibonacci( n - 2 );
}
// Test Driver
public static void main( String args[] ) {
System.out.println( "Fibonacci Sequence to F(10)");
for ( int number = 0; number < 10; number++ )
System.out.println( Fibonacci( number ) );
}
}
</pre>
<pre class='w3-container' ng-show='fib1[3]'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
var output = $("#output");
function println( text ) {
output.html( output.html() + "<br/>" + text );
}
// Recursive Solution
function Fibonacci( n ) {
if ( n == 0 ) return 0;
if ( n == 1 ) return 1;
return Fibonacci( n - 1 ) + Fibonacci( n - 2 );
}
// Test Driver
println( "Fibonacci Sequence to F(10)");
for ( var number = 0; number < 10; number++ )
println( Fibonacci( number ) );
});
</script>
<body>
<div id='output'></div>
</body>
</pre>
<a name="fibonacci2"></a>
<h4>Iterative</h4>
<ul class="w3-navbar w3-light-grey" ng-init="fib2[0] = true; fib2cls[0] = 'w3-black'">
<li><a href="javascript:void(0)" ng-click="fib2=[true,false,false,false]; fib2cls=['w3-black','w3-lightgray','w3-lightgray','w3-lightgray']; Algo('fib2')" ng-class='fib2cls[0]'>Algorithm</a></li>
<li><a href="javascript:void(0)" ng-click="fib2=[false,true,false,false]; fib2cls=['w3-lightgray','w3-black','w3-lightgray','w3-lightgray']; Python('fib2')" ng-class='fib2cls[1]'>Python</a></li>
<li><a href="javascript:void(0)" ng-click="fib2=[false,false,true,false]; fib2cls=['w3-lightgray','w3-lightgray','w3-black','w3-lightgray']; Java('fib2')" ng-class='fib2cls[2]'>Java</a></li>
<li><a href="javascript:void(0)" ng-click="fib2=[false,false,false,true]; fib2cls=['w3-lightgray','w3-lightgray','w3-lightgray','w3-black']; Javascript('fib2')" ng-class='fib2cls[3]'>Javascript</a></li>
</ul>
<div ng-show='fib2[0]'>
<p>
It is common to be asked if you can write the algorithm for an iterative solution (looping - no recursion).
</p>
<ol class='w3-ul'>
<li>If n = 0, then return 0.</li>
<li>If n = 1, then return 1.</li>
<li>If n > 1, then set last F(n-2) = 0, and last F(n-1) = 0, and F(n) initialized to zero.</li>
<li>Loop from 2 to n.
<ul>
<li>Set current F(n) to current F(n-1) + F(n-2).</li>
<li>Set F(n-2) to current F(n-1).</li>
<li>Set F(n-1) to current F(n).</li>
</ul>
</li>
</ol>
</div>
<pre class='w3-container' ng-show='fib2[1]'>
def FibonacciIterative(n):
# F(0) and F(1) case
if n==0:
return 0
if n==1:
return 1
fn = 0 # current value for F(n)
f_minus_1 = 1 # current value for F(n-1)
f_minus_2 = 0 # current value for F(n-2)
for i in range( 2, n+1 ):
fn = f_minus_1 + f_minus_2 # F(n) = F(n-1) + F(n-2)
f_minus_2 = f_minus_1 # next F(n-2)
f_minus_1 = fn # next F(n-1)
return fn
# Fibonacci Sequence to F(10)
for number in range( 0, 10 ):
print( FibonacciIterative(number) )
</pre>
<pre class='w3-container' ng-show='fib2[2]'>
public class fibonacci {
// Iterative Solution
public static int Fibonacci( int n ) {
if ( n == 0 ) return 0;
if ( n == 1 ) return 1;
int fn = 0; // current value for F(n)
int f_minus_2 = 0; // current value of F(n-2)
int f_minus_1 = 1; // current value of F(n-1)
for ( int i = 2; i <= n; i++ ) {
fn = f_minus_1 + f_minus_2; // F(n) = F(n-1) + F(n-2)
f_minus_2 = f_minus_1; // next F(n-2)
f_minus_1 = fn; // next F(n-1)
}
return fn;
}
// Test Driver
public static void main( String args[] ) {
System.out.println( "Fibonacci Sequence to F(10)");
for ( int number = 0; number < 10; number++ )
System.out.println( Fibonacci( number ) );
}
}
</pre>
<pre class='w3-container' ng-show='fib2[3]'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
var output = $("#output");
function println( text ) {
output.html( output.html() + "<br/>" + text );
}
// Iterative Solution
function FibonacciIterative( n ) {
if ( n == 0 ) return 0;
if ( n == 1 ) return 1;
var fn = 0; // current value for F(n)
var f_minus_2 = 0; // current value of F(n-2)
var f_minus_1 = 1; // current value of F(n-1)
for ( var i = 2; i <= n; i++ ) {
fn = f_minus_1 + f_minus_2; // F(n) = F(n-1) + F(n-2)
f_minus_2 = f_minus_1; // next F(n-2)
f_minus_1 = fn; // next F(n-1)
}
return fn;
}
// Test Driver
println( "Fibonacci Sequence to F(10)");
for ( var number = 0; number < 10; number++ )
println( FibonacciIterative( number ) );
});
</script>
<body>
<div id='output'></div>
</body>
</pre>
<a name="dynamic"></a>
<h3>3. Dynamic Arrays</h3>
<p>
A dynamic array is an array that can be resized, can be randomly accessed via an cardinal ordering, where there is a one-to-one relationship
between an integer index and a value. For example, if a dynamic array has the ordered elements A, B and D, they would be accessed (one-to-one relationship)
by indices 0=>A, 1=>B and 2=>D. If we insert a C between B and D, the ordering would be rearranged but there still would be a one-to-one relationship, accessed
as indices 0=>A, 1=>B, 2=>C and 3=>D. Note how index 2 now relates to C and index 3 to D.
</p>
<a name="dynamic1"></a>
<h4>Add/Get</h4>
<ul class="w3-navbar w3-light-grey" ng-init="dyn1[0] = true; dyn1cls[0] = 'w3-black'">
<li><a href="javascript:void(0)" ng-click="dyn1=[true,false,false,false]; dyn1cls=['w3-black','w3-lightgray','w3-lightgray','w3-lightgray']; Algo('dyn1')" ng-class='dyn1cls[0]'>Algorithm</a></li>
<li><a href="javascript:void(0)" ng-click="dyn1=[false,true,false,false]; dyn1cls=['w3-lightgray','w3-black','w3-lightgray','w3-lightgray']; Python('dyn1')" ng-class='dyn1cls[1]'>Python</a></li>
<li><a href="javascript:void(0)" ng-click="dyn1=[false,false,true,false]; dyn1cls=['w3-lightgray','w3-lightgray','w3-black','w3-lightgray']; Java('dyn1')" ng-class='dyn1cls[2]'>Java</a></li>
<li><a href="javascript:void(0)" ng-click="dyn1=[false,false,false,true]; dyn1cls=['w3-lightgray','w3-lightgray','w3-lightgray','w3-black']; Javascript('dyn1')" ng-class='dyn1cls[3]'>Javascript</a></li>
</ul>
<div ng-show='dyn1[0]'>
<p>
You maybe asked to implement a dynamic array using a class. You would be expected to implement at least an Add() and Get() methods.
</p>
<ol class='w3-ul'>
<li>Define a class for an element.
<ul>
<li>Has a member to hold the value.</li>
<li>Has a next pointer for the next element in the array.</li>
</ul>
</li>
<li>Define a class for an array.
<ul>
<li>Has a member to hold the head and a member to hold the tail of the array.</li>
<li>A member to hold the size of the array.</li>
<li>Define an Add method.
<ul>
<li>Instantiate a new element.</li>
<li>Add the element to the end of tail (the tail's next pointer) and update the tail to the new element.</li>
<li>If it is the first element in the array, set the head to the new element.</li>
<li>Increment the size of the array by one.</li>
</ul>
</li>
<li>Define a Get method.</li>
<ul>
<li>Check for array out of bounds condition.</li>
<li>Starting with the head, advance consecutively index number of times following the next pointer.</li>
<li>Return the value of the current element.</li>
</ul>
</li>
</ul>
</li>
</ol>
</div>
<pre class='w3-container' ng-show='dyn1[1]'>
# Definition for an element in the dynamic array
class Element:
next = None # next element in array
# Constructor: set the node data
def __init__(self, value):
self.value = value # node data
# Definition for a Dynamic Array
class DynamicArray:
head = None # head of the array
tail = None # tail of the array
size = 0 # size of the array
# The size (number of elements) of the array
def Size( self ):
return self.size;
# Add an element to the end of the dynamic array
def Add( self, value ):
e = Element(value)
# Set the next element of the previous tail to the new element
if self.tail != None:
self.tail.next = e
# set the current tail to the new element
self.tail = e
# If there is no head (first element), set the head to the new element.
if self.head == None:
self.head = e
# Increment the size of the array
self.size += 1
# Get the value at the corresponding index
def Get( self, index ):
# Check for out of bounds condition
if index > self.size - 1 or index < 0:
return None
# Step (linear) to the index position
curr = self.head;
for i in range( 0, index ):
curr = curr.next
return curr.value
# Test Driver
array = DynamicArray()
for i in range( 0, 7 ):
array.Add(i)
print("Expect 0,1,2,3,4,5,6")
for i in range( 0, array.Size() ):
print( array.Get(i) )
</pre>
<pre class='w3-container' ng-show='dyn1[2]'>
// Definition for an element in the dynamic array
class Element {
Object value = null; // Element value
Element next = null; // Next element in the array
// Constructor
public Element( Object value ) {
this.value = value;
}
}
// Definition for a Dynamic Array
class DynamicArray {
private Element head = null; // Head of the Array
private Element tail = null; // Tail of the Array
private int size = 0; // Number of elements in the Array
// The size (number of elements) of the array
public int Size() {
return size;
}
// Add an element to the end of the dynamic array
public void Add( Object value ) {
Element e = new Element( value );
// Set the next element of the previous tail to the new element
if ( tail != null )
tail.next = e;
// set the current tail to the new element
tail = e;
// If there is no head (first element), set the head to the new element.
if ( head == null )
head = e;
// Increment the size of the array
size++;
}
// Get the value at the corresponding index
public Object Get( int index ) {
// Check for out of bounds condition
if ( index > size - 1 || index < 0 )
return null;
// Step (linear) to the index position
Element curr = head;
for ( int i = 0; i < index; i++ )
curr = curr.next;
return curr.value;
}
}
// Test Driver
public class dynamic {
public static void main(String[] args) {
DynamicArray d = new DynamicArray();
for ( int i = 0; i < 7; i++ )
d.Add(i);
System.out.println("Expect 0,1,2,3,4,5,6");
for ( int i = 0; i < d.Size(); i++ )
System.out.println( (int) d.Get(i) );
}
</pre>
<pre class='w3-container' ng-show='dyn1[3]'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
var output = $("#output");
function println( text ) {
output.html( output.html() + "<br/>" + text );
}
// Definition for an element in the dynamic array
class Element {
// Constructor
constructor( value ) {
this.value = value; // Element value
this.next = null; // Next element in the array
}
}
// Definition for a Dynamic Array
class DynamicArray {
// constructor
constructor() {
this.head = null; // Head of the Array
this.tail = null; // Tail of the Array
this.size = 0; // Number of elements in the array
}
// The size (number of elements) of the array
Size() {
return this.size;
}
// Add an element to the end of the dynamic array
Add( value ) {
var e = new Element( value );
// Set the next element of the previous tail to the new element
if ( this.tail != null )
this.tail.next = e;
// set the current tail to the new element
this.tail = e;
// If there is no head (first element), set the head to the new element.
if ( this.head == null )
this.head = e;
// Increment the size of the array
this.size++;
}
// Get the value at the corresponding index
Get( index ) {
// Check for out of bounds condition
if ( index > this.size - 1 || index < 0 )
return null;
// Step (linear) to the index position
var curr = this.head;
for ( var i = 0; i < index; i++ )
curr = curr.next;
return curr.value;
}
}
// Test Driver
var d = new DynamicArray();
for ( var i = 0; i < 7; i++ )
d.Add(i);
println("Expect 0,1,2,3,4,5,6");
for ( var i = 0; i < d.Size(); i++ )
println( d.Get(i) );
});
</script>
<body>
<div id='output'></div>
</body>
</pre>
<a name="dynamic2"></a>
<h4>Delete</h4>
<ul class="w3-navbar w3-light-grey" ng-init="dyn2[0] = true; dyn2cls[0] = 'w3-black'">
<li><a href="javascript:void(0)" ng-click="dyn2=[true,false,false,false]; dyn2cls=['w3-black','w3-lightgray','w3-lightgray','w3-lightgray']; Algo('dyn2')" ng-class='dyn2cls[0]'>Algorithm</a></li>
<li><a href="javascript:void(0)" ng-click="dyn2=[false,true,false,false]; dyn2cls=['w3-lightgray','w3-black','w3-lightgray','w3-lightgray']; Python('dyn2')" ng-class='dyn2cls[1]'>Python</a></li>
<li><a href="javascript:void(0)" ng-click="dyn2=[false,false,true,false]; dyn2cls=['w3-lightgray','w3-lightgray','w3-black','w3-lightgray']; Java('dyn2')" ng-class='dyn2cls[2]'>Java</a></li>
<li><a href="javascript:void(0)" ng-click="dyn2=[false,false,false,true]; dyn2cls=['w3-lightgray','w3-lightgray','w3-lightgray','w3-black']; Javascript('dyn2')" ng-class='dyn2cls[3]'>Javascript</a></li>
</ul>