Shuffle and Number of Good Pairs
excerpt: This covers the basic building blocks such as writing into string like array, nested for loops and nested loop with one index. tags: writing-into-string-array nested-for-loop nested-loop-with-one-index swap
This article covers the following basic building blocks:
- Writing into String like Array
- Nested For Loops
- Nested Loop with One Index
Shuffle Array
|
|
Shuffle String
Implement a method to shuffle a given string.
|
|
Building Blocks
- Writing into String like Array
Print all pairs of numbers in an array.
|
|
Building Block
- Nested For Loops
This can be applied to solve the problem: Number of Good Pairs. Just add a counter to the nested for loop that has the right bounds for the start and end indices.
|
|
Iterate through the list and swap adjacent elements if they are in the wrong order.
|
|
The inner loop starts from 1 more than the outer loop index and ends at the last element. The outer loop starts from the first element and goes till the element before the last one. The structure of the program is the same as the previous problem Number of Good Pairs. This algorithm is called the Bubble Sort.
We can rewrite the program to use one index variable:
|
|
The inner loop index starts at 0 and ends at one element before the last one.
Building Blocks
- Nested for Loop
- Nested Loop with One Index